/*!----------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Version: 0.17.0(63d87164d0bc8c6206d9339c195289c93665028e) * 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/nls","vs/base/browser/dom","vs/nls!vs/editor/editor.main","vs/css!vs/editor/editor.main","vs/base/common/errors","vs/editor/browser/editorExtensions","vs/editor/common/core/position","vs/platform/instantiation/common/instantiation","vs/platform/theme/common/themeService","vs/base/common/async","vs/editor/common/modes","vs/base/common/platform","vs/platform/contextkey/common/contextkey","vs/base/common/arrays","vs/base/common/types","vs/editor/common/editorContextKeys","vs/editor/common/core/selection","vs/platform/theme/common/colorRegistry","vs/base/common/cancellation","vs/base/common/uri","vs/base/browser/fastDomNode","vs/platform/commands/common/commands","vs/base/common/color","vs/editor/common/model/textModel","vs/base/browser/browser","vs/base/common/objects","vs/editor/browser/services/codeEditorService","vs/editor/browser/view/viewPart","vs/editor/common/view/editorColorRegistry","vs/platform/notification/common/notification","vs/base/common/keyCodes","vs/platform/keybinding/common/keybinding","vs/editor/common/controller/cursorCommon","vs/editor/common/modes/languageConfigurationRegistry","vs/platform/registry/common/platform","vs/platform/configuration/common/configuration","vs/editor/common/services/modelService","vs/base/browser/mouseEvent","vs/base/browser/ui/widget","vs/editor/common/model","vs/base/common/map","vs/base/browser/ui/aria/aria","vs/editor/common/config/editorOptions","vs/base/common/actions","vs/editor/common/standaloneStrings","vs/base/browser/ui/scrollbar/scrollableElement","vs/base/browser/keyboardEvent","vs/base/common/network","vs/base/common/resources","vs/editor/common/core/editOperation","vs/platform/opener/common/opener","vs/base/common/iterator","vs/platform/actions/common/actions","vs/platform/contextview/browser/contextView","vs/editor/browser/config/configuration","vs/editor/common/modes/nullMode","vs/base/browser/event","vs/editor/common/services/editorWorkerService","vs/editor/browser/core/editorState","vs/base/common/filters","vs/platform/markers/common/markers","vs/editor/common/services/modeService","vs/platform/storage/common/storage","vs/editor/common/viewModel/viewModel","vs/editor/common/editorCommon","vs/editor/browser/view/dynamicViewOverlay","vs/base/browser/globalMouseMoveMonitor","vs/editor/common/view/viewEvents","vs/base/common/path","vs/platform/accessibility/common/accessibility","vs/editor/common/core/characterClassifier","vs/editor/common/commands/replaceCommand","vs/base/browser/touch","vs/base/browser/ui/actionbar/actionbar","vs/editor/common/services/resolverService","vs/editor/common/modes/languageConfiguration","vs/editor/standalone/common/standaloneThemeService","vs/editor/common/controller/wordCharacterClassifier","vs/base/common/linkedList","vs/platform/theme/common/styler","vs/editor/common/viewModel/viewEventHandler","vs/base/common/htmlContent","vs/editor/common/view/renderingContext","vs/platform/configuration/common/configurationRegistry","vs/editor/contrib/referenceSearch/referencesModel","vs/platform/instantiation/common/serviceCollection","vs/platform/progress/common/progress","vs/editor/common/modes/modesRegistry","vs/editor/common/core/lineTokens","vs/platform/keybinding/common/keybindingsRegistry","vs/base/browser/ui/sash/sash","vs/platform/telemetry/common/telemetry","vs/editor/browser/services/bulkEditService","vs/editor/contrib/markdown/markdownRenderer","vs/editor/contrib/suggest/suggest","vs/editor/common/config/editorZoom","vs/editor/browser/widget/codeEditorWidget","vs/editor/common/core/token","vs/editor/common/core/uint","vs/editor/contrib/referenceSearch/peekViewWidget","vs/editor/browser/editorBrowser","vs/editor/common/model/wordHelper","vs/editor/common/viewLayout/viewLineRenderer","vs/platform/instantiation/common/extensions","vs/editor/common/view/minimapCharRenderer","vs/editor/contrib/parameterHints/provideSignatureHelp","vs/editor/common/config/commonEditorConfig","vs/editor/browser/editorDom","vs/editor/common/config/fontInfo","vs/editor/common/services/resourceConfiguration","vs/base/parts/tree/browser/treeDefaults","vs/base/browser/ui/list/listView","vs/editor/browser/widget/embeddedCodeEditorWidget","vs/base/browser/htmlContentRenderer","vs/base/parts/quickopen/browser/quickOpenModel","vs/editor/contrib/find/findModel","vs/base/common/stopwatch","vs/base/common/severity","vs/editor/common/core/stringBuilder","vs/platform/label/common/label","vs/base/browser/dnd","vs/editor/common/controller/cursorWordOperations","vs/editor/contrib/message/messageController","vs/base/common/range","vs/editor/common/controller/cursorTypeOperations","vs/editor/standalone/browser/quickOpen/editorQuickOpen","vs/editor/browser/controller/coreCommands","vs/base/browser/ui/scrollbar/scrollbarArrow","vs/base/browser/ui/tree/abstractTree","vs/base/browser/ui/list/listWidget","vs/base/browser/ui/inputbox/inputBox","vs/editor/common/model/textModelSearch","vs/platform/list/browser/listService","vs/base/common/numbers","vs/platform/log/common/log","vs/editor/contrib/referenceSearch/referencesWidget","vs/base/common/idGenerator","vs/editor/contrib/referenceSearch/referencesController","vs/editor/common/modes/supports","vs/editor/contrib/snippet/snippetParser","vs/editor/common/modes/supports/richEditBrackets","vs/base/common/diff/diff","vs/editor/common/standalone/standaloneEnums","vs/editor/contrib/folding/foldingRanges","vs/platform/workspace/common/workspace","vs/editor/contrib/codeAction/codeActionTrigger","vs/base/common/decorators","vs/editor/standalone/browser/simpleServices","vs/editor/common/viewLayout/lineDecorations","vs/base/browser/ui/iconLabel/iconLabel","vs/editor/browser/viewParts/glyphMargin/glyphMargin","vs/base/common/assert","vs/editor/common/viewModel/prefixSumComputer","vs/editor/contrib/snippet/snippetController2","vs/editor/browser/view/viewLayer","vs/editor/common/services/editorWorkerServiceImpl","vs/editor/contrib/wordOperations/wordOperations","vs/platform/layout/browser/layoutService","vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode","vs/editor/browser/controller/textAreaState","vs/editor/browser/widget/diffNavigator","vs/platform/keybinding/common/keybindingResolver","vs/base/browser/ui/scrollbar/abstractScrollbar","vs/base/browser/iframe","vs/editor/contrib/goToDefinition/goToDefinition","vs/editor/browser/controller/textAreaInput","vs/editor/contrib/colorPicker/colorDetector","vs/editor/contrib/colorPicker/color","vs/editor/contrib/codeAction/codeActionModel","vs/base/common/keybindingLabels","vs/platform/clipboard/common/clipboardService","vs/editor/contrib/codeAction/codeAction","vs/base/browser/ui/highlightedlabel/highlightedLabel","vs/editor/standalone/common/monarch/monarchLexer","vs/editor/common/viewModel/splitLinesCollection","vs/editor/common/editorAction","vs/editor/contrib/codeAction/codeActionCommands","vs/base/common/marshalling","vs/editor/contrib/suggest/suggestMemory","vs/base/browser/ui/tree/objectTree","vs/editor/common/modes/textToHtmlTokenizer","vs/editor/common/controller/cursorMoveCommands","vs/editor/contrib/codelens/codeLensCache","vs/base/browser/ui/findinput/findInputCheckboxes","vs/css!vs/editor/contrib/goToDefinition/goToDefinitionMouse","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase","vs/editor/standalone/browser/standaloneServices","vs/editor/common/controller/cursorDeleteOperations","vs/editor/common/controller/cursorMoveOperations","vs/editor/common/commands/shiftCommand","vs/base/browser/ui/scrollbar/scrollbarState","vs/editor/contrib/gotoError/gotoError","vs/editor/standalone/common/monarch/monarchCommon","vs/base/common/labels","vs/base/common/worker/simpleWorker","vs/editor/contrib/smartSelect/bracketSelections","vs/editor/contrib/hover/hoverWidgets","vs/editor/contrib/hover/hoverOperation","vs/editor/browser/widget/diffEditorWidget","vs/editor/contrib/goToDefinition/clickLinkGesture","vs/base/common/scrollable","vs/editor/contrib/format/formattingEdit","vs/editor/contrib/folding/syntaxRangeProvider","vs/base/browser/ui/tree/indexTreeModel","vs/editor/common/standalone/standaloneBase","vs/editor/common/services/markersDecorationService","vs/editor/common/view/overviewZoneManager","vs/editor/browser/viewParts/lineNumbers/lineNumbers","vs/editor/contrib/comment/blockCommentCommand","vs/platform/jsonschemas/common/jsonContributionRegistry","vs/base/browser/ui/tree/objectTreeModel","vs/editor/browser/controller/mouseTarget","vs/editor/browser/viewParts/lines/viewLine","vs/platform/instantiation/common/descriptors","vs/editor/browser/viewParts/margin/margin","vs/platform/files/common/files","vs/editor/contrib/find/findController","vs/base/common/extpath","vs/editor/contrib/goToDefinition/goToDefinitionCommands","vs/base/common/glob","vs/css!vs/editor/browser/widget/media/tokens","vs/editor/common/services/editorSimpleWorker","vs/editor/common/viewLayout/linesLayout","vs/editor/browser/viewParts/contentWidgets/contentWidgets","vs/editor/browser/viewParts/decorations/decorations","vs/editor/common/viewLayout/whitespaceComputer","vs/editor/browser/viewParts/linesDecorations/linesDecorations","vs/editor/common/viewLayout/viewLinesViewportData","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/view/viewEventDispatcher","vs/editor/common/viewLayout/viewLayout","vs/editor/common/viewModel/viewModelDecorations","vs/editor/contrib/caretOperations/moveCaretCommand","vs/editor/common/view/viewContext","vs/editor/contrib/codeAction/codeActionWidget","vs/editor/contrib/colorPicker/colorPickerModel","vs/editor/browser/viewParts/lines/rangeUtil","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/editor.all","vs/editor/contrib/folding/foldingModel","vs/editor/contrib/folding/hiddenRangeModel","vs/editor/common/modes/tokenizationRegistry","vs/editor/contrib/folding/intializingRangeProvider","vs/editor/common/modes/supports/tokenization","vs/editor/common/modes/supports/electricCharacter","vs/editor/common/modes/supports/onEnter","vs/editor/common/modes/supports/inplaceReplaceSupport","vs/editor/contrib/inPlaceReplace/inPlaceReplaceCommand","vs/editor/contrib/indentation/indentUtils","vs/editor/contrib/linesOperations/copyLinesCommand","vs/editor/contrib/linesOperations/sortLinesCommand","vs/editor/common/modes/supports/indentRules","vs/editor/contrib/smartSelect/wordSelections","vs/editor/common/modes/supports/characterPair","vs/editor/contrib/suggest/wordDistance","vs/editor/common/modes/linkComputer","vs/editor/standalone/common/monarch/monarchCompile","vs/nls!vs/base/browser/ui/actionbar/actionbar","vs/editor/common/modes/languageSelector","vs/editor/common/modes/abstractMode","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder","vs/nls!vs/base/browser/ui/aria/aria","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer","vs/nls!vs/base/browser/ui/findinput/findInput","vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes","vs/editor/common/model/textModelEvents","vs/nls!vs/base/browser/ui/inputbox/inputBox","vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase","vs/base/browser/ui/findinput/findInput","vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel","vs/nls!vs/base/browser/ui/list/listWidget","vs/editor/common/model/intervalTree","vs/nls!vs/base/browser/ui/menu/menu","vs/base/browser/ui/menu/menu","vs/nls!vs/base/browser/ui/tree/abstractTree","vs/editor/common/model/indentationGuesser","vs/base/browser/ui/tree/dataTree","vs/editor/common/model/editStack","vs/base/browser/ui/tree/asyncDataTree","vs/nls!vs/base/common/keybindingLabels","vs/editor/common/diff/diffComputer","vs/base/browser/ui/keybindingLabel/keybindingLabel","vs/nls!vs/base/common/severity","vs/editor/common/commands/surroundSelectionCommand","vs/nls!vs/base/parts/quickopen/browser/quickOpenModel","vs/editor/common/core/rgba","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/widget/codeEditorWidget","vs/nls!vs/editor/browser/widget/diffEditorWidget","vs/nls!vs/editor/browser/widget/diffReview","vs/nls!vs/editor/common/config/commonEditorConfig","vs/nls!vs/editor/common/config/editorOptions","vs/editor/common/commands/trimTrailingWhitespaceCommand","vs/editor/browser/services/abstractCodeEditorService","vs/editor/contrib/suggest/completionModel","vs/nls!vs/editor/common/modes/modesRegistry","vs/nls!vs/editor/common/standaloneStrings","vs/editor/browser/config/elementSizeObserver","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/comment/comment","vs/nls!vs/editor/contrib/contextmenu/contextmenu","vs/nls!vs/editor/contrib/cursorUndo/cursorUndo","vs/nls!vs/editor/contrib/find/findController","vs/nls!vs/editor/contrib/find/findWidget","vs/nls!vs/editor/contrib/folding/folding","vs/nls!vs/editor/contrib/fontZoom/fontZoom","vs/nls!vs/editor/contrib/format/format","vs/nls!vs/editor/contrib/format/formatActions","vs/nls!vs/editor/contrib/goToDefinition/goToDefinitionCommands","vs/nls!vs/editor/contrib/goToDefinition/goToDefinitionMouse","vs/nls!vs/editor/contrib/gotoError/gotoError","vs/nls!vs/editor/contrib/gotoError/gotoErrorWidget","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/referenceSearch/peekViewWidget","vs/nls!vs/editor/contrib/referenceSearch/referenceSearch","vs/nls!vs/editor/contrib/referenceSearch/referencesController","vs/nls!vs/editor/contrib/referenceSearch/referencesModel","vs/editor/browser/config/charWidthReader","vs/nls!vs/editor/contrib/referenceSearch/referencesTree","vs/nls!vs/editor/contrib/referenceSearch/referencesWidget","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/accessibility/common/accessibilityService","vs/platform/extensions/common/extensions","vs/css!vs/platform/contextview/browser/contextMenuHandler","vs/css!vs/editor/standalone/browser/standalone-tokens","vs/css!vs/editor/standalone/browser/quickOpen/quickOutline","vs/platform/instantiation/common/graph","vs/css!vs/editor/standalone/browser/quickOpen/gotoLine","vs/css!vs/editor/standalone/browser/quickOpen/editorQuickOpen","vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens","vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard","vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp","vs/css!vs/editor/contrib/zoneWidget/zoneWidget","vs/css!vs/editor/contrib/suggest/media/suggest","vs/editor/common/modes/languageFeatureRegistry","vs/css!vs/editor/contrib/snippet/snippetSession","vs/css!vs/editor/contrib/rename/renameInputField","vs/css!vs/editor/contrib/referenceSearch/media/referencesWidget","vs/editor/common/model/textModelTokens","vs/css!vs/editor/contrib/referenceSearch/media/peekViewWidget","vs/css!vs/editor/contrib/parameterHints/parameterHints","vs/css!vs/editor/contrib/message/messageController","vs/editor/common/controller/cursorColumnSelection","vs/css!vs/editor/contrib/links/links","vs/css!vs/editor/contrib/hover/hover","vs/css!vs/editor/contrib/gotoError/media/gotoErrorWidget","vs/css!vs/editor/contrib/folding/folding","vs/css!vs/editor/contrib/find/findWidget","vs/editor/common/controller/oneCursor","vs/editor/common/controller/cursorCollection","vs/editor/common/controller/cursor","vs/css!vs/editor/contrib/dnd/dnd","vs/css!vs/editor/contrib/colorPicker/colorPicker","vs/css!vs/editor/contrib/codelens/codelensWidget","vs/css!vs/editor/contrib/codeAction/lightBulbWidget","vs/editor/common/view/runtimeMinimapCharRenderer","vs/css!vs/editor/contrib/clipboard/clipboard","vs/editor/common/viewModel/characterHardWrappingLineMapper","vs/editor/common/viewModel/viewModelImpl","vs/editor/contrib/folding/foldingDecorations","vs/editor/contrib/folding/indentRangeProvider","vs/editor/contrib/linesOperations/moveLinesCommand","vs/editor/contrib/zoneWidget/zoneWidget","vs/css!vs/editor/contrib/bracketMatching/bracketMatching","vs/editor/standalone/browser/colorizer","vs/editor/common/model/mirrorTextModel","vs/css!vs/editor/browser/widget/media/editor","vs/css!vs/editor/browser/widget/media/diffReview","vs/css!vs/editor/browser/widget/media/diffEditor","vs/editor/browser/services/openerService","vs/editor/contrib/links/getLinks","vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors","vs/css!vs/editor/browser/viewParts/selections/selections","vs/editor/contrib/suggest/suggestAlternatives","vs/editor/contrib/suggest/wordContextKey","vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration","vs/platform/actions/common/menuService","vs/css!vs/editor/browser/viewParts/rulers/rulers","vs/platform/dialogs/common/dialogs","vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets","vs/platform/instantiation/common/instantiationService","vs/platform/keybinding/common/abstractKeybindingService","vs/platform/keybinding/common/baseResolvedKeybinding","vs/css!vs/editor/browser/viewParts/minimap/minimap","vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations","vs/platform/keybinding/common/resolvedKeybindingItem","vs/platform/keybinding/common/usLayoutResolvedKeybinding","vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations","vs/css!vs/editor/browser/viewParts/lines/viewLines","vs/platform/contextview/browser/contextViewService","vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers","vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides","vs/editor/common/services/webWorker","vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin","vs/platform/markers/common/markerService","vs/css!vs/editor/browser/viewParts/decorations/decorations","vs/css!vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight","vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight","vs/editor/contrib/hover/modesGlyphHover","vs/css!vs/editor/browser/controller/textAreaHandler","vs/base/parts/tree/browser/treeImpl","vs/css!vs/base/parts/tree/browser/tree","vs/editor/common/services/getIconClasses","vs/css!vs/base/parts/quickopen/browser/quickopen","vs/css!vs/base/browser/ui/tree/media/tree","vs/base/browser/ui/splitview/splitview","vs/css!vs/base/browser/ui/splitview/splitview","vs/editor/browser/view/viewOverlays","vs/editor/browser/viewParts/viewCursors/viewCursor","vs/editor/common/services/languagesRegistry","vs/editor/common/services/modeServiceImpl","vs/base/parts/tree/browser/treeView","vs/editor/common/services/modelServiceImpl","vs/platform/configuration/common/configurationModels","vs/platform/contextkey/browser/contextKeyService","vs/css!vs/base/browser/ui/scrollbar/media/scrollbars","vs/platform/browser/contextScopedHistoryWidget","vs/css!vs/base/browser/ui/sash/sash","vs/base/browser/ui/progressbar/progressbar","vs/css!vs/base/browser/ui/progressbar/progressbar","vs/css!vs/base/browser/ui/menu/menu","vs/css!vs/base/browser/ui/list/list","vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel","vs/editor/browser/view/viewController","vs/editor/contrib/caretOperations/caretOperations","vs/editor/contrib/caretOperations/transpose","vs/editor/contrib/clipboard/clipboard","vs/css!vs/base/browser/ui/inputbox/inputBox","vs/css!vs/base/browser/ui/iconLabel/iconlabel","vs/editor/contrib/codeAction/lightBulbWidget","vs/editor/contrib/codelens/codelens","vs/css!vs/base/browser/ui/findinput/findInputCheckboxes","vs/css!vs/base/browser/ui/findinput/findInput","vs/editor/contrib/comment/comment","vs/editor/contrib/contextmenu/contextmenu","vs/editor/contrib/cursorUndo/cursorUndo","vs/editor/contrib/dnd/dnd","vs/editor/contrib/folding/folding","vs/editor/contrib/fontZoom/fontZoom","vs/editor/contrib/format/format","vs/editor/contrib/format/formatActions","vs/base/browser/ui/countBadge/countBadge","vs/editor/contrib/hover/getHover","vs/editor/contrib/linesOperations/linesOperations","vs/css!vs/base/browser/ui/countBadge/countBadge","vs/editor/contrib/parameterHints/parameterHintsModel","vs/editor/contrib/quickOpen/quickOpen","vs/editor/contrib/smartSelect/smartSelect","vs/base/browser/ui/contextview/contextview","vs/css!vs/base/browser/ui/contextview/contextview","vs/editor/contrib/tokenization/tokenization","vs/base/browser/ui/checkbox/checkbox","vs/editor/contrib/wordPartOperations/wordPartOperations","vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard","vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast","vs/css!vs/base/browser/ui/checkbox/checkbox","vs/editor/contrib/rename/renameInputField","vs/css!vs/base/browser/ui/aria/aria","vs/editor/standalone/browser/quickOpen/quickOpenEditorWidget","vs/platform/contextview/browser/contextMenuHandler","vs/css!vs/base/browser/ui/actionbar/actionbar","vs/editor/browser/services/codeEditorServiceImpl","vs/editor/browser/viewParts/editorScrollbar/editorScrollbar","vs/base/worker/defaultWorkerFactory","vs/base/parts/tree/browser/treeViewModel","vs/editor/browser/controller/mouseHandler","vs/editor/browser/controller/pointerHandler","vs/editor/browser/view/viewOutgoingEvents","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/base/parts/tree/browser/treeModel","vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight","vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight","vs/editor/browser/viewParts/indentGuides/indentGuides","vs/base/parts/tree/browser/treeDnd","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/base/parts/tree/browser/tree","vs/editor/browser/widget/diffReview","vs/base/parts/quickopen/browser/quickOpenViewer","vs/editor/contrib/suggest/suggestController","vs/editor/common/services/markerDecorationsServiceImpl","vs/editor/contrib/bracketMatching/bracketMatching","vs/editor/contrib/codelens/codelensWidget","vs/editor/contrib/codelens/codelensController","vs/editor/contrib/colorPicker/colorPickerWidget","vs/editor/contrib/find/findDecorations","vs/base/common/mime","vs/editor/contrib/find/findOptionsWidget","vs/editor/contrib/find/findWidget","vs/base/browser/ui/octiconLabel/octiconLabel","vs/editor/contrib/inPlaceReplace/inPlaceReplace","vs/editor/contrib/links/links","vs/base/browser/ui/list/rangeMap","vs/base/common/process","vs/editor/contrib/codeAction/codeActionContributions","vs/editor/contrib/multicursor/multicursor","vs/editor/contrib/parameterHints/parameterHintsWidget","vs/editor/contrib/parameterHints/parameterHints","vs/base/browser/ui/scrollbar/verticalScrollbar","vs/editor/contrib/referenceSearch/referencesTree","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/base/browser/ui/scrollbar/horizontalScrollbar","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/base/browser/ui/list/rowCache","vs/base/browser/ui/scrollbar/scrollbarVisibilityController","vs/editor/contrib/gotoError/gotoErrorWidget","vs/base/common/history","vs/editor/contrib/hover/modesContentHover","vs/editor/contrib/hover/hover","vs/base/common/hash","vs/base/common/functional","vs/editor/contrib/goToDefinition/goToDefinitionMouse","vs/editor/contrib/referenceSearch/referenceSearch","vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch","vs/base/common/diff/diffChange","vs/base/common/collections","vs/editor/standalone/browser/standaloneCodeEditor","vs/base/browser/ui/list/splice","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/base/browser/ui/list/list","vs/editor/contrib/suggest/suggestModel","vs/base/common/marked/marked","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 === undefined || 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(undefined, [_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[126/*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[169/*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. *--------------------------------------------------------------------------------------------*/ define(__m[581/*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 = {})); }); /*--------------------------------------------------------------------------------------------- * 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/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[196/*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) { this._scrollbarSize = Math.round(scrollbarSize); this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize); this._arrowSize = Math.round(arrowSize); this._visibleSize = 0; this._scrollSize = 0; this._scrollPosition = 0; this._computedAvailableSize = 0; this._computedIsNeeded = false; this._computedSliderSize = 0; this._computedSliderRatio = 0; this._computedSliderPosition = 0; this._refreshComputedValues(); } ScrollbarState.prototype.clone = function () { var r = new ScrollbarState(this._arrowSize, this._scrollbarSize, this._oppositeScrollbarSize); r.setVisibleSize(this._visibleSize); r.setScrollSize(this._scrollSize); r.setScrollPosition(this._scrollPosition); return r; }; 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; }); 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 a new array with all falsy values removed. The original array IS NOT modified. */ function coalesce(array) { if (!array) { return 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; /** * @returns True if the provided object is an array and has at least one element. */ 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 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 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 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[157/*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[572/*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; /** * 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; }); /*--------------------------------------------------------------------------------------------- * 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/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) { return null; } 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) { if (!hex) { // Invalid color return null; } 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[152/*vs/base/common/decorators*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 = "$memoize$" + key; descriptor[fnKey] = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!this.hasOwnProperty(memoizeKey)) { Object.defineProperty(this, memoizeKey, { configurable: false, enumerable: false, writable: false, value: fn.apply(this, args) }); } return this[memoizeKey]; }; } exports.memoize = memoize; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[571/*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[147/*vs/base/common/diff/diff*/], __M([0/*require*/,1/*exports*/,571/*vs/base/common/diff/diffChange*/]), function (require, exports, diffChange_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function createStringSequence(a) { return { getLength: function () { return a.length; }, getElementAtIndex: function (pos) { return a.charCodeAt(pos); } }; } function stringDiff(original, modified, pretty) { return new LcsDiff(createStringSequence(original), createStringSequence(modified)).ComputeDiff(pretty); } 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]; } }; return MyArray; }()); exports.MyArray = MyArray; //***************************************************************************** // LcsDiff.cs // // An implementation of the difference algorithm described in // "An O(ND) Difference Algorithm and its variations" by Eugene W. Myers // // Copyright (C) 2008 Microsoft Corporation @minifier_do_not_preserve //***************************************************************************** // Our total memory usage for storing history is (worst-case): // 2 * [(MaxDifferencesHistory + 1) * (MaxDifferencesHistory + 1) - 1] * sizeof(int) // 2 * [1448*1448 - 1] * 4 = 16773624 = 16MB var MaxDifferencesHistory = 1447; //let MaxDifferencesHistory = 100; /** * 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 = Number.MAX_VALUE; this.m_modifiedStart = Number.MAX_VALUE; 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 = Number.MAX_VALUE; this.m_modifiedStart = Number.MAX_VALUE; }; /** * 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, newSequence, continueProcessingPredicate) { if (continueProcessingPredicate === void 0) { continueProcessingPredicate = null; } this.OriginalSequence = originalSequence; this.ModifiedSequence = newSequence; this.ContinueProcessingPredicate = continueProcessingPredicate; this.m_forwardHistory = []; this.m_reverseHistory = []; } LcsDiff.prototype.ElementsAreEqual = function (originalIndex, newIndex) { return (this.OriginalSequence.getElementAtIndex(originalIndex) === this.ModifiedSequence.getElementAtIndex(newIndex)); }; LcsDiff.prototype.OriginalElementsAreEqual = function (index1, index2) { return (this.OriginalSequence.getElementAtIndex(index1) === this.OriginalSequence.getElementAtIndex(index2)); }; LcsDiff.prototype.ModifiedElementsAreEqual = function (index1, index2) { return (this.ModifiedSequence.getElementAtIndex(index1) === this.ModifiedSequence.getElementAtIndex(index2)); }; LcsDiff.prototype.ComputeDiff = function (pretty) { return this._ComputeDiff(0, this.OriginalSequence.getLength() - 1, 0, this.ModifiedSequence.getLength() - 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 return this.PrettifyChanges(changes); } return 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], 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, 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 = Number.MIN_VALUE; var historyIndex = this.m_forwardHistory.length - 1; var diagonal; do { // Get the diagonal index from the relative diagonal number 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 = Number.MAX_VALUE; historyIndex = (deltaIsEven) ? this.m_reverseHistory.length - 1 : this.m_reverseHistory.length - 2; do { // Get the diagonal index from the relative diagonal number 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; var numDifferences; // 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 Array(numDiagonals); var reversePoints = new Array(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. var diagonal, tempOriginalIndex; for (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 (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 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] && MaxDifferencesHistory > 0 && numDifferences <= (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, this.OriginalSequence, 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 && MaxDifferencesHistory > 0 && numDifferences <= (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 (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 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] && MaxDifferencesHistory > 0 && numDifferences <= (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 <= MaxDifferencesHistory) { // We are allocating space for one extra int, which we fill with // the index of the diagonal base index var temp = new Array(diagonalForwardEnd - diagonalForwardStart + 2); temp[0] = diagonalForwardBase - diagonalForwardStart + 1; MyArray.Copy(forwardPoints, diagonalForwardStart, temp, 1, diagonalForwardEnd - diagonalForwardStart + 1); this.m_forwardHistory.push(temp); temp = new Array(diagonalReverseEnd - diagonalReverseStart + 2); temp[0] = diagonalReverseBase - diagonalReverseStart + 1; MyArray.Copy(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.OriginalSequence.getLength(); var modifiedStop = (i < changes.length - 1) ? changes[i + 1].modifiedStart : this.ModifiedSequence.getLength(); 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.OriginalSequence.getLength() - 1) { return true; } var element = this.OriginalSequence.getElementAtIndex(index); return (typeof element === 'string' && /^\s*$/.test(element)); }; 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.ModifiedSequence.getLength() - 1) { return true; } var element = this.ModifiedSequence.getElementAtIndex(index); return (typeof element === 'string' && /^\s*$/.test(element)); }; 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[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[567/*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[566/*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; } 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[87/*vs/base/common/htmlContent*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/]), function (require, exports, arrays_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MarkdownString = /** @class */ (function () { function MarkdownString(value) { if (value === void 0) { value = ''; } this.value = value; } MarkdownString.prototype.appendText = function (value) { // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash this.value += value.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); 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); } 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; } } function removeMarkdownEscapes(text) { if (!text) { return text; } return text.replace(/\\([\\`*_{}[\]()#+\-.!])/g, '$1'); } exports.removeMarkdownEscapes = removeMarkdownEscapes; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[142/*vs/base/common/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#'); }); /*--------------------------------------------------------------------------------------------- * 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[57/*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 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 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) { var result = []; forEach(iterator, function (value) { return result.push(value); }); return result; } Iterator.collect = collect; })(Iterator = exports.Iterator || (exports.Iterator = {})); function getSequenceIterator(arg) { if (Array.isArray(arg)) { return Iterator.fromArray(arg); } 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.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[563/*vs/base/common/history*/], __M([0/*require*/,1/*exports*/,57/*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(); this._navigator = new iterator_1.ArrayNavigator(this._elements, 0, this._elements.length, this._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; }); define(__m[2/*vs/base/common/lifecycle*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isDisposable(thing) { return typeof thing.dispose === 'function' && thing.dispose.length === 0; } exports.isDisposable = isDisposable; function dispose(first) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } if (Array.isArray(first)) { first.forEach(function (d) { return d && d.dispose(); }); return []; } else if (rest.length === 0) { if (first) { first.dispose(); return first; } return undefined; } else { dispose(first); dispose(rest); return []; } } exports.dispose = dispose; function combinedDisposable(disposables) { return { dispose: function () { return dispose(disposables); } }; } exports.combinedDisposable = combinedDisposable; function toDisposable(fn) { return { dispose: function () { fn(); } }; } exports.toDisposable = toDisposable; var Disposable = /** @class */ (function () { function Disposable() { this._toDispose = []; this._lifecycle_disposable_isDisposed = false; } Disposable.prototype.dispose = function () { this._lifecycle_disposable_isDisposed = true; this._toDispose = dispose(this._toDispose); }; Disposable.prototype._register = function (t) { if (this._lifecycle_disposable_isDisposed) { console.warn('Registering disposable on object that has already been disposed.'); t.dispose(); } else { this._toDispose.push(t); } return t; }; Disposable.None = Object.freeze({ dispose: function () { } }); return Disposable; }()); exports.Disposable = Disposable; 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[84/*vs/base/common/linkedList*/], __M([0/*require*/,1/*exports*/,57/*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._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*/,567/*vs/base/common/functional*/,2/*vs/base/common/lifecycle*/,84/*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) { var _disposable = { dispose: function () { } }; Event.None = function () { return _disposable; }; /** * 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 * throught 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(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 cummulative result throught 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); } 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.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 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 _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 (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[30/*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.isEdgeWebView = exports.isEdge && (userAgent.indexOf('WebView/') >= 0); function hasClipboardSupport() { if (exports.isIE) { return false; } if (exports.isEdge) { var index = userAgent.indexOf('Edge/'); var version = parseInt(userAgent.substring(index + 5, userAgent.indexOf('.', index)), 10); if (!version || (version >= 12 && version <= 16)) { return false; } } return true; } exports.hasClipboardSupport = hasClipboardSupport; }); /*--------------------------------------------------------------------------------------------- * 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/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. *--------------------------------------------------------------------------------------------*/ define(__m[209/*vs/base/browser/ui/tree/indexTreeModel*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,4/*vs/base/common/event*/,57/*vs/base/common/iterator*/]), function (require, exports, 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 treeNodeToElement(node) { var element = node.element, collapsed = node.collapsed; var children = iterator_1.Iterator.map(iterator_1.Iterator.fromArray(node.children), treeNodeToElement); return { element: element, children: children, collapsed: collapsed }; } var IndexTreeModel = /** @class */ (function () { function IndexTreeModel(list, rootElement, options) { if (options === void 0) { options = {}; } 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 _this = this; var _a; if (location.length === 0) { throw new Error('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, [lastIndex, deleteCount].concat(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.renderNodeCount; }, 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); } var result = iterator_1.Iterator.map(iterator_1.Iterator.fromArray(deletedNodes), treeNodeToElement); this._onDidSplice.fire({ insertedNodes: nodesToInsert, deletedNodes: deletedNodes }); return result; }; IndexTreeModel.prototype.rerender = function (location) { if (location.length === 0) { throw new Error('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.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.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; } return this.eventBufferer.bufferEvents(function () { return _this._setCollapsed(location, collapsed, recursive); }); }; IndexTreeModel.prototype._setCollapsed = function (location, collapsed, recursive) { var _a = this.getTreeNodeWithListIndex(location), node = _a.node, listIndex = _a.listIndex, revealed = _a.revealed; var result = this._setListNodeCollapsed(node, listIndex, revealed, collapsed, recursive || false); if (this.autoExpandSingleChildren && !collapsed && !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._setCollapsed(location.concat([onlyVisibleChildIndex]), false, false); } } return result; }; IndexTreeModel.prototype._setListNodeCollapsed = function (node, listIndex, revealed, collapsed, recursive) { var result = this._setNodeCollapsed(node, collapsed, recursive, false); if (!revealed || !node.visible) { 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._setNodeCollapsed = function (node, collapsed, recursive, deep) { var result = node.collapsible && node.collapsed !== collapsed; if (node.collapsible) { node.collapsed = collapsed; if (result) { this._onDidChangeCollapseState.fire({ node: node, deep: deep }); } } if (recursive) { for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; result = this._setNodeCollapsed(child, collapsed, true, 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._setCollapsed(location, 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; 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.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 Error('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 Error('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 Error('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 = []; while (node.parent) { location.push(node.parent.children.indexOf(node)); node = node.parent; } return location.reverse(); }; IndexTreeModel.prototype.getParentNodeLocation = function (location) { if (location.length <= 1) { return []; } 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); }; define(__m[216/*vs/base/browser/ui/tree/objectTreeModel*/], __M([0/*require*/,1/*exports*/,57/*vs/base/common/iterator*/,209/*vs/base/browser/ui/tree/indexTreeModel*/]), function (require, exports, iterator_1, indexTreeModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ObjectTreeModel = /** @class */ (function () { function ObjectTreeModel(list, options) { if (options === void 0) { options = {}; } this.nodes = new Map(); this.model = new indexTreeModel_1.IndexTreeModel(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); } }; } } ObjectTreeModel.prototype.setChildren = function (element, children, onDidCreateNode, onDidDeleteNode) { var location = this.getElementLocation(element); return this._setChildren(location, this.preserveCollapseState(children), onDidCreateNode, onDidDeleteNode); }; ObjectTreeModel.prototype._setChildren = function (location, children, onDidCreateNode, onDidDeleteNode) { var _this = this; var insertedElements = new Set(); var _onDidCreateNode = function (node) { insertedElements.add(node.element); _this.nodes.set(node.element, node); if (onDidCreateNode) { onDidCreateNode(node); } }; var _onDidDeleteNode = function (node) { if (!insertedElements.has(node.element)) { _this.nodes.delete(node.element); } if (onDidDeleteNode) { onDidDeleteNode(node); } }; return this.model.splice(location.concat([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(iterator_1.Iterator.collect(iterator).sort(this.sorter.compare.bind(this.sorter))); } return iterator_1.Iterator.map(iterator, function (treeElement) { var node = _this.nodes.get(treeElement.element); if (!node) { return __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({}, 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.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.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 Error("Tree element not found: " + element); } return node; }; ObjectTreeModel.prototype.getNodeLocation = function (node) { return node.element; }; ObjectTreeModel.prototype.getParentNodeLocation = function (element) { var node = this.nodes.get(element); if (!node) { throw new Error("Tree element not found: " + element); } return node.parent.element; }; ObjectTreeModel.prototype.getElementLocation = function (element) { if (element === null) { return []; } var node = this.nodes.get(element); if (!node) { throw new Error("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[49/*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 () { function Action(id, label, cssClass, enabled, actionCallback) { if (label === void 0) { label = ''; } if (cssClass === void 0) { cssClass = ''; } if (enabled === void 0) { enabled = true; } this._onDidChange = new event_1.Emitter(); this.onDidChange = this._onDidChange.event; this._id = id; this._label = label; this._cssClass = cssClass; this._enabled = enabled; this._actionCallback = actionCallback; } 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 }); Object.defineProperty(Action.prototype, "radio", { get: function () { return this._radio; }, set: function (value) { this._setRadio(value); }, enumerable: true, configurable: true }); Action.prototype._setChecked = function (value) { if (this._checked !== value) { this._checked = value; this._onDidChange.fire({ checked: value }); } }; Action.prototype._setRadio = function (value) { if (this._radio !== value) { this._radio = value; this._onDidChange.fire({ radio: value }); } }; Action.prototype.run = function (event, _data) { if (this._actionCallback) { return this._actionCallback(event); } return Promise.resolve(true); }; Action.prototype.dispose = function () { this._onDidChange.dispose(); }; return Action; }()); 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) { var _this = this; if (!action.enabled) { return Promise.resolve(null); } this._onDidBeforeRun.fire({ action: action }); return this.runAction(action, context).then(function (result) { _this._onDidRun.fire({ action: action, result: result }); }, function (error) { _this._onDidRun.fire({ action: action, error: error }); }); }; 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[24/*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 () { 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*/,24/*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; /** * 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.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; var task = _this.task; _this.task = null; return task(); }); } this.timeout = setTimeout(function () { _this.timeout = null; _this.doResolve(null); }, delay); return this.completionPromise; }; Delayer.prototype.isTriggered = function () { return this.timeout !== null; }; Delayer.prototype.cancel = function () { this.cancelTimeout(); if (this.completionPromise) { 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 (_super) { __extends(TimeoutTimer, _super); function TimeoutTimer(runner, timeout) { var _this = _super.call(this) || this; _this._token = -1; if (typeof runner === 'function' && typeof timeout === 'number') { _this.setIfNotSet(runner, timeout); } return _this; } TimeoutTimer.prototype.dispose = function () { this.cancel(); _super.prototype.dispose.call(this); }; 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; }(lifecycle_1.Disposable)); exports.TimeoutTimer = TimeoutTimer; var IntervalTimer = /** @class */ (function (_super) { __extends(IntervalTimer, _super); function IntervalTimer() { var _this = _super.call(this) || this; _this._token = -1; return _this; } IntervalTimer.prototype.dispose = function () { this.cancel(); _super.prototype.dispose.call(this); }; 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; }(lifecycle_1.Disposable)); 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[561/*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[46/*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() { } 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 */ || 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.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[53/*vs/base/common/network*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "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 = exports.Schemas || (exports.Schemas = {})); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[139/*vs/base/common/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[17/*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 _locale = undefined; var _language = LANGUAGE_DEFAULT; var _translationsConfigFile = 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) { var userAgent = navigator.userAgent; _isWindows = userAgent.indexOf('Windows') >= 0; _isMacintosh = userAgent.indexOf('Macintosh') >= 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 (_isNative) { 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; var _globals = (typeof self === 'object' ? self : typeof global === 'object' ? global : {}); exports.globals = _globals; var _setImmediate = null; function setImmediate(callback) { if (_setImmediate === null) { if (exports.globals.setImmediate) { _setImmediate = exports.globals.setImmediate.bind(exports.globals); } else if (typeof process !== 'undefined' && typeof process.nextTick === 'function') { _setImmediate = process.nextTick.bind(process); } else { _setImmediate = exports.globals.setTimeout.bind(exports.globals); } } return _setImmediate(callback); } exports.setImmediate = setImmediate; 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[52/*vs/base/browser/keyboardEvent*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,36/*vs/base/common/keyCodes*/,17/*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[43/*vs/base/browser/mouseEvent*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,169/*vs/base/browser/iframe*/,17/*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.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) { 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; } // 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; } // 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[7/*vs/base/browser/dom*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,62/*vs/base/browser/event*/,52/*vs/base/browser/keyboardEvent*/,43/*vs/base/browser/mouseEvent*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,19/*vs/base/common/arrays*/]), function (require, exports, browser, event_1, keyboardEvent_1, mouseEvent_1, async_1, errors_1, event_2, lifecycle_1, platform, arrays_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; } return false; } exports.isInDOM = isInDOM; var _manualClassList = new /** @class */ (function () { function class_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, useCapture) { this._node = node; this._type = type; this._handler = handler; this._useCapture = (useCapture || false); this._node.addEventListener(this._type, this._handler, this._useCapture); } DomListener.prototype.dispose = function () { if (!this._handler) { // Already disposed return; } this._node.removeEventListener(this._type, this._handler, this._useCapture); // Prevent leakers from holding on to the dom or handler func this._node = null; this._handler = null; }; return DomListener; }()); function addDisposableListener(node, type, handler, useCapture) { return new DomListener(node, type, handler, useCapture); } 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); }; 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 || e.target); while (toElement && toElement !== node) { toElement = toElement.parentNode; } if (toElement === node) { return; } handler(e); }); } exports.addDisposableNonBubblingMouseOutListener = addDisposableNonBubblingMouseOutListener; 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; 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, top = element.offsetTop, left = element.offsetLeft; while ((element = element.parentNode) !== null && element !== document.body && element !== document.documentElement) { top -= element.scrollTop; var c = 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) { 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 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', CONTEXT_MENU: 'contextmenu', WHEEL: 'wheel', // Keyboard KEY_DOWN: 'keydown', KEY_PRESS: 'keypress', KEY_UP: 'keyup', // HTML Document LOAD: 'load', UNLOAD: 'unload', ABORT: 'abort', ERROR: 'error', RESIZE: 'resize', SCROLL: 'scroll', // 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 () { function FocusTracker(element) { var _this = this; this._onDidFocus = new event_2.Emitter(); this.onDidFocus = this._onDidFocus.event; this._onDidBlur = new event_2.Emitter(); this.onDidBlur = this._onDidBlur.event; this.disposables = []; 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); } }; event_1.domEvent(element, exports.EventType.FOCUS, true)(onFocus, null, this.disposables); event_1.domEvent(element, exports.EventType.BLUR, true)(onBlur, null, this.disposables); } FocusTracker.prototype.dispose = function () { this.disposables = lifecycle_1.dispose(this.disposables); this._onDidFocus.dispose(); this._onDidBlur.dispose(); }; return FocusTracker; }()); 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\-]+))*)/; function $(description, attrs) { var children = []; for (var _i = 2; _i < arguments.length; _i++) { children[_i - 2] = arguments[_i]; } var match = SELECTOR_REGEX.exec(description); if (!match) { throw new Error('Bad use of emmet'); } var result = document.createElement(match[1] || 'div'); if (match[3]) { result.id = match[3]; } if (match[4]) { result.className = match[4].replace(/\./g, ' ').trim(); } attrs = attrs || {}; Object.keys(attrs).forEach(function (name) { var value = attrs[name]; 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; } exports.$ = $; 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) { 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; }); /*--------------------------------------------------------------------------------------------- * 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/browser/fastDomNode*/], __M([0/*require*/,1/*exports*/,7/*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._lineHeight = -1; this._letterSpacing = -100; this._className = ''; this._display = ''; this._position = ''; this._visibility = ''; this._layerHint = false; } 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.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.setLayerHinting = function (layerHint) { if (this._layerHint === layerHint) { return; } this._layerHint = layerHint; this.domNode.style.willChange = this._layerHint ? 'transform' : 'auto'; }; 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[72/*vs/base/browser/globalMouseMoveMonitor*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,169/*vs/base/browser/iframe*/,43/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom, iframe_1, mouseEvent_1, lifecycle_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, posx: ev.posx, posy: ev.posy }; } exports.standardMouseMoveMerger = standardMouseMoveMerger; var GlobalMouseMoveMonitor = /** @class */ (function (_super) { __extends(GlobalMouseMoveMonitor, _super); function GlobalMouseMoveMonitor() { var _this = _super.call(this) || this; _this.hooks = []; _this.mouseMoveEventMerger = null; _this.mouseMoveCallback = null; _this.onStopCallback = null; return _this; } GlobalMouseMoveMonitor.prototype.dispose = function () { this.stopMonitoring(false); _super.prototype.dispose.call(this); }; GlobalMouseMoveMonitor.prototype.stopMonitoring = function (invokeStopCallback) { if (!this.isMonitoring()) { // Not monitoring return; } // Unhook this.hooks = lifecycle_1.dispose(this.hooks); this.mouseMoveEventMerger = null; this.mouseMoveCallback = null; var onStopCallback = this.onStopCallback; this.onStopCallback = null; if (invokeStopCallback && onStopCallback) { onStopCallback(); } }; GlobalMouseMoveMonitor.prototype.isMonitoring = function () { return this.hooks.length > 0; }; GlobalMouseMoveMonitor.prototype.startMonitoring = function (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(); for (var _i = 0, windowChain_1 = windowChain; _i < windowChain_1.length; _i++) { var element = windowChain_1[_i]; this.hooks.push(dom.addDisposableThrottledListener(element.window.document, 'mousemove', function (data) { return _this.mouseMoveCallback(data); }, function (lastEvent, currentEvent) { return _this.mouseMoveEventMerger(lastEvent, currentEvent); })); this.hooks.push(dom.addDisposableListener(element.window.document, '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.push(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.push(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.push(dom.addDisposableListener(lastSameOriginAncestor.window.document.body, 'mouseleave', function (browserEvent) { _this.stopMonitoring(true); })); } }; return GlobalMouseMoveMonitor; }(lifecycle_1.Disposable)); exports.GlobalMouseMoveMonitor = GlobalMouseMoveMonitor; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; define(__m[78/*vs/base/browser/touch*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,7/*vs/base/browser/dom*/,152/*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.activeTouches = {}; _this.handle = null; _this.targets = []; _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; } if (!Gesture.INSTANCE) { Gesture.INSTANCE = new Gesture(); } Gesture.INSTANCE.targets.push(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; return event; }; Gesture.prototype.dispatchEvent = function (event) { var _this = this; 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; __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[560/*vs/base/browser/ui/list/rowCache*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/]), function (require, exports, dom_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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.garbageCollect = function () { var _this = this; if (!this.renderers) { return; } 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.dispose = function () { this.garbageCollect(); this.cache.clear(); this.renderers = null; // StrictNullOverride: nulling out ok in dispose }; 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[44/*vs/base/browser/ui/widget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,52/*vs/base/browser/keyboardEvent*/,43/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom, keyboardEvent_1, mouseEvent_1, lifecycle_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.onchange = function (domNode, listener) { this._register(dom.addDisposableListener(domNode, dom.EventType.CHANGE, listener)); }; 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[133/*vs/base/browser/ui/scrollbar/scrollbarArrow*/], __M([0/*require*/,1/*exports*/,72/*vs/base/browser/globalMouseMoveMonitor*/,44/*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(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[168/*vs/base/browser/ui/scrollbar/abstractScrollbar*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,26/*vs/base/browser/fastDomNode*/,72/*vs/base/browser/globalMouseMoveMonitor*/,133/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,561/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/,44/*vs/base/browser/ui/widget*/,17/*vs/base/common/platform*/]), function (require, exports, dom, fastDomNode_1, globalMouseMoveMonitor_1, scrollbarArrow_1, scrollbarVisibilityController_1, widget_1, platform) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * 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._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.domNode.domNode.appendChild(this.slider.domNode); this.onmousedown(this.slider.domNode, function (e) { if (e.leftButton) { e.preventDefault(); _this._sliderMouseDown(e, function () { }); } }); }; // ----------------- 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(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[552/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/], __M([0/*require*/,1/*exports*/,43/*vs/base/browser/mouseEvent*/,168/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,133/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,196/*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 = _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)), 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[545/*vs/base/browser/ui/scrollbar/verticalScrollbar*/], __M([0/*require*/,1/*exports*/,43/*vs/base/browser/mouseEvent*/,168/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,133/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,196/*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 = _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), 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. *--------------------------------------------------------------------------------------------*/ define(__m[540/*vs/base/common/process*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/]), function (require, exports, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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[74/*vs/base/common/path*/], __M([0/*require*/,1/*exports*/,540/*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; 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[129/*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[539/*vs/base/browser/ui/list/rangeMap*/], __M([0/*require*/,1/*exports*/,129/*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; }; RangeMap.prototype.dispose = function () { this.groups = null; // StrictNullOverride: nulling out ok in dispose }; 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[206/*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[122/*vs/base/common/stopwatch*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/]), function (require, exports, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 }); /** * The empty string. */ exports.empty = ''; 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 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) { var len1 = a ? a.length : 0; var len2 = b ? b.length : 0; if (len1 !== len2) { return false; } return doEqualsIgnoreCase(a, b); } exports.equalsIgnoreCase = equalsIgnoreCase; function doEqualsIgnoreCase(a, b, stopAt) { if (stopAt === void 0) { stopAt = a.length; } if (typeof a !== 'string' || typeof b !== 'string') { return false; } 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; /** * 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-\uDEF8]|\uD83E[\uDD00-\uDDE6])/; 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; // -- 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; }); /*--------------------------------------------------------------------------------------------- * 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/base/browser/ui/octiconLabel/octiconLabel*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function renderOcticons(text) { return strings_1.escape(text); } exports.renderOcticons = renderOcticons; }); define(__m[223/*vs/base/common/extpath*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,74/*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[65/*vs/base/common/filters*/], __M([0/*require*/,1/*exports*/,46/*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; } } 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 = 53; 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 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 } var FuzzyScore; (function (FuzzyScore) { /** * No matches and value `-100` */ FuzzyScore.Default = [-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, patternPos, word, wordLow, wordPos, firstMatchCanBeWeak) { var patternLen = pattern.length > _maxLen ? _maxLen : pattern.length; var wordLen = word.length > _maxLen ? _maxLen : word.length; if (patternPos >= patternLen || wordPos >= wordLen || patternLen > wordLen) { 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, patternPos, patternLen, wordLow, wordPos, wordLen)) { return undefined; } var patternStartPos = patternPos; var wordStartPos = wordPos; // There will be a mach, fill in tables for (patternPos = patternStartPos + 1; patternPos <= patternLen; patternPos++) { for (wordPos = 1; wordPos <= wordLen; wordPos++) { var score = -1; if (patternLow[patternPos - 1] === wordLow[wordPos - 1]) { if (wordPos === (patternPos - patternStartPos)) { // common prefix: `foobar <-> foobaz` // ^^^^^ if (pattern[patternPos - 1] === word[wordPos - 1]) { score = 7; } else { score = 5; } } else if (isUpperCaseAtPos(wordPos - 1, word, wordLow) && (wordPos === 1 || !isUpperCaseAtPos(wordPos - 2, word, wordLow))) { // hitting upper-case: `foo <-> forOthers` // ^^ ^ if (pattern[patternPos - 1] === word[wordPos - 1]) { score = 7; } else { score = 5; } } else if (isSeparatorAtPos(wordLow, wordPos - 2) || isWhitespaceAtPos(wordLow, wordPos - 2)) { // post separator: `foo <-> bar_foo` // ^^^ score = 5; } else { score = 1; } } _scores[patternPos][wordPos] = score; var diag = _table[patternPos - 1][wordPos - 1] + (score > 1 ? 1 : score); var top_1 = _table[patternPos - 1][wordPos] + -1; var left = _table[patternPos][wordPos - 1] + -1; if (left >= top_1) { // left or diag if (left > diag) { _table[patternPos][wordPos] = left; _arrows[patternPos][wordPos] = 4 /* Left */; } else if (left === diag) { _table[patternPos][wordPos] = left; _arrows[patternPos][wordPos] = 4 /* Left */ | 2 /* Diag */; } else { _table[patternPos][wordPos] = diag; _arrows[patternPos][wordPos] = 2 /* Diag */; } } else { // top or diag if (top_1 > diag) { _table[patternPos][wordPos] = top_1; _arrows[patternPos][wordPos] = 1 /* Top */; } else if (top_1 === diag) { _table[patternPos][wordPos] = top_1; _arrows[patternPos][wordPos] = 1 /* Top */ | 2 /* Diag */; } else { _table[patternPos][wordPos] = diag; _arrows[patternPos][wordPos] = 2 /* Diag */; } } } } if (_debug) { console.log(printTable(_table, pattern, patternLen, word, wordLen)); console.log(printTable(_arrows, pattern, patternLen, word, wordLen)); console.log(printTable(_scores, pattern, patternLen, word, wordLen)); } _matchesCount = 0; _topScore = -100; _patternStartPos = patternStartPos; _firstMatchCanBeWeak = firstMatchCanBeWeak; _findAllMatches2(patternLen, wordLen, patternLen === wordLen ? 1 : 0, 0, false); if (_matchesCount === 0) { return undefined; } return [_topScore, _topMatch2, wordStartPos]; } exports.fuzzyScore = fuzzyScore; var _matchesCount = 0; var _topMatch2 = 0; var _topScore = 0; var _patternStartPos = 0; var _firstMatchCanBeWeak = false; function _findAllMatches2(patternPos, wordPos, 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 (patternPos > _patternStartPos && wordPos > 0) { var score = _scores[patternPos][wordPos]; var arrow = _arrows[patternPos][wordPos]; if (arrow === 4 /* Left */) { // left -> no match, skip a word character wordPos -= 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(patternPos, wordPos - 1, matches !== 0 ? total - 1 : total, // gap penalty after first match matches, lastMatched); } // diag total += score; patternPos -= 1; wordPos -= 1; lastMatched = true; // match -> set a 1 at the word pos matches += Math.pow(2, wordPos); // count simple matches and boost a row of // simple matches when they yield in a // strong match. if (score === 1) { simpleMatchCount += 1; if (patternPos === _patternStartPos && !_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 -= wordPos >= 3 ? 9 : wordPos * 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[225/*vs/base/common/glob*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,5/*vs/base/common/strings*/,223/*vs/base/common/extpath*/,74/*vs/base/common/path*/,46/*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[533/*vs/base/common/mime*/], __M([0/*require*/,1/*exports*/,74/*vs/base/common/path*/,5/*vs/base/common/strings*/,225/*vs/base/common/glob*/]), function (require, exports, path_1, strings_1, glob_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(path, firstLine) { 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) { for (var _i = 0, registeredAssociations_1 = registeredAssociations; _i < registeredAssociations_1.length; _i++) { var association = registeredAssociations_1[_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[20/*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; 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; /** * 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*/,20/*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[178/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/], __M([0/*require*/,1/*exports*/,31/*vs/base/common/objects*/,536/*vs/base/browser/ui/octiconLabel/octiconLabel*/,5/*vs/base/common/strings*/]), function (require, exports, objects, octiconLabel_1, strings_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var HighlightedLabel = /** @class */ (function () { function HighlightedLabel(container, supportOcticons) { this.supportOcticons = supportOcticons; this.domNode = document.createElement('span'); this.domNode.className = 'monaco-highlighted-label'; this.didEverRender = false; 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.supportOcticons ? octiconLabel_1.renderOcticons(substring_1) : strings_1.escape(substring_1); htmlContent += ''; pos = highlight.end; } htmlContent += ''; var substring = this.text.substring(highlight.start, highlight.end); htmlContent += this.supportOcticons ? octiconLabel_1.renderOcticons(substring) : strings_1.escape(substring); htmlContent += ''; pos = highlight.end; } if (pos < this.text.length) { htmlContent += ''; var substring = this.text.substring(pos); htmlContent += this.supportOcticons ? octiconLabel_1.renderOcticons(substring) : strings_1.escape(substring); htmlContent += ''; } this.domNode.innerHTML = htmlContent; this.domNode.title = this.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[25/*vs/base/common/uri*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/]), function (require, exports, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _a; var _schemePattern = /^\w[\w\d+.-]*$/; var _singleSlashStart = /^\//; var _doubleSlashStart = /^\/\//; var _throwOnMissingSchema = true; function _validateUri(ret, _strict) { // scheme, must be set if (!ret.scheme) { if (_strict || _throwOnMissingSchema) { throw new Error("[UriError]: Scheme is missing: {scheme: \"\", authority: \"" + ret.authority + "\", path: \"" + ret.path + "\", query: \"" + ret.query + "\", fragment: \"" + ret.fragment + "\"}"); } else { console.warn("[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 (_strict || _throwOnMissingSchema) { return scheme || _empty; } if (!scheme) { console.trace('BAD uri lacks scheme, falling back to file-scheme.'); scheme = '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, decodeURIComponent(match[4] || _empty), decodeURIComponent(match[5] || _empty), decodeURIComponent(match[7] || _empty), decodeURIComponent(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._fsPath = data.fsPath; result._formatted = data.external; return result; } }; return URI; }()); exports.URI = URI; // tslint:disable-next-line:class-name 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; } 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; } }); /*--------------------------------------------------------------------------------------------- * 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/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, 0); return data; } exports.parse = parse; function revive(obj, depth) { 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[119/*vs/base/browser/htmlContentRenderer*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,142/*vs/base/common/idGenerator*/,5/*vs/base/common/strings*/,87/*vs/base/common/htmlContent*/,583/*vs/base/common/marked/marked*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,183/*vs/base/common/marshalling*/,31/*vs/base/common/objects*/]), function (require, exports, DOM, idGenerator_1, strings_1, htmlContent_1, marked, errors_1, uri_1, marshalling_1, objects_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function createElement(options) { var tagName = options.inline ? 'span' : 'div'; var element = document.createElement(tagName); if (options.className) { element.className = options.className; } return element; } 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; /** * Create html nodes for the given content element. */ function renderMarkdown(markdown, options) { if (options === void 0) { options = {}; } var element = 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) { var data = markdown.uris && markdown.uris[href]; if (!data) { return href; } var uri = uri_1.URI.revive(data); if (uri.query) { uri = uri.with({ query: _uriMassage(uri.query) }); } if (data) { href = uri.toString(true); } return href; }; // 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) { href = _href(href); var dimensions = []; if (href) { 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 + "\""); } } } var attributes = []; if (href) { attributes.push("src=\"" + href + "\""); } if (text) { attributes.push("alt=\"" + text + "\""); } if (title) { attributes.push("title=\"" + title + "\""); } if (dimensions.length) { attributes = attributes.concat(dimensions); } return ''; }; renderer.link = 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); 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 "

    " + 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) + "
    "; }; } if (options.actionHandler) { options.actionHandler.disposeables.push(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) { options.actionHandler.callback(href, event); } } catch (err) { errors_1.onUnexpectedError(err); } finally { event.preventDefault(); } })); } var markedOptions = { sanitize: true, renderer: renderer }; element.innerHTML = marked.parse(markdown.value, markedOptions); signalInnerHTML(); return element; } exports.renderMarkdown = renderMarkdown; // --- formatted string parsing 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.push(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 actionItemIndex = 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 = actionItemIndex; actionItemIndex++; } 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[54/*vs/base/common/resources*/], __M([0/*require*/,1/*exports*/,223/*vs/base/common/extpath*/,74/*vs/base/common/path*/,25/*vs/base/common/uri*/,5/*vs/base/common/strings*/,53/*vs/base/common/network*/,17/*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, [originalFSPath(resource)].concat(pathFragment))).path; } else { joinedPath = (_a = paths.posix).join.apply(_a, [resource.path || '/'].concat(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) { 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; } return paths.posix.relative(from.path || '/', to.path || '/'); } 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[199/*vs/base/common/labels*/], __M([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/,74/*vs/base/common/path*/,5/*vs/base/common/strings*/,53/*vs/base/common/network*/,17/*vs/base/common/platform*/,54/*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 && 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[200/*vs/base/common/worker/simpleWorker*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,20/*vs/base/common/types*/]), function (require, exports, errors_1, lifecycle_1, platform_1, types_1) { "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 (serializedMessage) { var message; try { message = JSON.parse(serializedMessage); } catch (e) { // nothing return; } 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 strMsg = JSON.stringify(msg); // console.log('SENDING: ' + strMsg); this._handler.sendMessage(strMsg); }; return SimpleWorkerProtocol; }()); /** * Main thread side */ var SimpleWorkerClient = /** @class */ (function (_super) { __extends(SimpleWorkerClient, _super); function SimpleWorkerClient(workerFactory, moduleId) { 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) { _this._worker.postMessage(msg); }, handleMessage: function (method, args) { // Intentionally not supporting worker -> main requests return Promise.resolve(null); } }); _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; } // Send initialize message _this._onModuleLoaded = _this._protocol.sendMessage(INITIALIZE, [ _this._worker.getId(), moduleId, loaderConfiguration ]); _this._lazyProxy = new Promise(function (resolve, reject) { lazyProxyReject = reject; _this._onModuleLoaded.then(function (availableMethods) { var proxy = {}; for (var _i = 0, availableMethods_1 = availableMethods; _i < availableMethods_1.length; _i++) { var methodName = availableMethods_1[_i]; proxy[methodName] = createProxyMethod(methodName, proxyMethodRequest); } resolve(proxy); }, function (e) { reject(e); _this._onError('Worker failed to load ' + moduleId, e); }); }); // Create proxy to loaded code var proxyMethodRequest = function (method, args) { return _this._request(method, args); }; var createProxyMethod = function (method, proxyMethodRequest) { return function () { var args = Array.prototype.slice.call(arguments, 0); return proxyMethodRequest(method, args); }; }; 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(postSerializedMessage, requestHandler) { var _this = this; this._requestHandler = requestHandler; this._protocol = new SimpleWorkerProtocol({ sendMessage: function (msg) { postSerializedMessage(msg); }, 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]); } 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, moduleId, loaderConfig) { var _this = this; this._protocol.setWorkerId(workerId); if (this._requestHandler) { // static request handler var methods = []; for (var _i = 0, _a = types_1.getAllPropertyNames(this._requestHandler); _i < _a.length; _i++) { var prop = _a[_i]; if (typeof this._requestHandler[prop] === 'function') { methods.push(prop); } } return Promise.resolve(methods); } 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 () { var result = []; for (var _i = 0; _i < arguments.length; _i++) { result[_i] = arguments[_i]; } var handlerModule = result[0]; _this._requestHandler = handlerModule.create(); if (!_this._requestHandler) { reject(new Error("No RequestHandler!")); return; } var methods = []; for (var _a = 0, _b = types_1.getAllPropertyNames(_this._requestHandler); _a < _b.length; _a++) { var prop = _b[_a]; if (typeof _this._requestHandler[prop] === 'function') { methods.push(prop); } } resolve(methods); }, 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[525/*vs/base/parts/quickopen/browser/quickOpenViewer*/], __M([0/*require*/,1/*exports*/,20/*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[523/*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[116/*vs/base/parts/tree/browser/treeDefaults*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,10/*vs/base/common/errors*/,7/*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[517/*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[513/*vs/base/parts/tree/browser/treeModel*/], __M([0/*require*/,1/*exports*/,157/*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 = null; // StrictNullOverride: nulling out ok in 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._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._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 () { if (this.registry) { this.registry.dispose(); this.registry = null; // StrictNullOverride: nulling out ok in 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[505/*vs/base/parts/tree/browser/treeViewModel*/], __M([0/*require*/,1/*exports*/,57/*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[504/*vs/base/worker/defaultWorkerFactory*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,200/*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); if (/^(http:)|(https:)|(file:)/.test(workerMain)) { 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 (workerMain.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 workerBaseUrl = workerMain.substr(0, workerMain.length - 'vs/base/worker/workerMain.js'.length); var js = "/*" + label + "*/self.MonacoEnvironment={baseUrl: '" + workerBaseUrl + "'};importScripts('" + workerMain + "');/*" + label + "*/"; var url = "data:text/javascript;charset=utf-8," + encodeURIComponent(js); return new Worker(url); } } return new Worker(workerMain + '#' + label); } // ESM-comment-end throw new Error("You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker"); } 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 (msg) { if (this.worker) { this.worker.then(function (w) { return w.postMessage(msg); }); } }; 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[501/*vs/css!vs/base/browser/ui/actionbar/actionbar*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[498/*vs/css!vs/base/browser/ui/aria/aria*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[496/*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[492/*vs/base/browser/ui/checkbox/checkbox*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,44/*vs/base/browser/ui/widget*/,28/*vs/base/common/color*/,4/*vs/base/common/event*/,31/*vs/base/common/objects*/,496/*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('#007ACC') }; 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._onKeyDown = _this._register(new event_1.Emitter()); _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 ' + (_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.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, "onChange", { get: function () { return this._onChange.event; }, enumerable: true, configurable: true }); Object.defineProperty(Checkbox.prototype, "onKeyDown", { get: function () { return this._onKeyDown.event; }, 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; } this.applyStyles(); }; Checkbox.prototype.applyStyles = function () { if (this.domNode) { this.domNode.style.borderColor = this._checked && this._opts.inputActiveOptionBorder ? this._opts.inputActiveOptionBorder.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[490/*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[489/*vs/base/browser/ui/contextview/contextview*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,129/*vs/base/common/range*/,490/*vs/css!vs/base/browser/ui/contextview/contextview*/]), function (require, exports, DOM, lifecycle_1, range_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.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) { lifecycle_1.dispose(this.toDisposeOnSetContainer); this.container.removeChild(this.view); this.container = null; } if (container) { this.container = container; this.container.appendChild(this.view); var toDisposeOnSetContainer_1 = []; ContextView.BUBBLE_UP_EVENTS.forEach(function (event) { toDisposeOnSetContainer_1.push(DOM.addStandardDisposableListener(_this.container, event, function (e) { _this.onDOMEvent(e, document.activeElement, false); })); }); ContextView.BUBBLE_DOWN_EVENTS.forEach(function (event) { toDisposeOnSetContainer_1.push(DOM.addStandardDisposableListener(_this.container, event, function (e) { _this.onDOMEvent(e, document.activeElement, true); }, true)); }); this.toDisposeOnSetContainer = lifecycle_1.combinedDisposable(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); // 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) { 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 { var realAnchor = anchor; around = { top: realAnchor.y, left: realAnchor.x, width: realAnchor.width || 1, height: realAnchor.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; } 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) { if (this.delegate && this.delegate.onHide) { this.delegate.onHide(data); } this.delegate = null; if (this.toDisposeOnClean) { this.toDisposeOnClean.dispose(); this.toDisposeOnClean = null; } DOM.hide(this.view); }; ContextView.prototype.isVisible = function () { return !!this.delegate; }; ContextView.prototype.onDOMEvent = function (e, element, 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[485/*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[482/*vs/base/browser/ui/countBadge/countBadge*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,5/*vs/base/common/strings*/,28/*vs/base/common/color*/,31/*vs/base/common/objects*/,485/*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.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() : null; var foreground = this.badgeForeground ? this.badgeForeground.toString() : null; var border = this.badgeBorder ? this.badgeBorder.toString() : null; this.element.style.backgroundColor = background; this.element.style.color = foreground; this.element.style.borderWidth = border ? '1px' : null; this.element.style.borderStyle = border ? 'solid' : null; this.element.style.borderColor = border; } }; return CountBadge; }()); exports.CountBadge = CountBadge; }); define(__m[473/*vs/css!vs/base/browser/ui/findinput/findInput*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[472/*vs/css!vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[469/*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[155/*vs/base/browser/ui/iconLabel/iconLabel*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,178/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,2/*vs/base/common/lifecycle*/,469/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/]), function (require, exports, dom, highlightedLabel_1, lifecycle_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' : null; }, 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')))); _this.labelDescriptionContainer = _this._register(new FastLabelNode(dom.append(_this.domNode.element, dom.$('.monaco-icon-label-description-container')))); if (options && options.supportHighlights) { _this.labelNode = new highlightedLabel_1.HighlightedLabel(dom.append(_this.labelDescriptionContainer.element, dom.$('a.label-name')), !options.donotSupportOcticons); } else { _this.labelNode = _this._register(new FastLabelNode(dom.append(_this.labelDescriptionContainer.element, dom.$('a.label-name')))); } if (options && options.supportDescriptionHighlights) { _this.descriptionNodeFactory = function () { return new highlightedLabel_1.HighlightedLabel(dom.append(_this.labelDescriptionContainer.element, dom.$('span.label-description')), !options.donotSupportOcticons); }; } else { _this.descriptionNodeFactory = function () { return _this._register(new FastLabelNode(dom.append(_this.labelDescriptionContainer.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 && options.title ? options.title : ''; if (this.labelNode instanceof highlightedLabel_1.HighlightedLabel) { this.labelNode.set(label || '', options ? options.matches : undefined, options && options.title ? options.title : undefined, options && options.labelEscapeNewLines); } else { this.labelNode.textContent = label || ''; } 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 && options.descriptionTitle) { this.descriptionNode.element.title = options.descriptionTitle; } else { this.descriptionNode.element.removeAttribute('title'); } } else { this.descriptionNode.textContent = description || ''; this.descriptionNode.title = options && options.descriptionTitle ? options.descriptionTitle : ''; this.descriptionNode.empty = !description; } } }; return IconLabel; }(lifecycle_1.Disposable)); exports.IconLabel = IconLabel; }); define(__m[468/*vs/css!vs/base/browser/ui/inputbox/inputBox*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[463/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[462/*vs/css!vs/base/browser/ui/list/list*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[461/*vs/css!vs/base/browser/ui/menu/menu*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[460/*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[459/*vs/base/browser/ui/progressbar/progressbar*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,28/*vs/base/common/color*/,31/*vs/base/common/objects*/,7/*vs/base/browser/dom*/,15/*vs/base/common/async*/,460/*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() : null; this.bit.style.backgroundColor = background; } }; return ProgressBar; }(lifecycle_1.Disposable)); exports.ProgressBar = ProgressBar; }); define(__m[458/*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. *--------------------------------------------------------------------------------------------*/ define(__m[96/*vs/base/browser/ui/sash/sash*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,30/*vs/base/browser/browser*/,17/*vs/base/common/platform*/,20/*vs/base/common/types*/,78/*vs/base/browser/touch*/,43/*vs/base/browser/mouseEvent*/,4/*vs/base/common/event*/,7/*vs/base/browser/dom*/,62/*vs/base/browser/event*/,458/*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.orthogonalEndSashDisposables = []; _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)); 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 http://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 = lifecycle_1.dispose(this.orthogonalStartSashDisposables); if (sash) { sash.onDidEnablementChange(this.onOrthogonalStartSashEnablementChange, this, this.orthogonalStartSashDisposables); 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 = lifecycle_1.dispose(this.orthogonalEndSashDisposables); if (sash) { sash.onDidEnablementChange(this.onOrthogonalEndSashEnablementChange, this, this.orthogonalEndSashDisposables); 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 (this.linkedSash && !e.__linkedSashEvent) { e.__linkedSashEvent = true; this.linkedSash.onMouseDown(e); } if (!e.__orthogonalSashEvent) { var orthogonalSash = void 0; if (this.orientation === 0 /* VERTICAL */) { if (e.offsetY <= 4) { orthogonalSash = this.orthogonalStartSash; } else if (e.offsetY >= this.el.clientHeight - 4) { orthogonalSash = this.orthogonalEndSash; } } else { if (e.offsetX <= 4) { orthogonalSash = this.orthogonalStartSash; } else if (e.offsetX >= this.el.clientWidth - 4) { orthogonalSash = this.orthogonalEndSash; } } if (orthogonalSash) { isMultisashResize = true; e.__orthogonalSashEvent = true; orthogonalSash.onMouseDown(e); } } if (!this.state) { return; } var iframes = dom_1.getElementsByTagName('iframe'); 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 = []; 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(); lifecycle_1.dispose(disposables); var iframes = dom_1.getElementsByTagName('iframe'); 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 (event) { 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.dispose = function () { _super.prototype.dispose.call(this); this.orthogonalStartSashDisposables = lifecycle_1.dispose(this.orthogonalStartSashDisposables); this.orthogonalEndSashDisposables = lifecycle_1.dispose(this.orthogonalEndSashDisposables); if (this.el && this.el.parentElement) { this.el.parentElement.removeChild(this.el); } this.el = null; // StrictNullOverride: nulling out ok in dispose }; return Sash; }(lifecycle_1.Disposable)); exports.Sash = Sash; }); define(__m[456/*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[51/*vs/base/browser/ui/scrollbar/scrollableElement*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,26/*vs/base/browser/fastDomNode*/,43/*vs/base/browser/mouseEvent*/,552/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/,545/*vs/base/browser/ui/scrollbar/verticalScrollbar*/,44/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,206/*vs/base/common/scrollable*/,456/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/]), function (require, exports, dom, fastDomNode_1, mouseEvent_1, horizontalScrollbar_1, verticalScrollbar_1, widget_1, async_1, event_1, lifecycle_1, platform, scrollable_1) { "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 * before last + 0.125 * before before 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); } _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, 'mousewheel', onMouseWheel)); } }; 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. *--------------------------------------------------------------------------------------------*/ define(__m[117/*vs/base/browser/ui/list/listView*/], __M([0/*require*/,1/*exports*/,31/*vs/base/common/objects*/,2/*vs/base/common/lifecycle*/,78/*vs/base/browser/touch*/,7/*vs/base/browser/dom*/,4/*vs/base/common/event*/,62/*vs/base/browser/event*/,51/*vs/base/browser/ui/scrollbar/scrollableElement*/,539/*vs/base/browser/ui/list/rangeMap*/,560/*vs/base/browser/ui/list/rowCache*/,17/*vs/base/common/platform*/,30/*vs/base/browser/browser*/,152/*vs/base/common/decorators*/,129/*vs/base/common/range*/,19/*vs/base/common/arrays*/,126/*vs/base/browser/dnd*/,15/*vs/base/common/async*/]), function (require, exports, objects_1, lifecycle_1, touch_1, DOM, event_1, event_2, scrollableElement_1, rangeMap_1, rowCache_1, platform_1, browser, decorators_1, range_1, arrays_1, dnd_1, async_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, [0, this.types.length].concat(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.scrollableElementUpdateDisposable = null; this.scrollableElementWidthDelayer = new async_1.Delayer(50); this.splicing = false; this.dragOverAnimationStopDisposable = lifecycle_1.Disposable.None; this.canUseTranslate3d = undefined; this.canDrop = false; this.currentDragFeedbackDisposable = lifecycle_1.Disposable.None; this.onDragLeaveTimeout = lifecycle_1.Disposable.None; 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 = 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.ariaSetProvider = options.ariaSetProvider || { getSetSize: function (e, i, length) { return length; }, getPosInSet: function (_, index) { return index + 1; } }; this.rowsContainer = document.createElement('div'); this.rowsContainer.className = 'monaco-list-rows'; touch_1.Gesture.addTarget(this.rowsContainer); this.scrollableElement = 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.disposables = [this.rangeMap, this.gesture, this.scrollableElement, this.cache]; 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 _this = this; var _a; 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, [start, deleteCount].concat(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 = [elementsRange].concat(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); } } var canUseTranslate3d = !platform_1.isWindows && !browser.isFirefox && browser.getZoomLevel() === 0; if (canUseTranslate3d) { var transform = "translate3d(-" + renderLeft + "px, -" + renderTop + "px, 0px)"; this.rowsContainer.style.transform = transform; this.rowsContainer.style.webkitTransform = transform; if (canUseTranslate3d !== this.canUseTranslate3d) { this.rowsContainer.style.left = '0'; this.rowsContainer.style.top = '0'; } } else { this.rowsContainer.style.left = "-" + renderLeft + "px"; this.rowsContainer.style.top = "-" + renderTop + "px"; if (canUseTranslate3d !== this.canUseTranslate3d) { this.rowsContainer.style.transform = ''; this.rowsContainer.style.webkitTransform = ''; } } if (this.horizontalScrolling) { this.rowsContainer.style.width = Math.max(scrollWidth, this.renderWidth) + "px"; } this.canUseTranslate3d = canUseTranslate3d; 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); item.row.domNode.setAttribute('role', 'treeitem'); } 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); } 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 = '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.ariaSetProvider.getSetSize(item.element, index, this.length))); item.row.domNode.setAttribute('aria-posinset', String(this.ariaSetProvider.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); } 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); }, 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); } 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(); feedback = feedback[0] === -1 ? [-1] : feedback; if (feedback.length === 0) { throw new Error('Invalid empty feedback list'); } 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'); this.currentDragFeedbackDisposable = lifecycle_1.toDisposable(function () { return DOM.removeClass(_this.domNode, '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 () { this.canDrop = false; this.teardownDragAndDropScrollTopAnimation(); this.clearDragOverFeedback(); this.currentDragData = undefined; dnd_1.StaticDND.CurrentDragAndDropData = undefined; }; 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, true); if (renderer.disposeElement) { renderer.disposeElement(item.element, index, row.templateData, true); } } 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); } this.disposables = 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[452/*vs/base/parts/tree/browser/treeView*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,30/*vs/base/browser/browser*/,2/*vs/base/common/lifecycle*/,7/*vs/base/browser/dom*/,147/*vs/base/common/diff/diff*/,78/*vs/base/browser/touch*/,5/*vs/base/common/strings*/,43/*vs/base/browser/mouseEvent*/,52/*vs/base/browser/keyboardEvent*/,517/*vs/base/parts/tree/browser/treeDnd*/,57/*vs/base/common/iterator*/,51/*vs/base/browser/ui/scrollbar/scrollableElement*/,505/*vs/base/parts/tree/browser/treeViewModel*/,523/*vs/base/parts/tree/browser/tree*/,4/*vs/base/common/event*/,126/*vs/base/browser/dnd*/,116/*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.unbindDragStart = Lifecycle.Disposable.None; 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('loading') : this.removeClass('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 = '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.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.dragAndDropScrollInterval = null; _this.dragAndDropScrollTimeout = null; _this.dragAndDropMouseY = null; _this.onHiddenScrollTop = null; _this._onDOMFocus = new event_1.Emitter(); _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 { 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; } Object.defineProperty(TreeView.prototype, "onDOMFocus", { get: function () { return this._onDOMFocus.event; }, enumerable: true, configurable: true }); 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({ getLength: function () { return previousChildrenIds_1.length; }, getElementAtIndex: function (i) { return previousChildrenIds_1[i]; } }, { getLength: function () { return afterModelItems_1.length; }, getElementAtIndex: function (i) { return afterModelItems_1[i].id; } }, null); diff = lcs.ComputeDiff(false); // 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(); } _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[447/*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. *--------------------------------------------------------------------------------------------*/ define(__m[446/*vs/base/browser/ui/splitview/splitview*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/,20/*vs/base/common/types*/,7/*vs/base/browser/dom*/,139/*vs/base/common/numbers*/,19/*vs/base/common/arrays*/,96/*vs/base/browser/ui/sash/sash*/,28/*vs/base/common/color*/,62/*vs/base/browser/event*/,447/*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 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; })(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.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); 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 }); 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) { 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 layoutContainer = this.orientation === 0 /* VERTICAL */ ? function () { return item.container.style.height = item.size + "px"; } : function () { return item.container.style.width = item.size + "px"; }; var layout = function () { layoutContainer(); item.view.layout(item.size, _this.orientation); }; var viewSize; if (typeof size === 'number') { viewSize = size; } else if (size.type === 'split') { viewSize = this.getViewSize(size.index) / 2; } else { viewSize = view.minimumSize; } var item = { view: view, container: container, size: viewSize, layout: layout, disposable: 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 () { return _this._onDidSashReset.fire(arrays_1.firstIndex(_this.sashItems, function (item) { return item.sash === sash_2; })); }); 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 highPriorityIndex; if (typeof size !== 'number' && size.type === 'split') { highPriorityIndex = size.index; } this.relayout(index, highPriorityIndex); this.state = State.Idle; if (typeof size !== 'number' && size.type === 'distribute') { this.distributeViewSizes(); } }; SplitView.prototype.relayout = function (lowPriorityIndex, highPriorityIndex) { var contentSize = this.viewItems.reduce(function (r, i) { return r + i.size; }, 0); var lowPriorityIndexes = typeof lowPriorityIndex === 'number' ? [lowPriorityIndex] : undefined; var highPriorityIndexes = typeof highPriorityIndex === 'number' ? [highPriorityIndex] : undefined; this.resize(this.viewItems.length - 1, this.size - contentSize, undefined, lowPriorityIndexes, highPriorityIndexes); this.distributeEmptySpace(); this.layoutViews(); this.saveProportions(); }; SplitView.prototype.layout = function (size) { var _this = this; var previousSize = Math.max(this.size, this.contentSize); this.size = size; if (!this.proportions) { var indexes = arrays_1.range(this.viewItems.length); var lowPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].view.priority === 1 /* Low */; }); var highPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].view.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.view.minimumSize, item.view.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; 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.view.minimumSize - viewItem.size) / 2; maxDelta = (viewItem.view.maximumSize - viewItem.size) / 2; } else { var viewItem = _this.viewItems[index + 1]; minDelta = (viewItem.size - viewItem.view.maximumSize) / 2; maxDelta = (viewItem.size - viewItem.view.minimumSize) / 2; } } _this.sashDragState = { start: start, current: start, index: index, sizes: sizes, minDelta: minDelta, maxDelta: maxDelta, alt: alt, 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; this.sashDragState.current = current; var delta = current - start; var newDelta = this.resize(index, delta, sizes, undefined, undefined, minDelta, maxDelta); 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.view.maximumSize; var newMaxDelta = viewItem.size - viewItem.view.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(); }; 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.view.minimumSize, item.view.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 item = this.viewItems[index]; size = Math.round(size); size = numbers_1.clamp(size, item.view.minimumSize, item.view.maximumSize); var delta = size - item.size; if (delta !== 0 && index < this.viewItems.length - 1) { var downIndexes = arrays_1.range(index + 1, this.viewItems.length); var collapseDown = downIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].size - _this.viewItems[i].view.minimumSize); }, 0); var expandDown = downIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].view.maximumSize - _this.viewItems[i].size); }, 0); var deltaDown = numbers_1.clamp(delta, -expandDown, collapseDown); this.resize(index, deltaDown); delta -= deltaDown; } if (delta !== 0 && index > 0) { var upIndexes = arrays_1.range(index - 1, -1); var collapseUp = upIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].size - _this.viewItems[i].view.minimumSize); }, 0); var expandUp = upIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].view.maximumSize - _this.viewItems[i].size); }, 0); var deltaUp = numbers_1.clamp(-delta, -collapseUp, expandUp); this.resize(index - 1, deltaUp); } this.distributeEmptySpace(); this.layoutViews(); this.saveProportions(); this.state = State.Idle; }; SplitView.prototype.distributeViewSizes = function () { var size = Math.floor(this.size / this.viewItems.length); for (var i = 0; i < this.viewItems.length - 1; i++) { this.resizeView(i, size); } }; SplitView.prototype.getViewSize = function (index) { if (index < 0 || index >= this.viewItems.length) { return -1; } return this.viewItems[index].size; }; SplitView.prototype.resize = function (index, delta, sizes, lowPriorityIndexes, highPriorityIndexes, overloadMinDelta, overloadMaxDelta) { 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].view.minimumSize - sizes[i]); }, 0); var maxDeltaUp = upIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].view.maximumSize - sizes[i]); }, 0); var maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce(function (r, i) { return r + (sizes[i] - _this.viewItems[i].view.minimumSize); }, 0); var minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce(function (r, i) { return r + (sizes[i] - _this.viewItems[i].view.maximumSize); }, 0); var minDelta = Math.max(minDeltaUp, minDeltaDown, overloadMinDelta); var maxDelta = Math.min(maxDeltaDown, maxDeltaUp, 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.view.minimumSize, item.view.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.view.minimumSize, item.view.maximumSize); var viewDelta = size - downSizes[i]; deltaDown += viewDelta; item.size = size; } return delta; }; SplitView.prototype.distributeEmptySpace = function () { var contentSize = this.viewItems.reduce(function (r, i) { return r + i.size; }, 0); var emptyDelta = this.size - contentSize; for (var i = this.viewItems.length - 1; emptyDelta !== 0 && i >= 0; i--) { var item = this.viewItems[i]; var size = numbers_1.clamp(item.size + emptyDelta, item.view.minimumSize, item.view.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 this.viewItems.forEach(function (item) { return item.layout(); }); // Layout sashes this.sashItems.forEach(function (item) { return item.sash.layout(); }); // Update sashes enablement var previous = false; var collapsesDown = this.viewItems.map(function (i) { return previous = (i.size - i.view.minimumSize > 0) || previous; }); previous = false; var expandsDown = this.viewItems.map(function (i) { return previous = (i.view.maximumSize - i.size > 0) || previous; }); var reverseViews = this.viewItems.slice().reverse(); previous = false; var collapsesUp = reverseViews.map(function (i) { return previous = (i.size - i.view.minimumSize > 0) || previous; }).reverse(); previous = false; var expandsUp = reverseViews.map(function (i) { return previous = (i.view.maximumSize - i.size > 0) || previous; }).reverse(); this.sashItems.forEach(function (s, i) { var min = !(collapsesDown[i] && expandsUp[i + 1]); var max = !(expandsDown[i] && collapsesUp[i + 1]); if (min && max) { s.sash.state = 0 /* Disabled */; } else if (min && !max) { s.sash.state = 1 /* Minimum */; } else if (!min && max) { s.sash.state = 2 /* Maximum */; } else { s.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 position; } } return 0; }; SplitView.prototype.dispose = function () { _super.prototype.dispose.call(this); this.viewItems.forEach(function (i) { return i.disposable.dispose(); }); this.viewItems = []; this.sashItems.forEach(function (i) { return i.disposable.dispose(); }); this.sashItems = []; }; return SplitView; }(lifecycle_1.Disposable)); exports.SplitView = SplitView; }); define(__m[445/*vs/css!vs/base/browser/ui/tree/media/tree*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[444/*vs/css!vs/base/parts/quickopen/browser/quickopen*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[442/*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[441/*vs/base/parts/tree/browser/treeImpl*/], __M([0/*require*/,1/*exports*/,116/*vs/base/parts/tree/browser/treeDefaults*/,513/*vs/base/parts/tree/browser/treeModel*/,452/*vs/base/parts/tree/browser/treeView*/,4/*vs/base/common/event*/,28/*vs/base/common/color*/,31/*vs/base/common/objects*/,442/*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 && 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(); if (this.model !== null) { this.model.dispose(); this.model = null; // StrictNullOverride Nulling out ok in dispose } if (this.view !== null) { this.view.dispose(); this.view = null; // StrictNullOverride Nulling out ok in 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[440/*vs/css!vs/editor/browser/controller/textAreaHandler*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[438/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[437/*vs/css!vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[436/*vs/css!vs/editor/browser/viewParts/decorations/decorations*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[434/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[432/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[431/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[429/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[428/*vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[425/*vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[424/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[420/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[418/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[416/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[413/*vs/css!vs/editor/browser/viewParts/selections/selections*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[412/*vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[409/*vs/css!vs/editor/browser/widget/media/diffEditor*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[408/*vs/css!vs/editor/browser/widget/media/diffReview*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[407/*vs/css!vs/editor/browser/widget/media/editor*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[226/*vs/css!vs/editor/browser/widget/media/tokens*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[404/*vs/css!vs/editor/contrib/bracketMatching/bracketMatching*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[397/*vs/css!vs/editor/contrib/clipboard/clipboard*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[395/*vs/css!vs/editor/contrib/codeAction/lightBulbWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[394/*vs/css!vs/editor/contrib/codelens/codelensWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[393/*vs/css!vs/editor/contrib/colorPicker/colorPicker*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[392/*vs/css!vs/editor/contrib/dnd/dnd*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[388/*vs/css!vs/editor/contrib/find/findWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[387/*vs/css!vs/editor/contrib/folding/folding*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[190/*vs/css!vs/editor/contrib/goToDefinition/goToDefinitionMouse*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[386/*vs/css!vs/editor/contrib/gotoError/media/gotoErrorWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[385/*vs/css!vs/editor/contrib/hover/hover*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[384/*vs/css!vs/editor/contrib/links/links*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[382/*vs/css!vs/editor/contrib/message/messageController*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[381/*vs/css!vs/editor/contrib/parameterHints/parameterHints*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[380/*vs/css!vs/editor/contrib/referenceSearch/media/peekViewWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[378/*vs/css!vs/editor/contrib/referenceSearch/media/referencesWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[377/*vs/css!vs/editor/contrib/rename/renameInputField*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[376/*vs/css!vs/editor/contrib/snippet/snippetSession*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[374/*vs/css!vs/editor/contrib/suggest/media/suggest*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[373/*vs/css!vs/editor/contrib/zoneWidget/zoneWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[372/*vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[371/*vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[370/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[369/*vs/css!vs/editor/standalone/browser/quickOpen/editorQuickOpen*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[368/*vs/css!vs/editor/standalone/browser/quickOpen/gotoLine*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[366/*vs/css!vs/editor/standalone/browser/quickOpen/quickOutline*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[365/*vs/css!vs/editor/standalone/browser/standalone-tokens*/], __M([9/*vs/css!vs/editor/editor.main*/]), {}); define(__m[364/*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[345/*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.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.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.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, len = this._requests.length; i < len; i++) { var request = this._requests[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[i] = 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[312/*vs/editor/browser/config/elementSizeObserver*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ElementSizeObserver = /** @class */ (function (_super) { __extends(ElementSizeObserver, _super); function ElementSizeObserver(referenceDomElement, changeCallback) { var _this = _super.call(this) || this; _this.referenceDomElement = referenceDomElement; _this.changeCallback = changeCallback; _this.measureReferenceDomElementToken = -1; _this.width = -1; _this.height = -1; _this.measureReferenceDomElement(false); 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.measureReferenceDomElementToken === -1) { this.measureReferenceDomElementToken = setInterval(function () { return _this.measureReferenceDomElement(true); }, 100); } }; ElementSizeObserver.prototype.stopObserving = function () { if (this.measureReferenceDomElementToken !== -1) { clearInterval(this.measureReferenceDomElementToken); this.measureReferenceDomElementToken = -1; } }; ElementSizeObserver.prototype.observe = function (dimension) { this.measureReferenceDomElement(true, dimension); }; 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[64/*vs/editor/browser/core/editorState*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,24/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/]), function (require, exports, strings, cancellation_1, lifecycle_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; } if ((this.flags & 4 /* Position */) !== 0) { this.position = editor.getPosition(); } if ((this.flags & 2 /* Selection */) !== 0) { this.selection = editor.getSelection(); } if ((this.flags & 8 /* Scroll */) !== 0) { this.scrollLeft = editor.getScrollLeft(); this.scrollTop = editor.getScrollTop(); } } 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, parent) || this; _this.editor = editor; _this._listener = []; if (flags & 4 /* Position */) { _this._listener.push(editor.onDidChangeCursorPosition(function (_) { return _this.cancel(); })); } if (flags & 2 /* Selection */) { _this._listener.push(editor.onDidChangeCursorSelection(function (_) { return _this.cancel(); })); } if (flags & 8 /* Scroll */) { _this._listener.push(editor.onDidScrollChange(function (_) { return _this.cancel(); })); } if (flags & 1 /* Value */) { _this._listener.push(editor.onDidChangeModel(function (_) { return _this.cancel(); })); _this._listener.push(editor.onDidChangeModelContent(function (_) { return _this.cancel(); })); } return _this; } EditorStateCancellationTokenSource.prototype.dispose = function () { lifecycle_1.dispose(this._listener); _super.prototype.dispose.call(this); }; return EditorStateCancellationTokenSource; }(cancellation_1.CancellationTokenSource)); 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[113/*vs/editor/browser/editorDom*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,72/*vs/base/browser/globalMouseMoveMonitor*/,43/*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 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 (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(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[308/*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._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[101/*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[12/*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 postion 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*/,12/*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; }; /** * 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[165/*vs/editor/browser/controller/textAreaState*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,12/*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, couldBeTypingAtOffset0) { 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; if (couldBeTypingAtOffset0 && previousValue.length > 0 && previousSelectionStart === previousSelectionEnd && currentSelectionStart === currentSelectionEnd) { // See https://github.com/Microsoft/vscode/issues/42251 // where typing always happens at offset 0 in the textarea // when using a custom title area in OSX and moving the window if (!strings.startsWith(currentValue, previousValue) && strings.endsWith(currentValue, previousValue)) { // Looks like something was typed at offset 0 // ==> pretend we placed the cursor at offset 0 to begin with... previousSelectionStart = 0; previousSelectionEnd = 0; } } // 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) { return Math.floor((lineNumber - 1) / PagedScreenReaderStrategy._LINES_PER_PAGE); }; PagedScreenReaderStrategy._getRangeForPage = function (page) { var offset = page * PagedScreenReaderStrategy._LINES_PER_PAGE; var startLineNumber = offset + 1; var endLineNumber = offset + PagedScreenReaderStrategy._LINES_PER_PAGE; return new range_1.Range(startLineNumber, 1, endLineNumber + 1, 1); }; PagedScreenReaderStrategy.fromEditorSelection = function (previousState, model, selection, trimLongText) { var selectionStartPage = PagedScreenReaderStrategy._getPageOfLine(selection.startLineNumber); var selectionStartPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionStartPage); var selectionEndPage = PagedScreenReaderStrategy._getPageOfLine(selection.endLineNumber); var selectionEndPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionEndPage); 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)); }; PagedScreenReaderStrategy._LINES_PER_PAGE = 10; 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[166/*vs/editor/browser/widget/diffNavigator*/], __M([0/*require*/,1/*exports*/,157/*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 () { function DiffNavigator(editor, options) { var _this = this; if (options === void 0) { options = {}; } this._onDidUpdate = new event_1.Emitter(); this._editor = editor; this._options = objects.mixin(options, defaultOptions, false); this.disposed = false; this._disposables = []; 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._disposables.push(this._editor.onDidDispose(function () { return _this.dispose(); })); this._disposables.push(this._editor.onDidUpdateDiff(function () { return _this._onDiffUpdated(); })); if (this._options.followsCaret) { this._disposables.push(this._editor.getModifiedEditor().onDidChangeCursorPosition(function (e) { if (_this.ignoreSelectionChange) { return; } _this.nextIdx = -1; })); } if (this._options.alwaysRevealFirst) { this._disposables.push(this._editor.getModifiedEditor().onDidChangeModel(function (e) { _this.revealFirst = true; })); } // init things this._init(); } 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 () { lifecycle_1.dispose(this._disposables); this._disposables.length = 0; this._onDidUpdate.dispose(); this.ranges = []; this.disposed = true; }; return DiffNavigator; }()); 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[55/*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[307/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,55/*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; } 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[298/*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*/,12/*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; } /** * Clone this selection. */ Selection.prototype.clone = function () { return new Selection(this.selectionStartLineNumber, this.selectionStartColumn, this.positionLineNumber, this.positionColumn); }; /** * 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[171/*vs/editor/browser/controller/textAreaInput*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,15/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,5/*vs/base/common/strings*/,165/*vs/editor/browser/controller/textAreaState*/,22/*vs/editor/common/core/selection*/]), function (require, exports, browser, dom, async_1, event_1, lifecycle_1, platform, strings, textAreaState_1, selection_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CopyOptions = { forceCopyWithSyntaxHighlighting: false }; /** * 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._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._lastTextAreaEvent = 0 /* none */; _this._asyncTriggerCut = _this._register(new async_1.RunOnceScheduler(function () { return _this._onCut.fire(); }, 0)); _this._textAreaState = textAreaState_1.TextAreaState.EMPTY; _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) { _this._lastTextAreaEvent = 1 /* compositionstart */; 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, couldBeTypingAtOffset0) { var oldState = _this._textAreaState; var newState = textAreaState_1.TextAreaState.readFromTextArea(_this._textArea); return [newState, textAreaState_1.TextAreaState.deduceInput(oldState, newState, couldBeEmojiInput, couldBeTypingAtOffset0)]; }; /** * 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) { _this._lastTextAreaEvent = 2 /* compositionupdate */; if (compositionDataInValid(e.locale)) { var _a = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ false, /*couldBeTypingAtOffset0*/ 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) { _this._lastTextAreaEvent = 3 /* compositionend */; if (compositionDataInValid(e.locale)) { // https://github.com/Microsoft/monaco-editor/issues/339 var _a = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ false, /*couldBeTypingAtOffset0*/ 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 () { // We want to find out if this is the first `input` after a `focus`. var previousEventWasFocus = (_this._lastTextAreaEvent === 8 /* focus */); _this._lastTextAreaEvent = 4 /* input */; // Pretend here we touched the text area, as the `input` event will most likely // result in a `selectionchange` event which we want to ignore _this._textArea.setIgnoreSelectionChangeTime('received input event'); if (_this._isDoingComposition) { return; } var _a = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ platform.isMacintosh, /*couldBeTypingAtOffset0*/ previousEventWasFocus && 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 !== '') { _this._onPaste.fire({ text: typeInput.text }); } _this._nextCommand = 0 /* Type */; } })); // --- Clipboard operations _this._register(dom.addDisposableListener(textArea.domNode, 'cut', function (e) { _this._lastTextAreaEvent = 5 /* cut */; // 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._lastTextAreaEvent = 6 /* copy */; _this._ensureClipboardGetsEditorSelection(e); })); _this._register(dom.addDisposableListener(textArea.domNode, 'paste', function (e) { _this._lastTextAreaEvent = 7 /* paste */; // 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 pastePlainText = ClipboardEventUtils.getTextData(e); if (pastePlainText !== '') { _this._onPaste.fire({ text: pastePlainText }); } } 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._lastTextAreaEvent = 8 /* focus */; _this._setHasFocus(true); })); _this._register(dom.addDisposableListener(textArea.domNode, 'blur', function () { _this._lastTextAreaEvent = 9 /* blur */; _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); }; TextAreaInput.prototype.isFocused = function () { return this._hasFocus; }; 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 copyPlainText = this._host.getPlainTextToCopy(); 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(copyPlainText)); return; } var copyHTML = null; if (browser.hasClipboardSupport() && (copyPlainText.length < 65536 || exports.CopyOptions.forceCopyWithSyntaxHighlighting)) { copyHTML = this._host.getHTMLToCopy(); } ClipboardEventUtils.setTextData(e, copyPlainText, copyHTML); }; 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(); return e.clipboardData.getData('text/plain'); } if (window.clipboardData) { e.preventDefault(); return window.clipboardData.getData('Text'); } throw new Error('ClipboardEventUtils.getTextData: Cannot use text data!'); }; ClipboardEventUtils.setTextData = function (e, text, richText) { if (e.clipboardData) { e.clipboardData.setData('text/plain', text); if (richText !== null) { e.clipboardData.setData('text/html', richText); } 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 currentIsFocused = (document.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[77/*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 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) { this._range = editRange; this._text = text; this._initialSelection = initialSelection; } ReplaceCommandThatPreservesSelection.prototype.getEditOperations = function (model, builder) { builder.addEditOperation(this._range, this._text); 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[296/*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[124/*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[160/*vs/editor/browser/view/viewLayer*/], __M([0/*require*/,1/*exports*/,26/*vs/base/browser/fastDomNode*/,124/*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) { return e.layoutInfo; }; 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[103/*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[104/*vs/editor/common/core/uint*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "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; 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; function toUint32Array(arr) { var len = arr.length; var r = new Uint32Array(len); for (var i = 0; i < len; i++) { r[i] = toUint32(arr[i]); } return r; } exports.toUint32Array = toUint32Array; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[76/*vs/editor/common/core/characterClassifier*/], __M([0/*require*/,1/*exports*/,104/*vs/editor/common/core/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[83/*vs/editor/common/controller/wordCharacterClassifier*/], __M([0/*require*/,1/*exports*/,76/*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[293/*vs/editor/common/diff/diffComputer*/], __M([0/*require*/,1/*exports*/,147/*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 MAXIMUM_RUN_TIME = 5000; // 5 seconds 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 LineMarkerSequence = /** @class */ (function () { function LineMarkerSequence(lines) { var startColumns = []; var endColumns = []; for (var i = 0, length_1 = lines.length; i < length_1; i++) { startColumns[i] = LineMarkerSequence._getFirstNonBlankColumn(lines[i], 1); endColumns[i] = LineMarkerSequence._getLastNonBlankColumn(lines[i], 1); } this._lines = lines; this._startColumns = startColumns; this._endColumns = endColumns; } LineMarkerSequence.prototype.getLength = function () { return this._lines.length; }; LineMarkerSequence.prototype.getElementAtIndex = function (i) { return this._lines[i].substring(this._startColumns[i] - 1, this._endColumns[i] - 1); }; LineMarkerSequence.prototype.getStartLineNumber = function (i) { return i + 1; }; LineMarkerSequence.prototype.getEndLineNumber = function (i) { return i + 1; }; LineMarkerSequence._getFirstNonBlankColumn = function (txt, defaultValue) { var r = strings.firstNonWhitespaceIndex(txt); if (r === -1) { return defaultValue; } return r + 1; }; LineMarkerSequence._getLastNonBlankColumn = function (txt, defaultValue) { var r = strings.lastNonWhitespaceIndex(txt); if (r === -1) { return defaultValue; } return r + 2; }; LineMarkerSequence.prototype.getCharSequence = 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 LineMarkerSequence; }()); var CharSequence = /** @class */ (function () { function CharSequence(charCodes, lineNumbers, columns) { this._charCodes = charCodes; this._lineNumbers = lineNumbers; this._columns = columns; } CharSequence.prototype.getLength = function () { return this._charCodes.length; }; CharSequence.prototype.getElementAtIndex = function (i) { return this._charCodes[i]; }; 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, continueProcessingPredicate, 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.modifiedLength !== 0 && continueProcessingPredicate()) { var originalCharSequence = originalLineSequence.getCharSequence(shouldIgnoreTrimWhitespace, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1); var modifiedCharSequence = modifiedLineSequence.getCharSequence(shouldIgnoreTrimWhitespace, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1); var rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueProcessingPredicate, true); 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.maximumRunTimeMs = MAXIMUM_RUN_TIME; this.originalLines = originalLines; this.modifiedLines = modifiedLines; this.original = new LineMarkerSequence(originalLines); this.modified = new LineMarkerSequence(modifiedLines); } DiffComputer.prototype.computeDiff = function () { if (this.original.getLength() === 1 && this.original.getElementAtIndex(0).length === 0) { // empty original => fast path return [{ originalStartLineNumber: 1, originalEndLineNumber: 1, modifiedStartLineNumber: 1, modifiedEndLineNumber: this.modified.getLength(), charChanges: [{ modifiedEndColumn: 0, modifiedEndLineNumber: 0, modifiedStartColumn: 0, modifiedStartLineNumber: 0, originalEndColumn: 0, originalEndLineNumber: 0, originalStartColumn: 0, originalStartLineNumber: 0 }] }]; } if (this.modified.getLength() === 1 && this.modified.getElementAtIndex(0).length === 0) { // empty modified => fast path return [{ originalStartLineNumber: 1, originalEndLineNumber: this.original.getLength(), modifiedStartLineNumber: 1, modifiedEndLineNumber: 1, charChanges: [{ modifiedEndColumn: 0, modifiedEndLineNumber: 0, modifiedStartColumn: 0, modifiedStartLineNumber: 0, originalEndColumn: 0, originalEndLineNumber: 0, originalStartColumn: 0, originalStartLineNumber: 0 }] }]; } this.computationStartTime = (new Date()).getTime(); var rawChanges = computeDiff(this.original, this.modified, this._continueProcessingPredicate.bind(this), this.shouldMakePrettyDiff); // 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._continueProcessingPredicate.bind(this), this.shouldComputeCharChanges, this.shouldPostProcessCharChanges)); } return 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 = LineMarkerSequence._getFirstNonBlankColumn(originalLine, 1); var modifiedStartColumn = LineMarkerSequence._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 = LineMarkerSequence._getLastNonBlankColumn(originalLine, 1); var modifiedEndColumn = LineMarkerSequence._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._continueProcessingPredicate.bind(this), this.shouldComputeCharChanges, this.shouldPostProcessCharChanges)); originalLineIndex += nextChange.originalLength; modifiedLineIndex += nextChange.modifiedLength; } } return 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.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn)); } return true; } return false; }; DiffComputer.prototype._continueProcessingPredicate = function () { if (this.maximumRunTimeMs === 0) { return true; } var now = (new Date()).getTime(); return now - this.computationStartTime < this.maximumRunTimeMs; }; return DiffComputer; }()); exports.DiffComputer = DiffComputer; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[181/*vs/editor/common/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[70/*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[106/*vs/editor/browser/editorBrowser*/], __M([0/*require*/,1/*exports*/,70/*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[45/*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 = {})); var TextModelResolvedOptions = /** @class */ (function () { /** * @internal */ function TextModelResolvedOptions(src) { this.tabSize = 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[290/*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[288/*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() { } 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 */) { // 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) { // skip this line entirely 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; var tabSizeScore = (insertSpaces ? 0 : 0.1 * linesCount); // console.log("score threshold: " + tabSizeScore); ALLOWED_TAB_SIZE_GUESSES.forEach(function (possibleTabSize) { var possibleTabSizeScore = spacesDiffCount[possibleTabSize]; if (possibleTabSizeScore > tabSizeScore) { tabSizeScore = possibleTabSizeScore; tabSize = possibleTabSize; } }); // Let a tabSize of 2 win even if it is not the maximum // (only in case 4 was guessed) if (tabSize === 4 && spacesDiffCount[4] > 0 && spacesDiffCount[2] > 0 && spacesDiffCount[2] >= spacesDiffCount[4] / 2) { tabSize = 2; } // console.log('--------------------------'); // console.log('linesIndentedWithTabsCount: ' + linesIndentedWithTabsCount + ', linesIndentedWithSpacesCount: ' + linesIndentedWithSpacesCount); // console.log('spacesDiffCount: ' + spacesDiffCount); // console.log('tabSize: ' + tabSize + ', tabSizeScore: ' + tabSizeScore); return { insertSpaces: insertSpaces, tabSize: tabSize }; } exports.guessIndentation = guessIndentation; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[284/*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[280/*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[278/*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[137/*vs/editor/common/model/textModelSearch*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,83/*vs/editor/common/controller/wordCharacterClassifier*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,45/*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 }); } 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 */) { 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) { // 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*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,45/*vs/editor/common/model*/,280/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/,137/*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 () { return this.getContentOfSubTree(this.root).split(/\r\n|\r|\n/); }; 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 searcher.reset(start); var ret = { line: 0, column: 0 }; do { m = searcher.next(buffer.buffer); if (m) { if (m.index >= end) { return resultLen; } this.positionInBuffer(node, 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 (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 startPostion = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn); if (startPostion === null) { return []; } var endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn); if (endPosition === null) { return []; } var start = this.positionInBuffer(startPostion.node, startPostion.remainder); var end = this.positionInBuffer(endPosition.node, endPosition.remainder); if (startPostion.node === endPosition.node) { this.findMatchesInNode(startPostion.node, searcher, searchRange.startLineNumber, searchRange.startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result); return result; } var startLineNumber = searchRange.startLineNumber; var currentNode = startPostion.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++; startPostion = this.nodeAt2(startLineNumber, 1); currentNode = startPostion.node; start = this.positionInBuffer(startPostion.node, startPostion.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; }; PieceTreeBase.prototype.getContentOfSubTree = function (node) { var _this = this; var str = ''; this.iterate(node, function (node) { str += _this.getNodeContent(node); return true; }); return str; }; 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[275/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,45/*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.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[273/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,191/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/,275/*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[107/*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[272/*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[81/*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[271/*vs/editor/common/modes/languageSelector*/], __M([0/*require*/,1/*exports*/,225/*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[268/*vs/editor/common/modes/linkComputer*/], __M([0/*require*/,1/*exports*/,76/*vs/editor/common/core/characterClassifier*/,104/*vs/editor/common/core/uint*/]), function (require, exports, characterClassifier_1, uint_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 uint_1.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; 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[144/*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.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[266/*vs/editor/common/modes/supports/characterPair*/], __M([0/*require*/,1/*exports*/,81/*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 = []; } 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.prototype.shouldAutoClosePair = function (character, context, column) { // Always complete on empty line if (context.getTokenCount() === 0) { return true; } var tokenIndex = context.findTokenIndexAtOffset(column - 2); var standardTokenType = context.getStandardTokenType(tokenIndex); for (var _i = 0, _a = this._autoClosingPairs; _i < _a.length; _i++) { var autoClosingPair = _a[_i]; if (autoClosingPair.open === character) { return autoClosingPair.isOK(standardTokenType); } } return false; }; 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[264/*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[259/*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[258/*vs/editor/common/modes/supports/onEnter*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,5/*vs/base/common/strings*/,81/*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.regExpRules || []; } OnEnterSupport.prototype.onEnter = function (oneLineAboveText, beforeEnterText, afterEnterText) { // (1): `regExpRules` 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 (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 (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, open, close, forwardRegex, reversedRegex) { this.languageIdentifier = languageIdentifier; this.open = open; this.close = close; this.forwardRegex = forwardRegex; this.reversedRegex = reversedRegex; } return RichEditBracket; }()); exports.RichEditBracket = RichEditBracket; var RichEditBrackets = /** @class */ (function () { function RichEditBrackets(languageIdentifier, brackets) { var _this = this; this.brackets = brackets.map(function (b) { return new RichEditBracket(languageIdentifier, b[0], b[1], getRegexForBracketPair({ open: b[0], close: b[1] }), getReversedRegexForBracketPair({ open: b[0], close: b[1] })); }); this.forwardRegex = getRegexForBrackets(this.brackets); this.reversedRegex = getReversedRegexForBrackets(this.brackets); this.textIsBracket = {}; this.textIsOpenBracket = {}; var maxBracketLength = 0; this.brackets.forEach(function (b) { _this.textIsBracket[b.open.toLowerCase()] = b; _this.textIsBracket[b.close.toLowerCase()] = b; _this.textIsOpenBracket[b.open.toLowerCase()] = true; _this.textIsOpenBracket[b.close.toLowerCase()] = false; maxBracketLength = Math.max(maxBracketLength, b.open.length); maxBracketLength = Math.max(maxBracketLength, b.close.length); }); this.maxBracketLength = maxBracketLength; } return RichEditBrackets; }()); exports.RichEditBrackets = RichEditBrackets; function once(keyFn, computeFn) { var cache = {}; return function (input) { var key = keyFn(input); if (!cache.hasOwnProperty(key)) { cache[key] = computeFn(input); } return cache[key]; }; } var getRegexForBracketPair = once(function (input) { return input.open + ";" + input.close; }, function (input) { return createBracketOrRegExp([input.open, input.close]); }); var getReversedRegexForBracketPair = once(function (input) { return input.open + ";" + input.close; }, function (input) { return createBracketOrRegExp([toReversedString(input.open), toReversedString(input.close)]); }); var getRegexForBrackets = once(function (input) { return input.map(function (b) { return b.open + ";" + b.close; }).join(';'); }, function (input) { var pieces = []; input.forEach(function (b) { pieces.push(b.open); pieces.push(b.close); }); return createBracketOrRegExp(pieces); }); var getReversedRegexForBrackets = once(function (input) { return input.map(function (b) { return b.open + ";" + b.close; }).join(';'); }, function (input) { var pieces = []; input.forEach(function (b) { pieces.push(toReversedString(b.open)); pieces.push(toReversedString(b.close)); }); return createBracketOrRegExp(pieces); }); 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.findPrevBracketInToken = function (reversedBracketRegex, lineNumber, lineText, currentTokenStart, currentTokenEnd) { // Because JS does not support backwards regex search, we search forwards in a reversed string with a reversed regex ;) var reversedLineText = toReversedString(lineText); var reversedTokenText = reversedLineText.substring(lineText.length - currentTokenEnd, lineText.length - currentTokenStart); return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedTokenText, currentTokenStart); }; 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.findNextBracketInToken = function (bracketRegex, lineNumber, lineText, currentTokenStart, currentTokenEnd) { var currentTokenText = lineText.substring(currentTokenStart, currentTokenEnd); return this.findNextBracketInText(bracketRegex, lineNumber, currentTokenText, currentTokenStart); }; 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[257/*vs/editor/common/modes/supports/electricCharacter*/], __M([0/*require*/,1/*exports*/,81/*vs/editor/common/modes/languageConfiguration*/,144/*vs/editor/common/modes/supports*/,146/*vs/editor/common/modes/supports/richEditBrackets*/]), function (require, exports, languageConfiguration_1, supports_1, richEditBrackets_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var BracketElectricCharacterSupport = /** @class */ (function () { function BracketElectricCharacterSupport(richEditBrackets, autoClosePairs, contribution) { contribution = contribution || {}; this._richEditBrackets = richEditBrackets; this._complexAutoClosePairs = autoClosePairs.filter(function (pair) { return pair.open.length > 1 && !!pair.close; }).map(function (el) { return new languageConfiguration_1.StandardAutoClosingPairConditional(el); }); if (contribution.docComment) { // IDocComment is legacy, only partially supported this._complexAutoClosePairs.push(new languageConfiguration_1.StandardAutoClosingPairConditional({ open: contribution.docComment.open, close: contribution.docComment.close || '' })); } } BracketElectricCharacterSupport.prototype.getElectricCharacters = function () { var result = []; if (this._richEditBrackets) { for (var i = 0, len = this._richEditBrackets.brackets.length; i < len; i++) { var bracketPair = this._richEditBrackets.brackets[i]; var lastChar = bracketPair.close.charAt(bracketPair.close.length - 1); result.push(lastChar); } } // auto close for (var _i = 0, _a = this._complexAutoClosePairs; _i < _a.length; _i++) { var pair = _a[_i]; result.push(pair.open.charAt(pair.open.length - 1)); } // Filter duplicate entries result = result.filter(function (item, pos, array) { return array.indexOf(item) === pos; }); return result; }; BracketElectricCharacterSupport.prototype.onElectricCharacter = function (character, context, column) { return (this._onElectricAutoClose(character, context, column) || this._onElectricAutoIndent(character, context, column)); }; BracketElectricCharacterSupport.prototype._onElectricAutoIndent = 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.findPrevBracketInToken(reversedBracketRegex, 1, text, 0, text.length); if (!r) { return null; } var bracketText = text.substring(r.startColumn - 1, r.endColumn - 1); bracketText = bracketText.toLowerCase(); var isOpen = this._richEditBrackets.textIsOpenBracket[bracketText]; if (isOpen) { return null; } var textBeforeBracket = text.substring(0, r.startColumn - 1); if (!/^\s*$/.test(textBeforeBracket)) { // There is other text on the line before the bracket return null; } return { matchOpenBracket: bracketText }; }; BracketElectricCharacterSupport.prototype._onElectricAutoClose = function (character, context, column) { if (!this._complexAutoClosePairs.length) { return null; } var line = context.getLineContent(); for (var i = 0, len = this._complexAutoClosePairs.length; i < len; i++) { var pair = this._complexAutoClosePairs[i]; // See if the right electric character was pressed if (character !== pair.open.charAt(pair.open.length - 1)) { continue; } // check if the full open bracket matches var start = column - pair.open.length + 1; var actual = line.substring(start - 1, column - 1) + character; if (actual !== pair.open) { continue; } var lastTokenIndex = context.findTokenIndexAtOffset(column - 1); var lastTokenStandardType = context.getStandardTokenType(lastTokenIndex); // If we're in a scope listed in 'notIn', do nothing if (!pair.isOK(lastTokenStandardType)) { continue; } // If this line already contains the closing tag, do nothing. if (line.indexOf(pair.close, column - 1) >= 0) { continue; } return { appendText: pair.close }; } return null; }; 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[39/*vs/editor/common/modes/languageConfigurationRegistry*/], __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*/,3/*vs/editor/common/core/range*/,107/*vs/editor/common/model/wordHelper*/,81/*vs/editor/common/modes/languageConfiguration*/,144/*vs/editor/common/modes/supports*/,266/*vs/editor/common/modes/supports/characterPair*/,257/*vs/editor/common/modes/supports/electricCharacter*/,264/*vs/editor/common/modes/supports/indentRules*/,258/*vs/editor/common/modes/supports/onEnter*/,146/*vs/editor/common/modes/supports/richEditBrackets*/]), function (require, exports, errors_1, event_1, lifecycle_1, strings, range_1, 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.onEnter = RichEditSupport._handleOnEnter(this._conf); 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); } 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) { var autoClosingPairs = []; if (this._conf.autoClosingPairs) { autoClosingPairs = this._conf.autoClosingPairs; } else if (this._conf.brackets) { autoClosingPairs = this._conf.brackets.map(function (b) { return { open: b[0], close: b[1] }; }); } this._electricCharacter = new electricCharacter_1.BracketElectricCharacterSupport(this.brackets, autoClosingPairs, this._conf.__electricCharacterSupport); } return this._electricCharacter; }, enumerable: true, configurable: true }); 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._handleOnEnter = function (conf) { // on enter var onEnter = {}; var empty = true; if (conf.brackets) { empty = false; onEnter.brackets = conf.brackets; } if (conf.indentationRules) { empty = false; } if (conf.onEnterRules) { empty = false; onEnter.regExpRules = conf.onEnterRules; } if (!empty) { return new onEnter_1.OnEnterSupport(onEnter); } return null; }; 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() { } 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({ languageIdentifier: languageIdentifier }); return lifecycle_1.toDisposable(function () { if (_this._entries.get(languageIdentifier.id) === current) { _this._entries.set(languageIdentifier.id, previous); _this._onDidChange.fire({ languageIdentifier: 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 (character, context, column) { var scopedLineTokens = supports_1.createScopedLineTokens(context, column - 1); var characterPairSupport = this._getCharacterPairSupport(scopedLineTokens.languageId); if (!characterPairSupport) { return false; } return characterPairSupport.shouldAutoClosePair(character, 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 (model, lineNumber, honorIntentialIndent) { if (honorIntentialIndent === void 0) { honorIntentialIndent = true; } 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 (virtualModel, languageId, lineNumber, indentConverter) { var indentRulesSupport = this.getIndentRulesSupport(languageId); if (!indentRulesSupport) { return null; } var indent = this.getInheritIndentForLine(virtualModel, lineNumber); var lineContent = virtualModel.getLineContent(lineNumber); if (indent) { var inheritLine = indent.line; if (inheritLine !== undefined) { var onEnterSupport = this._getOnEnterSupport(languageId); var enterResult = null; try { if (onEnterSupport) { enterResult = onEnterSupport.onEnter('', virtualModel.getLineContent(inheritLine), ''); } } catch (e) { errors_1.onUnexpectedError(e); } 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 (model, range, indentConverter, autoIndent) { model.forceTokenization(range.startLineNumber); var lineTokens = model.getLineTokens(range.startLineNumber); var beforeEnterText; var afterEnterText; var scopedLineTokens = supports_1.createScopedLineTokens(lineTokens, range.startColumn - 1); var scopedLineText = scopedLineTokens.getLineContent(); var embeddedLanguage = false; 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); } 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); if (!autoIndent && !embeddedLanguage) { var beforeEnterIndentAction = this.getInheritIndentForLine(model, range.startLineNumber); if (indentRulesSupport.shouldDecrease(beforeEnterText)) { if (beforeEnterIndentAction) { beforeEnterIndent = beforeEnterIndentAction.indentation; if (beforeEnterIndentAction.action !== languageConfiguration_1.IndentAction.Indent) { beforeEnterIndent = indentConverter.unshiftIndent(beforeEnterIndent); } } } beforeEnterResult = beforeEnterIndent + strings.ltrim(strings.ltrim(beforeEnterText, ' '), '\t'); } 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(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 (model, range, ch, indentConverter) { 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); var afterTypeText; // selection support 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(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._getOnEnterSupport = function (languageId) { var value = this._getRichEditSupport(languageId); if (!value) { return null; } return value.onEnter || null; }; LanguageConfigurationRegistryImpl.prototype.getRawEnterActionAtPosition = function (model, lineNumber, column) { var r = this.getEnterAction(model, new range_1.Range(lineNumber, column, lineNumber, column)); return r ? r.enterAction : null; }; LanguageConfigurationRegistryImpl.prototype.getEnterAction = function (model, range) { var indentation = this.getIndentationAtPosition(model, range.startLineNumber, range.startColumn); var scopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber, range.startColumn); var onEnterSupport = this._getOnEnterSupport(scopedLineTokens.languageId); if (!onEnterSupport) { return null; } var scopedLineText = scopedLineTokens.getLineContent(); var beforeEnterText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset); var afterEnterText; // selection support 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 lineNumber = range.startLineNumber; var oneLineAboveText = ''; if (lineNumber > 1 && scopedLineTokens.firstCharOffset === 0) { // This is not the first line and the entire line belongs to this mode var oneLineAboveScopedLineTokens = this.getScopedLineTokens(model, lineNumber - 1); if (oneLineAboveScopedLineTokens.languageId === scopedLineTokens.languageId) { // The line above ends with text belonging to the same mode oneLineAboveText = oneLineAboveScopedLineTokens.getLineContent(); } } var enterResult = null; try { enterResult = onEnterSupport.onEnter(oneLineAboveText, beforeEnterText, afterEnterText); } catch (e) { errors_1.onUnexpectedError(e); } if (!enterResult) { return null; } else { // Here we add `\t` to appendText first because enterAction is leveraging appendText and removeText to change indentation. if (!enterResult.appendText) { if ((enterResult.indentAction === languageConfiguration_1.IndentAction.Indent) || (enterResult.indentAction === languageConfiguration_1.IndentAction.IndentOutdent)) { enterResult.appendText = '\t'; } else { enterResult.appendText = ''; } } } if (enterResult.removeText) { indentation = indentation.substring(0, indentation.length - enterResult.removeText); } return { enterAction: enterResult, 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); var scopedLineTokens = supports_1.createScopedLineTokens(lineTokens, column); return scopedLineTokens; }; // 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[256/*vs/editor/common/modes/supports/tokenization*/], __M([0/*require*/,1/*exports*/,28/*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[254/*vs/editor/common/modes/tokenizationRegistry*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,46/*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[148/*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 MarkerTag; (function (MarkerTag) { MarkerTag[MarkerTag["Unnecessary"] = 1] = "Unnecessary"; })(MarkerTag = exports.MarkerTag || (exports.MarkerTag = {})); 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 = {})); /** * 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 = {})); /** * 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 ScrollbarVisibility; (function (ScrollbarVisibility) { ScrollbarVisibility[ScrollbarVisibility["Auto"] = 1] = "Auto"; ScrollbarVisibility[ScrollbarVisibility["Hidden"] = 2] = "Hidden"; ScrollbarVisibility[ScrollbarVisibility["Visible"] = 3] = "Visible"; })(ScrollbarVisibility = exports.ScrollbarVisibility || (exports.ScrollbarVisibility = {})); /** * 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 = {})); /** * 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 = {})); /** * 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 = {})); /** * 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 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 = {})); var ScrollType; (function (ScrollType) { ScrollType[ScrollType["Smooth"] = 0] = "Smooth"; ScrollType[ScrollType["Immediate"] = 1] = "Immediate"; })(ScrollType = exports.ScrollType || (exports.ScrollType = {})); /** * 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 = {})); var RenderMinimap; (function (RenderMinimap) { RenderMinimap[RenderMinimap["None"] = 0] = "None"; RenderMinimap[RenderMinimap["Small"] = 1] = "Small"; RenderMinimap[RenderMinimap["Large"] = 2] = "Large"; RenderMinimap[RenderMinimap["SmallBlocks"] = 3] = "SmallBlocks"; RenderMinimap[RenderMinimap["LargeBlocks"] = 4] = "LargeBlocks"; })(RenderMinimap = exports.RenderMinimap || (exports.RenderMinimap = {})); /** * 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 = {})); /** * 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 = {})); 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 = {})); /** * 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 = {})); /** * 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 = {})); /** * 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 = {})); /** * Describes what to do with the indentation when pressing Enter. */ var IndentAction; (function (IndentAction) { /** * Insert new line and copy the previous line's indentation. */ IndentAction[IndentAction["None"] = 0] = "None"; /** * Insert new line and indent once (relative to the previous line's indentation). */ IndentAction[IndentAction["Indent"] = 1] = "Indent"; /** * Insert two new lines: * - the first one indented which will hold the cursor * - the second one at the same indentation level */ IndentAction[IndentAction["IndentOutdent"] = 2] = "IndentOutdent"; /** * Insert new line and outdent once (relative to the previous line's indentation). */ IndentAction[IndentAction["Outdent"] = 3] = "Outdent"; })(IndentAction = exports.IndentAction || (exports.IndentAction = {})); var 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 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 = {})); /** * 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 = {})); 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 = {})); /** * 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 = {})); }); /*--------------------------------------------------------------------------------------------- * 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/standalone/standaloneBase*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/cancellation*/,4/*vs/base/common/event*/,36/*vs/base/common/keyCodes*/,25/*vs/base/common/uri*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,103/*vs/editor/common/core/token*/,148/*vs/editor/common/standalone/standaloneEnums*/,584/*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[212/*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[88/*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(lineNumber, ranges) { 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; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[245/*vs/editor/browser/viewParts/lines/rangeUtil*/], __M([0/*require*/,1/*exports*/,88/*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 = Number.MAX_VALUE; } } 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[242/*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[238/*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[73/*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.canUseLayerHinting = source.canUseLayerHinting; this.pixelRatio = source.pixelRatio; this.editorClassName = source.editorClassName; this.lineHeight = source.lineHeight; this.readOnly = source.readOnly; this.accessibilitySupport = source.accessibilitySupport; this.emptySelectionClipboard = source.emptySelectionClipboard; this.copyWithSyntaxHighlighting = source.copyWithSyntaxHighlighting; this.layoutInfo = source.layoutInfo; this.fontInfo = source.fontInfo; this.viewInfo = source.viewInfo; this.wrappingInfo = source.wrappingInfo; } return ViewConfigurationChangedEvent; }()); exports.ViewConfigurationChangedEvent = ViewConfigurationChangedEvent; var ViewCursorStateChangedEvent = /** @class */ (function () { function ViewCursorStateChangedEvent(selections) { this.type = 2 /* ViewCursorStateChanged */; this.selections = selections; } return ViewCursorStateChangedEvent; }()); exports.ViewCursorStateChangedEvent = ViewCursorStateChangedEvent; var ViewDecorationsChangedEvent = /** @class */ (function () { function ViewDecorationsChangedEvent() { this.type = 3 /* ViewDecorationsChanged */; // Nothing to do } return ViewDecorationsChangedEvent; }()); exports.ViewDecorationsChangedEvent = ViewDecorationsChangedEvent; var ViewFlushedEvent = /** @class */ (function () { function ViewFlushedEvent() { this.type = 4 /* ViewFlushed */; // Nothing to do } return ViewFlushedEvent; }()); exports.ViewFlushedEvent = ViewFlushedEvent; var ViewFocusChangedEvent = /** @class */ (function () { function ViewFocusChangedEvent(isFocused) { this.type = 5 /* ViewFocusChanged */; this.isFocused = isFocused; } return ViewFocusChangedEvent; }()); exports.ViewFocusChangedEvent = ViewFocusChangedEvent; var ViewLineMappingChangedEvent = /** @class */ (function () { function ViewLineMappingChangedEvent() { this.type = 6 /* ViewLineMappingChanged */; // Nothing to do } return ViewLineMappingChangedEvent; }()); exports.ViewLineMappingChangedEvent = ViewLineMappingChangedEvent; var ViewLinesChangedEvent = /** @class */ (function () { function ViewLinesChangedEvent(fromLineNumber, toLineNumber) { this.type = 7 /* ViewLinesChanged */; this.fromLineNumber = fromLineNumber; this.toLineNumber = toLineNumber; } return ViewLinesChangedEvent; }()); exports.ViewLinesChangedEvent = ViewLinesChangedEvent; var ViewLinesDeletedEvent = /** @class */ (function () { function ViewLinesDeletedEvent(fromLineNumber, toLineNumber) { this.type = 8 /* ViewLinesDeleted */; this.fromLineNumber = fromLineNumber; this.toLineNumber = toLineNumber; } return ViewLinesDeletedEvent; }()); exports.ViewLinesDeletedEvent = ViewLinesDeletedEvent; var ViewLinesInsertedEvent = /** @class */ (function () { function ViewLinesInsertedEvent(fromLineNumber, toLineNumber) { this.type = 9 /* ViewLinesInserted */; this.fromLineNumber = fromLineNumber; this.toLineNumber = toLineNumber; } return ViewLinesInsertedEvent; }()); exports.ViewLinesInsertedEvent = ViewLinesInsertedEvent; var ViewRevealRangeRequestEvent = /** @class */ (function () { function ViewRevealRangeRequestEvent(range, verticalType, revealHorizontal, scrollType) { this.type = 10 /* ViewRevealRangeRequest */; 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 = 11 /* 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 ViewTokensChangedEvent = /** @class */ (function () { function ViewTokensChangedEvent(ranges) { this.type = 12 /* ViewTokensChanged */; this.ranges = ranges; } return ViewTokensChangedEvent; }()); exports.ViewTokensChangedEvent = ViewTokensChangedEvent; var ViewThemeChangedEvent = /** @class */ (function () { function ViewThemeChangedEvent() { this.type = 15 /* ViewThemeChanged */; } return ViewThemeChangedEvent; }()); exports.ViewThemeChangedEvent = ViewThemeChangedEvent; var ViewTokensColorsChangedEvent = /** @class */ (function () { function ViewTokensColorsChangedEvent() { this.type = 13 /* ViewTokensColorsChanged */; // Nothing to do } return ViewTokensColorsChangedEvent; }()); exports.ViewTokensColorsChangedEvent = ViewTokensColorsChangedEvent; var ViewZonesChangedEvent = /** @class */ (function () { function ViewZonesChangedEvent() { this.type = 14 /* ViewZonesChanged */; // Nothing to do } return ViewZonesChangedEvent; }()); exports.ViewZonesChangedEvent = ViewZonesChangedEvent; var ViewLanguageConfigurationEvent = /** @class */ (function () { function ViewLanguageConfigurationEvent() { this.type = 16 /* ViewLanguageConfigurationChanged */; } return ViewLanguageConfigurationEvent; }()); exports.ViewLanguageConfigurationEvent = ViewLanguageConfigurationEvent; 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[154/*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[108/*vs/editor/common/viewLayout/viewLineRenderer*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,124/*vs/editor/common/core/stringBuilder*/,154/*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 RenderLineInput = /** @class */ (function () { function RenderLineInput(useMonospaceOptimizations, canUseHalfwidthRightwardsArrow, lineContent, continuesWithWrappedLine, isBasicASCII, containsRTL, fauxIndentLength, lineTokens, lineDecorations, tabSize, spaceWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures) { 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.spaceWidth = spaceWidth; this.stopRenderingLineAfter = stopRenderingLineAfter; this.renderWhitespace = (renderWhitespace === 'all' ? 2 /* All */ : renderWhitespace === 'boundary' ? 1 /* Boundary */ : 0 /* None */); this.renderControlCharacters = renderControlCharacters; this.fontLigatures = fontLigatures; } 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.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)); }; 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 classNames = []; for (var i = 0, len = input.lineDecorations.length; i < len; i++) { var lineDecoration = input.lineDecorations[i]; if (lineDecoration.type === 1 /* Before */) { classNames.push(input.lineDecorations[i].className); containsForeignElements |= 1 /* Before */; } if (lineDecoration.type === 2 /* After */) { classNames.push(input.lineDecorations[i].className); containsForeignElements |= 2 /* After */; } } if (containsForeignElements !== 0 /* None */) { content = ""; } } 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, tabSize, containsRTL, spaceWidth, renderWhitespace, renderControlCharacters) { this.fontIsMonospace = fontIsMonospace; this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow; this.lineContent = lineContent; this.len = len; this.isOverflowing = isOverflowing; this.parts = parts; this.containsForeignElements = containsForeignElements; this.tabSize = tabSize; this.containsRTL = containsRTL; this.spaceWidth = spaceWidth; 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 === 2 /* All */ || input.renderWhitespace === 1 /* Boundary */) { tokens = _applyRenderWhitespace(lineContent, len, input.continuesWithWrappedLine, tokens, input.fauxIndentLength, input.tabSize, useMonospaceOptimizations, 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.tabSize, input.containsRTL, input.spaceWidth, 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, useMonospaceOptimizations, 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 tmpIndent = 0; for (var charIndex = 0; charIndex < fauxIndentLength; charIndex++) { var chCode = lineContent.charCodeAt(charIndex); if (chCode === 9 /* Tab */) { tmpIndent = tabSize; } else if (strings.isFullWidthCharacter(chCode)) { tmpIndent += 2; } else { tmpIndent++; } } tmpIndent = tmpIndent % tabSize; var wasInWhitespace = false; for (var charIndex = fauxIndentLength; charIndex < len; charIndex++) { var chCode = lineContent.charCodeAt(charIndex); 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 (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 tabSize = input.tabSize; var containsRTL = input.containsRTL; var spaceWidth = input.spaceWidth; var renderWhitespace = input.renderWhitespace; var renderControlCharacters = input.renderControlCharacters; var characterMapping = new CharacterMapping(len + 1, parts.length); var charIndex = 0; var tabsCharDelta = 0; 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(' 0) { if (!canUseHalfwidthRightwardsArrow || insertSpacesCount > 1) { sb.write1(0x2192); // RIGHTWARDS ARROW } else { sb.write1(0xFFEB); // HALFWIDTH RIGHTWARDS ARROW } insertSpacesCount--; } while (insertSpacesCount > 0) { sb.write1(0xA0); //   insertSpacesCount--; } } else { // must be CharCode.Space sb.write1(0xB7); // · } charOffsetInPart++; } 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); switch (charCode) { case 9 /* Tab */: var insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize; tabsCharDelta += insertSpacesCount - 1; charOffsetInPart += insertSpacesCount - 1; while (insertSpacesCount > 0) { sb.write1(0xA0); //   partContentCnt++; insertSpacesCount--; } break; case 32 /* Space */: sb.write1(0xA0); //   partContentCnt++; break; case 60 /* LessThan */: sb.appendASCIIString('<'); partContentCnt++; break; case 62 /* GreaterThan */: sb.appendASCIIString('>'); partContentCnt++; break; case 38 /* Ampersand */: sb.appendASCIIString('&'); partContentCnt++; break; case 0 /* Null */: sb.appendASCIIString('�'); partContentCnt++; break; case 65279 /* UTF8_BOM */: case 8232 /* LINE_SEPARATOR_2028 */: sb.write1(0xFFFD); partContentCnt++; break; default: if (strings.isFullWidthCharacter(charCode)) { tabsCharDelta++; } if (renderControlCharacters && charCode < 32) { sb.write1(9216 + charCode); partContentCnt++; } else { sb.write1(charCode); partContentCnt++; } } charOffsetInPart++; } 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[233/*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[231/*vs/editor/common/viewLayout/whitespaceComputer*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Represent whitespaces in between lines and provide fast CRUD management methods. * The whitespaces are sorted ascending by `afterLineNumber`. */ var WhitespaceComputer = /** @class */ (function () { function WhitespaceComputer() { this._heights = []; this._minWidths = []; this._ids = []; this._afterLineNumbers = []; this._ordinals = []; this._prefixSum = []; this._prefixSumValidIndex = -1; this._whitespaceId2Index = {}; this._lastWhitespaceId = 0; this._minWidth = -1; /* marker for not being computed */ } /** * 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. */ WhitespaceComputer.findInsertionIndex = function (sortedArray, value, ordinals, valueOrdinal) { var low = 0; var high = sortedArray.length; while (low < high) { var mid = ((low + high) >>> 1); if (value === sortedArray[mid]) { if (valueOrdinal < ordinals[mid]) { high = mid; } else { low = mid + 1; } } else if (value < sortedArray[mid]) { high = mid; } else { low = mid + 1; } } return low; }; /** * Insert a new whitespace of a certain height after a line number. * The whitespace has a "sticky" characteristic. * Irrespective of edits above or below `afterLineNumber`, the whitespace will follow the initial line. * * @param afterLineNumber The conceptual position of this whitespace. The whitespace will follow this line as best as possible even when deleting/inserting lines above/below. * @param heightInPx The height of the whitespace, in pixels. * @return An id that can be used later to mutate or delete the whitespace */ WhitespaceComputer.prototype.insertWhitespace = function (afterLineNumber, ordinal, heightInPx, minWidth) { afterLineNumber = afterLineNumber | 0; ordinal = ordinal | 0; heightInPx = heightInPx | 0; minWidth = minWidth | 0; var id = (++this._lastWhitespaceId); var insertionIndex = WhitespaceComputer.findInsertionIndex(this._afterLineNumbers, afterLineNumber, this._ordinals, ordinal); this._insertWhitespaceAtIndex(id, insertionIndex, afterLineNumber, ordinal, heightInPx, minWidth); this._minWidth = -1; /* marker for not being computed */ return id; }; WhitespaceComputer.prototype._insertWhitespaceAtIndex = function (id, insertIndex, afterLineNumber, ordinal, heightInPx, minWidth) { id = id | 0; insertIndex = insertIndex | 0; afterLineNumber = afterLineNumber | 0; ordinal = ordinal | 0; heightInPx = heightInPx | 0; minWidth = minWidth | 0; this._heights.splice(insertIndex, 0, heightInPx); this._minWidths.splice(insertIndex, 0, minWidth); this._ids.splice(insertIndex, 0, id); this._afterLineNumbers.splice(insertIndex, 0, afterLineNumber); this._ordinals.splice(insertIndex, 0, ordinal); this._prefixSum.splice(insertIndex, 0, 0); var keys = Object.keys(this._whitespaceId2Index); for (var i = 0, len = keys.length; i < len; i++) { var sid = keys[i]; var oldIndex = this._whitespaceId2Index[sid]; if (oldIndex >= insertIndex) { this._whitespaceId2Index[sid] = oldIndex + 1; } } this._whitespaceId2Index[id.toString()] = insertIndex; this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1); }; /** * Change properties associated with a certain whitespace. */ WhitespaceComputer.prototype.changeWhitespace = function (id, newAfterLineNumber, newHeight) { id = id | 0; newAfterLineNumber = newAfterLineNumber | 0; newHeight = newHeight | 0; var hasChanges = false; hasChanges = this.changeWhitespaceHeight(id, newHeight) || hasChanges; hasChanges = this.changeWhitespaceAfterLineNumber(id, newAfterLineNumber) || hasChanges; return hasChanges; }; /** * Change the height of an existing whitespace * * @param id The whitespace to change * @param newHeightInPx The new height of the whitespace, in pixels * @return Returns true if the whitespace is found and if the new height is different than the old height */ WhitespaceComputer.prototype.changeWhitespaceHeight = function (id, newHeightInPx) { id = id | 0; newHeightInPx = newHeightInPx | 0; var sid = id.toString(); if (this._whitespaceId2Index.hasOwnProperty(sid)) { var index = this._whitespaceId2Index[sid]; if (this._heights[index] !== newHeightInPx) { this._heights[index] = newHeightInPx; this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, index - 1); return true; } } return false; }; /** * Change the line number after which an existing whitespace flows. * * @param id The whitespace to change * @param newAfterLineNumber The new line number the whitespace will follow * @return Returns true if the whitespace is found and if the new line number is different than the old line number */ WhitespaceComputer.prototype.changeWhitespaceAfterLineNumber = function (id, newAfterLineNumber) { id = id | 0; newAfterLineNumber = newAfterLineNumber | 0; var sid = id.toString(); if (this._whitespaceId2Index.hasOwnProperty(sid)) { var index = this._whitespaceId2Index[sid]; if (this._afterLineNumbers[index] !== newAfterLineNumber) { // `afterLineNumber` changed for this whitespace // Record old ordinal var ordinal = this._ordinals[index]; // Record old height var heightInPx = this._heights[index]; // Record old min width var minWidth = this._minWidths[index]; // Since changing `afterLineNumber` can trigger a reordering, we're gonna remove this whitespace this.removeWhitespace(id); // And add it again var insertionIndex = WhitespaceComputer.findInsertionIndex(this._afterLineNumbers, newAfterLineNumber, this._ordinals, ordinal); this._insertWhitespaceAtIndex(id, insertionIndex, newAfterLineNumber, ordinal, heightInPx, minWidth); return true; } } return false; }; /** * Remove an existing whitespace. * * @param id The whitespace to remove * @return Returns true if the whitespace is found and it is removed. */ WhitespaceComputer.prototype.removeWhitespace = function (id) { id = id | 0; var sid = id.toString(); if (this._whitespaceId2Index.hasOwnProperty(sid)) { var index = this._whitespaceId2Index[sid]; delete this._whitespaceId2Index[sid]; this._removeWhitespaceAtIndex(index); this._minWidth = -1; /* marker for not being computed */ return true; } return false; }; WhitespaceComputer.prototype._removeWhitespaceAtIndex = function (removeIndex) { removeIndex = removeIndex | 0; this._heights.splice(removeIndex, 1); this._minWidths.splice(removeIndex, 1); this._ids.splice(removeIndex, 1); this._afterLineNumbers.splice(removeIndex, 1); this._ordinals.splice(removeIndex, 1); this._prefixSum.splice(removeIndex, 1); this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, removeIndex - 1); var keys = Object.keys(this._whitespaceId2Index); for (var i = 0, len = keys.length; i < len; i++) { var sid = keys[i]; var oldIndex = this._whitespaceId2Index[sid]; if (oldIndex >= removeIndex) { this._whitespaceId2Index[sid] = oldIndex - 1; } } }; /** * Notify the computer that lines have been deleted (a continuous zone of lines). * This gives it a chance to update `afterLineNumber` for whitespaces, giving the "sticky" characteristic. * * @param fromLineNumber The line number at which the deletion started, inclusive * @param toLineNumber The line number at which the deletion ended, inclusive */ WhitespaceComputer.prototype.onLinesDeleted = function (fromLineNumber, toLineNumber) { fromLineNumber = fromLineNumber | 0; toLineNumber = toLineNumber | 0; for (var i = 0, len = this._afterLineNumbers.length; i < len; i++) { var afterLineNumber = this._afterLineNumbers[i]; if (fromLineNumber <= afterLineNumber && afterLineNumber <= toLineNumber) { // The line this whitespace was after has been deleted // => move whitespace to before first deleted line this._afterLineNumbers[i] = fromLineNumber - 1; } else if (afterLineNumber > toLineNumber) { // The line this whitespace was after has been moved up // => move whitespace up this._afterLineNumbers[i] -= (toLineNumber - fromLineNumber + 1); } } }; /** * Notify the computer that lines have been inserted (a continuous zone of lines). * This gives it a chance to update `afterLineNumber` for whitespaces, giving the "sticky" characteristic. * * @param fromLineNumber The line number at which the insertion started, inclusive * @param toLineNumber The line number at which the insertion ended, inclusive. */ WhitespaceComputer.prototype.onLinesInserted = function (fromLineNumber, toLineNumber) { fromLineNumber = fromLineNumber | 0; toLineNumber = toLineNumber | 0; for (var i = 0, len = this._afterLineNumbers.length; i < len; i++) { var afterLineNumber = this._afterLineNumbers[i]; if (fromLineNumber <= afterLineNumber) { this._afterLineNumbers[i] += (toLineNumber - fromLineNumber + 1); } } }; /** * Get the sum of all the whitespaces. */ WhitespaceComputer.prototype.getTotalHeight = function () { if (this._heights.length === 0) { return 0; } return this.getAccumulatedHeight(this._heights.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`. */ WhitespaceComputer.prototype.getAccumulatedHeight = function (index) { index = index | 0; var startIndex = Math.max(0, this._prefixSumValidIndex + 1); if (startIndex === 0) { this._prefixSum[0] = this._heights[0]; startIndex++; } for (var i = startIndex; i <= index; i++) { this._prefixSum[i] = this._prefixSum[i - 1] + this._heights[i]; } this._prefixSumValidIndex = Math.max(this._prefixSumValidIndex, index); return this._prefixSum[index]; }; /** * Find all whitespaces with `afterLineNumber` < `lineNumber` and return the sum of their heights. * * @param lineNumber The line number whitespaces should be before. * @return The sum of the heights of the whitespaces before `lineNumber`. */ WhitespaceComputer.prototype.getAccumulatedHeightBeforeLineNumber = function (lineNumber) { lineNumber = lineNumber | 0; var lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber); if (lastWhitespaceBeforeLineNumber === -1) { return 0; } return this.getAccumulatedHeight(lastWhitespaceBeforeLineNumber); }; WhitespaceComputer.prototype._findLastWhitespaceBeforeLineNumber = function (lineNumber) { lineNumber = lineNumber | 0; // Find the whitespace before line number var afterLineNumbers = this._afterLineNumbers; var low = 0; var high = afterLineNumbers.length - 1; while (low <= high) { var delta = (high - low) | 0; var halfDelta = (delta / 2) | 0; var mid = (low + halfDelta) | 0; if (afterLineNumbers[mid] < lineNumber) { if (mid + 1 >= afterLineNumbers.length || afterLineNumbers[mid + 1] >= lineNumber) { return mid; } else { low = (mid + 1) | 0; } } else { high = (mid - 1) | 0; } } return -1; }; WhitespaceComputer.prototype._findFirstWhitespaceAfterLineNumber = function (lineNumber) { lineNumber = lineNumber | 0; var lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber); var firstWhitespaceAfterLineNumber = lastWhitespaceBeforeLineNumber + 1; if (firstWhitespaceAfterLineNumber < this._heights.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. */ WhitespaceComputer.prototype.getFirstWhitespaceIndexAfterLineNumber = function (lineNumber) { lineNumber = lineNumber | 0; return this._findFirstWhitespaceAfterLineNumber(lineNumber); }; /** * The number of whitespaces. */ WhitespaceComputer.prototype.getCount = function () { return this._heights.length; }; /** * The maximum min width for all whitespaces. */ WhitespaceComputer.prototype.getMinWidth = function () { if (this._minWidth === -1) { var minWidth = 0; for (var i = 0, len = this._minWidths.length; i < len; i++) { minWidth = Math.max(minWidth, this._minWidths[i]); } this._minWidth = minWidth; } return this._minWidth; }; /** * Get the `afterLineNumber` for whitespace at index `index`. * * @param index The index of the whitespace. * @return `afterLineNumber` of whitespace at `index`. */ WhitespaceComputer.prototype.getAfterLineNumberForWhitespaceIndex = function (index) { index = index | 0; return this._afterLineNumbers[index]; }; /** * Get the `id` for whitespace at index `index`. * * @param index The index of the whitespace. * @return `id` of whitespace at `index`. */ WhitespaceComputer.prototype.getIdForWhitespaceIndex = function (index) { index = index | 0; return this._ids[index]; }; /** * Get the `height` for whitespace at index `index`. * * @param index The index of the whitespace. * @return `height` of whitespace at `index`. */ WhitespaceComputer.prototype.getHeightForWhitespaceIndex = function (index) { index = index | 0; return this._heights[index]; }; /** * Get all whitespaces. */ WhitespaceComputer.prototype.getWhitespaces = function (deviceLineHeight) { deviceLineHeight = deviceLineHeight | 0; var result = []; for (var i = 0; i < this._heights.length; i++) { result.push({ id: this._ids[i], afterLineNumber: this._afterLineNumbers[i], heightInLines: this._heights[i] / deviceLineHeight }); } return result; }; return WhitespaceComputer; }()); exports.WhitespaceComputer = WhitespaceComputer; }); /*--------------------------------------------------------------------------------------------- * 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/common/viewLayout/linesLayout*/], __M([0/*require*/,1/*exports*/,231/*vs/editor/common/viewLayout/whitespaceComputer*/]), function (require, exports, whitespaceComputer_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * 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). * This is written with no knowledge of an editor in mind. */ var LinesLayout = /** @class */ (function () { function LinesLayout(lineCount, lineHeight) { this._lineCount = lineCount; this._lineHeight = lineHeight; this._whitespaces = new whitespaceComputer_1.WhitespaceComputer(); } /** * Change the height of a line in pixels. */ LinesLayout.prototype.setLineHeight = function (lineHeight) { this._lineHeight = lineHeight; }; /** * Set the number of lines. * * @param lineCount New number of lines. */ LinesLayout.prototype.onFlushed = function (lineCount) { this._lineCount = lineCount; }; /** * Insert a new whitespace of a certain height after a line number. * The whitespace has a "sticky" characteristic. * Irrespective of edits above or below `afterLineNumber`, the whitespace will follow the initial line. * * @param afterLineNumber The conceptual position of this whitespace. The whitespace will follow this line as best as possible even when deleting/inserting lines above/below. * @param heightInPx The height of the whitespace, in pixels. * @return An id that can be used later to mutate or delete the whitespace */ LinesLayout.prototype.insertWhitespace = function (afterLineNumber, ordinal, heightInPx, minWidth) { return this._whitespaces.insertWhitespace(afterLineNumber, ordinal, heightInPx, minWidth); }; /** * Change properties associated with a certain whitespace. */ LinesLayout.prototype.changeWhitespace = function (id, newAfterLineNumber, newHeight) { return this._whitespaces.changeWhitespace(id, newAfterLineNumber, newHeight); }; /** * Remove an existing whitespace. * * @param id The whitespace to remove * @return Returns true if the whitespace is found and it is removed. */ LinesLayout.prototype.removeWhitespace = function (id) { return this._whitespaces.removeWhitespace(id); }; /** * 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._lineCount -= (toLineNumber - fromLineNumber + 1); this._whitespaces.onLinesDeleted(fromLineNumber, toLineNumber); }; /** * 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._lineCount += (toLineNumber - fromLineNumber + 1); this._whitespaces.onLinesInserted(fromLineNumber, toLineNumber); }; /** * Get the sum of heights for all objects. * * @return The sum of heights for all objects. */ LinesLayout.prototype.getLinesTotalHeight = function () { var linesHeight = this._lineHeight * this._lineCount; var whitespacesHeight = this._whitespaces.getTotalHeight(); return linesHeight + whitespacesHeight; }; /** * 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) { lineNumber = lineNumber | 0; var previousLinesHeight; if (lineNumber > 1) { previousLinesHeight = this._lineHeight * (lineNumber - 1); } else { previousLinesHeight = 0; } var previousWhitespacesHeight = this._whitespaces.getAccumulatedHeightBeforeLineNumber(lineNumber); return previousLinesHeight + previousWhitespacesHeight; }; /** * Returns the accumulated height of whitespaces before the given line number. * * @param lineNumber The line number */ LinesLayout.prototype.getWhitespaceAccumulatedHeightBeforeLineNumber = function (lineNumber) { return this._whitespaces.getAccumulatedHeightBeforeLineNumber(lineNumber); }; LinesLayout.prototype.getWhitespaceMinWidth = function () { return this._whitespaces.getMinWidth(); }; /** * Check if `verticalOffset` is below all lines. */ LinesLayout.prototype.isAfterLines = function (verticalOffset) { 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) { 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) { 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._whitespaces.getFirstWhitespaceIndexAfterLineNumber(startLineNumber) | 0; var whitespaceCount = this._whitespaces.getCount() | 0; var currentWhitespaceHeight; var currentWhitespaceAfterLineNumber; if (whitespaceIndex === -1) { whitespaceIndex = whitespaceCount; currentWhitespaceAfterLineNumber = endLineNumber + 1; currentWhitespaceHeight = 0; } else { currentWhitespaceAfterLineNumber = this._whitespaces.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0; currentWhitespaceHeight = this._whitespaces.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._whitespaces.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0; currentWhitespaceHeight = this._whitespaces.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) { whitespaceIndex = whitespaceIndex | 0; var afterLineNumber = this._whitespaces.getAfterLineNumberForWhitespaceIndex(whitespaceIndex); var previousLinesHeight; if (afterLineNumber >= 1) { previousLinesHeight = this._lineHeight * afterLineNumber; } else { previousLinesHeight = 0; } var previousWhitespacesHeight; if (whitespaceIndex > 0) { previousWhitespacesHeight = this._whitespaces.getAccumulatedHeight(whitespaceIndex - 1); } else { previousWhitespacesHeight = 0; } return previousLinesHeight + previousWhitespacesHeight; }; LinesLayout.prototype.getWhitespaceIndexAtOrAfterVerticallOffset = function (verticalOffset) { verticalOffset = verticalOffset | 0; var midWhitespaceIndex, minWhitespaceIndex = 0, maxWhitespaceIndex = this._whitespaces.getCount() - 1, midWhitespaceVerticalOffset, midWhitespaceHeight; if (maxWhitespaceIndex < 0) { return -1; } // Special case: nothing to be found var maxWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(maxWhitespaceIndex); var maxWhitespaceHeight = this._whitespaces.getHeightForWhitespaceIndex(maxWhitespaceIndex); if (verticalOffset >= maxWhitespaceVerticalOffset + maxWhitespaceHeight) { return -1; } while (minWhitespaceIndex < maxWhitespaceIndex) { midWhitespaceIndex = Math.floor((minWhitespaceIndex + maxWhitespaceIndex) / 2); midWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(midWhitespaceIndex); midWhitespaceHeight = this._whitespaces.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) { verticalOffset = verticalOffset | 0; var candidateIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset); if (candidateIndex < 0) { return null; } if (candidateIndex >= this._whitespaces.getCount()) { return null; } var candidateTop = this.getVerticalOffsetForWhitespaceIndex(candidateIndex); if (candidateTop > verticalOffset) { return null; } var candidateHeight = this._whitespaces.getHeightForWhitespaceIndex(candidateIndex); var candidateId = this._whitespaces.getIdForWhitespaceIndex(candidateIndex); var candidateAfterLineNumber = this._whitespaces.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) { verticalOffset1 = verticalOffset1 | 0; verticalOffset2 = verticalOffset2 | 0; var startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1); var endIndex = this._whitespaces.getCount() - 1; if (startIndex < 0) { return []; } var result = []; for (var i = startIndex; i <= endIndex; i++) { var top_1 = this.getVerticalOffsetForWhitespaceIndex(i); var height = this._whitespaces.getHeightForWhitespaceIndex(i); if (top_1 >= verticalOffset2) { break; } result.push({ id: this._whitespaces.getIdForWhitespaceIndex(i), afterLineNumber: this._whitespaces.getAfterLineNumberForWhitespaceIndex(i), verticalOffset: top_1, height: height }); } return result; }; /** * Get all whitespaces. */ LinesLayout.prototype.getWhitespaces = function () { return this._whitespaces.getWhitespaces(this._lineHeight); }; 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[158/*vs/editor/common/viewModel/prefixSumComputer*/], __M([0/*require*/,1/*exports*/,104/*vs/editor/common/core/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.getCount = function () { return this.values.length; }; 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; var PrefixSumComputerWithCache = /** @class */ (function () { function PrefixSumComputerWithCache(values) { this._cacheAccumulatedValueStart = 0; this._cache = null; this._actual = new PrefixSumComputer(values); this._bustCache(); } PrefixSumComputerWithCache.prototype._bustCache = function () { this._cacheAccumulatedValueStart = 0; this._cache = null; }; PrefixSumComputerWithCache.prototype.insertValues = function (insertIndex, insertValues) { if (this._actual.insertValues(insertIndex, insertValues)) { this._bustCache(); } }; PrefixSumComputerWithCache.prototype.changeValue = function (index, value) { if (this._actual.changeValue(index, value)) { this._bustCache(); } }; PrefixSumComputerWithCache.prototype.removeValues = function (startIndex, cnt) { if (this._actual.removeValues(startIndex, cnt)) { this._bustCache(); } }; PrefixSumComputerWithCache.prototype.getTotalValue = function () { return this._actual.getTotalValue(); }; PrefixSumComputerWithCache.prototype.getAccumulatedValue = function (index) { return this._actual.getAccumulatedValue(index); }; PrefixSumComputerWithCache.prototype.getIndexOf = function (accumulatedValue) { accumulatedValue = Math.floor(accumulatedValue); //@perf if (this._cache !== null) { var cacheIndex = accumulatedValue - this._cacheAccumulatedValueStart; if (cacheIndex >= 0 && cacheIndex < this._cache.length) { // Cache hit! return this._cache[cacheIndex]; } } // Cache miss! return this._actual.getIndexOf(accumulatedValue); }; /** * Gives a hint that a lot of requests are about to come in for these accumulated values. */ PrefixSumComputerWithCache.prototype.warmUpCache = function (accumulatedValueStart, accumulatedValueEnd) { var newCache = []; for (var accumulatedValue = accumulatedValueStart; accumulatedValue <= accumulatedValueEnd; accumulatedValue++) { newCache[accumulatedValue - accumulatedValueStart] = this.getIndexOf(accumulatedValue); } this._cache = newCache; this._cacheAccumulatedValueStart = accumulatedValueStart; }; return PrefixSumComputerWithCache; }()); exports.PrefixSumComputerWithCache = PrefixSumComputerWithCache; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[406/*vs/editor/common/model/mirrorTextModel*/], __M([0/*require*/,1/*exports*/,12/*vs/editor/common/core/position*/,158/*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[227/*vs/editor/common/services/editorSimpleWorker*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,147/*vs/base/common/diff/diff*/,57/*vs/base/common/iterator*/,17/*vs/base/common/platform*/,25/*vs/base/common/uri*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,293/*vs/editor/common/diff/diffComputer*/,406/*vs/editor/common/model/mirrorTextModel*/,107/*vs/editor/common/model/wordHelper*/,268/*vs/editor/common/modes/linkComputer*/,259/*vs/editor/common/modes/supports/inplaceReplaceSupport*/,210/*vs/editor/common/standalone/standaloneBase*/,20/*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_1) { "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.getWordUntilPosition = function (position, wordDefinition) { var wordAtPosition = this.getWordAtPosition(position, wordDefinition); if (!wordAtPosition) { return { word: '', startColumn: position.column, endColumn: position.column }; } return { word: this._lines[position.lineNumber - 1].substring(wordAtPosition.startColumn - 1, position.column - 1), startColumn: wordAtPosition.startColumn, endColumn: position.column }; }; 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 BaseEditorSimpleWorker = /** @class */ (function () { function BaseEditorSimpleWorker(foreignModuleFactory) { this._foreignModuleFactory = foreignModuleFactory; this._foreignModule = null; } // ---- BEGIN diff -------------------------------------------------------------------------- BaseEditorSimpleWorker.prototype.computeDiff = function (originalUrl, modifiedUrl, ignoreTrimWhitespace) { var original = this._getModel(originalUrl); var modified = this._getModel(modifiedUrl); if (!original || !modified) { return Promise.resolve(null); } var originalLines = original.getLinesContent(); var modifiedLines = modified.getLinesContent(); var diffComputer = new diffComputer_1.DiffComputer(originalLines, modifiedLines, { shouldComputeCharChanges: true, shouldPostProcessCharChanges: true, shouldIgnoreTrimWhitespace: ignoreTrimWhitespace, shouldMakePrettyDiff: true }); var changes = diffComputer.computeDiff(); var identical = (changes.length > 0 ? false : this._modelsAreIdentical(original, modified)); return Promise.resolve({ identical: identical, changes: changes }); }; BaseEditorSimpleWorker.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; }; BaseEditorSimpleWorker.prototype.computeMoreMinimalEdits = function (modelUrl, edits) { var model = this._getModel(modelUrl); if (!model) { return Promise.resolve(edits); } var result = []; var 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 (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { var _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; } var 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) > BaseEditorSimpleWorker._diffLimit) { result.push({ range: range, text: text }); continue; } // compute diff between original and edit.text var changes = diff_1.stringDiff(original, text, false); var editOffset = model.offsetAt(range_1.Range.lift(range).getStartPosition()); for (var _b = 0, changes_1 = changes; _b < changes_1.length; _b++) { var change = changes_1[_b]; var start = model.positionAt(editOffset + change.originalStart); var end = model.positionAt(editOffset + change.originalStart + change.originalLength); var 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 Promise.resolve(result); }; // ---- END minimal edits --------------------------------------------------------------- BaseEditorSimpleWorker.prototype.computeLinks = function (modelUrl) { var model = this._getModel(modelUrl); if (!model) { return Promise.resolve(null); } return Promise.resolve(linkComputer_1.computeLinks(model)); }; BaseEditorSimpleWorker.prototype.textualSuggest = function (modelUrl, position, wordDef, wordDefFlags) { var model = this._getModel(modelUrl); if (!model) { return Promise.resolve(null); } var seen = Object.create(null); var suggestions = []; var wordDefRegExp = new RegExp(wordDef, wordDefFlags); var wordUntil = model.getWordUntilPosition(position, wordDefRegExp); var wordAt = model.getWordAtPosition(position, wordDefRegExp); if (wordAt) { seen[model.getValueInRange(wordAt)] = true; } for (var iter = model.createWordIterator(wordDefRegExp), e = iter.next(); !e.done && suggestions.length <= BaseEditorSimpleWorker._suggestionsLimit; e = iter.next()) { var word = e.value; if (seen[word]) { continue; } seen[word] = true; if (!isNaN(Number(word))) { continue; } suggestions.push({ kind: 18 /* Text */, label: word, insertText: word, range: { startLineNumber: position.lineNumber, startColumn: wordUntil.startColumn, endLineNumber: position.lineNumber, endColumn: wordUntil.endColumn } }); } return Promise.resolve({ suggestions: suggestions }); }; // ---- END suggest -------------------------------------------------------------------------- //#region -- word ranges -- BaseEditorSimpleWorker.prototype.computeWordRanges = function (modelUrl, range, wordDef, wordDefFlags) { var model = this._getModel(modelUrl); if (!model) { return Promise.resolve(Object.create(null)); } var wordDefRegExp = new RegExp(wordDef, wordDefFlags); var result = Object.create(null); for (var line = range.startLineNumber; line < range.endLineNumber; line++) { var words = model.getLineWords(line, wordDefRegExp); for (var _i = 0, words_1 = words; _i < words_1.length; _i++) { var word = words_1[_i]; if (!isNaN(Number(word.word))) { continue; } var array = result[word.word]; if (!array) { array = []; result[word.word] = array; } array.push({ startLineNumber: line, startColumn: word.startColumn, endLineNumber: line, endColumn: word.endColumn }); } } return Promise.resolve(result); }; //#endregion BaseEditorSimpleWorker.prototype.navigateValueSet = function (modelUrl, range, up, wordDef, wordDefFlags) { var model = this._getModel(modelUrl); if (!model) { return Promise.resolve(null); } var wordDefRegExp = new RegExp(wordDef, wordDefFlags); if (range.startColumn === range.endColumn) { range = { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.endLineNumber, endColumn: range.endColumn + 1 }; } var selectionText = model.getValueInRange(range); var wordRange = model.getWordAtPosition({ lineNumber: range.startLineNumber, column: range.startColumn }, wordDefRegExp); if (!wordRange) { return Promise.resolve(null); } var word = model.getValueInRange(wordRange); var result = inplaceReplaceSupport_1.BasicInplaceReplace.INSTANCE.navigateValueSet(range, selectionText, wordRange, word, up); return Promise.resolve(result); }; // ---- BEGIN foreign module support -------------------------------------------------------------------------- BaseEditorSimpleWorker.prototype.loadForeignModule = function (moduleId, createData) { var _this = this; var ctx = { getMirrorModels: function () { return _this._getModels(); } }; if (this._foreignModuleFactory) { this._foreignModule = this._foreignModuleFactory(ctx, createData); // static foreing module var methods = []; for (var _i = 0, _a = types_1.getAllPropertyNames(this._foreignModule); _i < _a.length; _i++) { var prop = _a[_i]; if (typeof this._foreignModule[prop] === 'function') { methods.push(prop); } } return Promise.resolve(methods); } // ESM-comment-begin return new Promise(function (resolve, reject) { require([moduleId], function (foreignModule) { _this._foreignModule = foreignModule.create(ctx, createData); var methods = []; for (var _i = 0, _a = types_1.getAllPropertyNames(_this._foreignModule); _i < _a.length; _i++) { var prop = _a[_i]; if (typeof _this._foreignModule[prop] === 'function') { methods.push(prop); } } resolve(methods); }, reject); }); // ESM-comment-end // ESM-uncomment-begin // return Promise.reject(new Error(`Unexpected usage`)); // ESM-uncomment-end }; // foreign method request BaseEditorSimpleWorker.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 --------------------------------------------------------------- BaseEditorSimpleWorker._diffLimit = 100000; // ---- BEGIN suggest -------------------------------------------------------------------------- BaseEditorSimpleWorker._suggestionsLimit = 10000; return BaseEditorSimpleWorker; }()); exports.BaseEditorSimpleWorker = BaseEditorSimpleWorker; /** * @internal */ var EditorSimpleWorkerImpl = /** @class */ (function (_super) { __extends(EditorSimpleWorkerImpl, _super); function EditorSimpleWorkerImpl(foreignModuleFactory) { var _this = _super.call(this, foreignModuleFactory) || this; _this._models = Object.create(null); return _this; } EditorSimpleWorkerImpl.prototype.dispose = function () { this._models = Object.create(null); }; EditorSimpleWorkerImpl.prototype._getModel = function (uri) { return this._models[uri]; }; EditorSimpleWorkerImpl.prototype._getModels = function () { var _this = this; var all = []; Object.keys(this._models).forEach(function (key) { return all.push(_this._models[key]); }); return all; }; EditorSimpleWorkerImpl.prototype.acceptNewModel = function (data) { this._models[data.url] = new MirrorModel(uri_1.URI.parse(data.url), data.lines, data.EOL, data.versionId); }; EditorSimpleWorkerImpl.prototype.acceptModelChanged = function (strURL, e) { if (!this._models[strURL]) { return; } var model = this._models[strURL]; model.onEvents(e); }; EditorSimpleWorkerImpl.prototype.acceptRemovedModel = function (strURL) { if (!this._models[strURL]) { return; } delete this._models[strURL]; }; return EditorSimpleWorkerImpl; }(BaseEditorSimpleWorker)); exports.EditorSimpleWorkerImpl = EditorSimpleWorkerImpl; /** * Called on the worker side * @internal */ function create() { return new EditorSimpleWorkerImpl(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[86/*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.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.onTokensChanged = function (e) { return false; }; ViewEventHandler.prototype.onTokensColorsChanged = function (e) { return false; }; ViewEventHandler.prototype.onZonesChanged = function (e) { return false; }; ViewEventHandler.prototype.onThemeChanged = 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 /* ViewCursorStateChanged */: if (this.onCursorStateChanged(e)) { shouldRender = true; } break; case 3 /* ViewDecorationsChanged */: if (this.onDecorationsChanged(e)) { shouldRender = true; } break; case 4 /* ViewFlushed */: if (this.onFlushed(e)) { shouldRender = true; } break; case 5 /* ViewFocusChanged */: if (this.onFocusChanged(e)) { shouldRender = true; } break; case 16 /* ViewLanguageConfigurationChanged */: if (this.onLanguageConfigurationChanged(e)) { shouldRender = true; } break; case 6 /* ViewLineMappingChanged */: if (this.onLineMappingChanged(e)) { shouldRender = true; } break; case 7 /* ViewLinesChanged */: if (this.onLinesChanged(e)) { shouldRender = true; } break; case 8 /* ViewLinesDeleted */: if (this.onLinesDeleted(e)) { shouldRender = true; } break; case 9 /* ViewLinesInserted */: if (this.onLinesInserted(e)) { shouldRender = true; } break; case 10 /* ViewRevealRangeRequest */: if (this.onRevealRangeRequest(e)) { shouldRender = true; } break; case 11 /* ViewScrollChanged */: if (this.onScrollChanged(e)) { shouldRender = true; } break; case 12 /* ViewTokensChanged */: if (this.onTokensChanged(e)) { shouldRender = true; } break; case 13 /* ViewTokensColorsChanged */: if (this.onTokensColorsChanged(e)) { shouldRender = true; } break; case 14 /* ViewZonesChanged */: if (this.onZonesChanged(e)) { shouldRender = true; } break; case 15 /* ViewThemeChanged */: if (this.onThemeChanged(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[71/*vs/editor/browser/view/dynamicViewOverlay*/], __M([0/*require*/,1/*exports*/,86/*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[33/*vs/editor/browser/view/viewPart*/], __M([0/*require*/,1/*exports*/,26/*vs/base/browser/fastDomNode*/,86/*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[229/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,26/*vs/base/browser/fastDomNode*/,33/*vs/editor/browser/view/viewPart*/,20/*vs/base/common/types*/]), function (require, exports, dom, fastDomNode_1, viewPart_1, types_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, position, range, preference) { var myWidget = this._widgets[widget.getId()]; myWidget.setPosition(position, 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; this._fixedOverflowWidgets = this._context.configuration.editor.viewInfo.fixedOverflowWidgets; this._contentWidth = this._context.configuration.editor.layoutInfo.contentWidth; this._contentLeft = this._context.configuration.editor.layoutInfo.contentLeft; this._lineHeight = this._context.configuration.editor.lineHeight; this._setPosition(null, 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) { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; } if (e.layoutInfo) { this._contentLeft = this._context.configuration.editor.layoutInfo.contentLeft; this._contentWidth = this._context.configuration.editor.layoutInfo.contentWidth; this._maxWidth = this._getMaxWidth(); } }; Widget.prototype.onLineMappingChanged = function (e) { this._setPosition(this._position, this._range); }; Widget.prototype._setPosition = function (position, range) { this._position = types_1.withUndefinedAsNull(position); this._range = types_1.withUndefinedAsNull(range); this._viewPosition = null; this._viewRange = null; if (this._position) { // Do not trust that widgets give a valid position var validModelPosition = this._context.model.validateModelPosition(this._position); if (this._context.model.coordinatesConverter.modelPositionIsVisible(validModelPosition)) { this._viewPosition = this._context.model.coordinatesConverter.convertModelPositionToViewPosition(validModelPosition); } } if (this._range) { // Do not trust that widgets give a valid position var validModelRange = this._context.model.validateModelRange(this._range); 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 (position, range, preference) { this._setPosition(position, range); this._preference = types_1.withUndefinedAsNull(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._layoutBoxInPage = function (topLeft, bottomLeft, width, height, ctx) { var aboveLeft0 = topLeft.left - ctx.scrollLeft; var belowLeft0 = bottomLeft.left - ctx.scrollLeft; if (aboveLeft0 < 0 || aboveLeft0 > this._contentWidth) { // Don't render if position is scrolled outside viewport return null; } var aboveTop = topLeft.top - height; var belowTop = bottomLeft.top + this._lineHeight; var aboveLeft = aboveLeft0 + this._contentLeft; var belowLeft = belowLeft0 + this._contentLeft; var domNodePosition = dom.getDomNodePagePosition(this._viewDomNode.domNode); var absoluteAboveTop = domNodePosition.top + aboveTop - dom.StandardWindow.scrollY; var absoluteBelowTop = domNodePosition.top + belowTop - dom.StandardWindow.scrollY; var absoluteAboveLeft = domNodePosition.left + aboveLeft - dom.StandardWindow.scrollX; var absoluteBelowLeft = domNodePosition.left + belowLeft - dom.StandardWindow.scrollX; var INNER_WIDTH = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var INNER_HEIGHT = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; // Leave some clearance to the bottom var TOP_PADDING = 22; var BOTTOM_PADDING = 22; var fitsAbove = (absoluteAboveTop >= TOP_PADDING), fitsBelow = (absoluteBelowTop + height <= INNER_HEIGHT - BOTTOM_PADDING); if (absoluteAboveLeft + width + 20 > INNER_WIDTH) { var delta = absoluteAboveLeft - (INNER_WIDTH - width - 20); absoluteAboveLeft -= delta; aboveLeft -= delta; } if (absoluteBelowLeft + width + 20 > INNER_WIDTH) { var delta = absoluteBelowLeft - (INNER_WIDTH - width - 20); absoluteBelowLeft -= delta; belowLeft -= delta; } if (absoluteAboveLeft < 0) { var delta = absoluteAboveLeft; absoluteAboveLeft -= delta; aboveLeft -= delta; } if (absoluteBelowLeft < 0) { var delta = absoluteBelowLeft; absoluteBelowLeft -= delta; belowLeft -= delta; } if (this._fixedOverflowWidgets) { aboveTop = absoluteAboveTop; belowTop = absoluteBelowTop; aboveLeft = absoluteAboveLeft; belowLeft = absoluteBelowLeft; } return { fitsAbove: fitsAbove, aboveTop: aboveTop, 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._viewPosition) { return [null, null]; } var visibleRangeForPosition = ctx.visibleRangeForPosition(this._viewPosition); if (!visibleRangeForPosition) { return [null, null]; } var topForPosition = ctx.getVerticalOffsetForLineNumber(this._viewPosition.lineNumber) - ctx.scrollTop; var topLeft = new Coordinate(topForPosition, visibleRangeForPosition.left); var largestLineNumber = this._viewPosition.lineNumber; var smallestLeft = visibleRangeForPosition.left; if (this._viewRange) { var visibleRangesForRange = ctx.linesVisibleRangesForRange(this._viewRange, false); if (visibleRangesForRange && visibleRangesForRange.length > 0) { for (var i = visibleRangesForRange.length - 1; i >= 0; i--) { var visibleRangesForLine = visibleRangesForRange[i]; if (visibleRangesForLine.lineNumber >= largestLineNumber) { if (visibleRangesForLine.lineNumber > largestLineNumber) { largestLineNumber = visibleRangesForLine.lineNumber; smallestLeft = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; } for (var j = 0, lenJ = visibleRangesForLine.ranges.length; j < lenJ; j++) { var visibleRange = visibleRangesForLine.ranges[j]; if (visibleRange.left < smallestLeft) { smallestLeft = visibleRange.left; } } } } } } var topForBottomLine = ctx.getVerticalOffsetForLineNumber(largestLineNumber) - ctx.scrollTop; var bottomLeft = new Coordinate(topForBottomLine, smallestLeft); 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._viewPosition || !this._preference) { return; } if (this._viewPosition.lineNumber < viewportData.startLineNumber || this._viewPosition.lineNumber > 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[230/*vs/editor/browser/viewParts/decorations/decorations*/], __M([0/*require*/,1/*exports*/,71/*vs/editor/browser/view/dynamicViewOverlay*/,3/*vs/editor/common/core/range*/,88/*vs/editor/common/view/renderingContext*/,436/*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; _this._lineHeight = _this._context.configuration.editor.lineHeight; _this._typicalHalfwidthCharacterWidth = _this._context.configuration.editor.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) { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; } if (e.fontInfo) { this._typicalHalfwidthCharacterWidth = this._context.configuration.editor.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]; 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[156/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([0/*require*/,1/*exports*/,71/*vs/editor/browser/view/dynamicViewOverlay*/,434/*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; _this._lineHeight = _this._context.configuration.editor.lineHeight; _this._glyphMargin = _this._context.configuration.editor.viewInfo.glyphMargin; _this._glyphMarginLeft = _this._context.configuration.editor.layoutInfo.glyphMarginLeft; _this._glyphMarginWidth = _this._context.configuration.editor.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) { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; } if (e.viewInfo) { this._glyphMargin = this._context.configuration.editor.viewInfo.glyphMargin; } if (e.layoutInfo) { this._glyphMarginLeft = this._context.configuration.editor.layoutInfo.glyphMarginLeft; this._glyphMarginWidth = this._context.configuration.editor.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[235/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([0/*require*/,1/*exports*/,26/*vs/base/browser/fastDomNode*/,33/*vs/editor/browser/view/viewPart*/,420/*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; _this._widgets = {}; _this._verticalScrollbarWidth = _this._context.configuration.editor.layoutInfo.verticalScrollbarWidth; _this._minimapWidth = _this._context.configuration.editor.layoutInfo.minimapWidth; _this._horizontalScrollbarHeight = _this._context.configuration.editor.layoutInfo.horizontalScrollbarHeight; _this._editorHeight = _this._context.configuration.editor.layoutInfo.height; _this._editorWidth = _this._context.configuration.editor.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) { if (e.layoutInfo) { this._verticalScrollbarWidth = this._context.configuration.editor.layoutInfo.verticalScrollbarWidth; this._minimapWidth = this._context.configuration.editor.layoutInfo.minimapWidth; this._horizontalScrollbarHeight = this._context.configuration.editor.layoutInfo.horizontalScrollbarHeight; this._editorHeight = this._context.configuration.editor.layoutInfo.height; this._editorWidth = this._context.configuration.editor.layoutInfo.width; return true; } return false; }; // ---- 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[236/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/], __M([0/*require*/,1/*exports*/,26/*vs/base/browser/fastDomNode*/,212/*vs/editor/common/view/overviewZoneManager*/,86/*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; _this._domNode = fastDomNode_1.createFastDomNode(document.createElement('canvas')); _this._domNode.setClassName(cssClassName); _this._domNode.setPosition('absolute'); _this._domNode.setLayerHinting(true); _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(_this._context.configuration.editor.lineHeight); _this._zoneManager.setPixelRatio(_this._context.configuration.editor.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) { if (e.lineHeight) { this._zoneManager.setLineHeight(this._context.configuration.editor.lineHeight); this._render(); } if (e.pixelRatio) { this._zoneManager.setPixelRatio(this._context.configuration.editor.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[237/*vs/editor/browser/viewParts/viewZones/viewZones*/], __M([0/*require*/,1/*exports*/,26/*vs/base/browser/fastDomNode*/,10/*vs/base/common/errors*/,33/*vs/editor/browser/view/viewPart*/,12/*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 ViewZones = /** @class */ (function (_super) { __extends(ViewZones, _super); function ViewZones(context) { var _this = _super.call(this, context) || this; _this._lineHeight = _this._context.configuration.editor.lineHeight; _this._contentWidth = _this._context.configuration.editor.layoutInfo.contentWidth; _this._contentLeft = _this._context.configuration.editor.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 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); if (this._context.viewLayout.changeWhitespace(parseInt(id, 10), props.afterViewLineNumber, props.heightInPx)) { this._safeCallOnComputedHeight(zone.delegate, props.heightInPx); hadAChange = true; } } return hadAChange; }; ViewZones.prototype.onConfigurationChanged = function (e) { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; return this._recomputeWhitespacesProps(); } if (e.layoutInfo) { this._contentWidth = this._context.configuration.editor.layoutInfo.contentWidth; this._contentLeft = this._context.configuration.editor.layoutInfo.contentLeft; } 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.addZone = function (zone) { var props = this._computeWhitespaceProps(zone); var whitespaceId = this._context.viewLayout.addWhitespace(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.toString()); 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.toString()); this.marginDomNode.appendChild(myZone.marginDomNode); } this._zones[myZone.whitespaceId.toString()] = myZone; this.setShouldRender(); return myZone.whitespaceId; }; ViewZones.prototype.removeZone = function (id) { if (this._zones.hasOwnProperty(id.toString())) { var zone = this._zones[id.toString()]; delete this._zones[id.toString()]; this._context.viewLayout.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 (id) { var changed = false; if (this._zones.hasOwnProperty(id.toString())) { var zone = this._zones[id.toString()]; var props = this._computeWhitespaceProps(zone.delegate); // const newOrdinal = this._getZoneOrdinal(zone.delegate); changed = this._context.viewLayout.changeWhitespace(zone.whitespaceId, props.afterViewLineNumber, props.heightInPx) || changed; // TODO@Alex: change `newOrdinal` too if (changed) { this._safeCallOnComputedHeight(zone.delegate, props.heightInPx); this.setShouldRender(); } } return changed; }; ViewZones.prototype.shouldSuppressMouseDownOnViewZone = function (id) { if (this._zones.hasOwnProperty(id.toString())) { var zone = this._zones[id.toString()]; 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.toString()] = 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; }); /*--------------------------------------------------------------------------------------------- * 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, tokens) { this.content = content; this.continuesWithWrappedLine = continuesWithWrappedLine; this.minColumn = minColumn; this.maxColumn = maxColumn; this.tokens = tokens; } return ViewLineData; }()); exports.ViewLineData = ViewLineData; var ViewLineRenderingData = /** @class */ (function () { function ViewLineRenderingData(minColumn, maxColumn, content, continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, tokens, inlineDecorations, tabSize) { 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; } 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[239/*vs/editor/common/viewLayout/viewLayout*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,206/*vs/base/common/scrollable*/,228/*vs/editor/common/viewLayout/linesLayout*/,69/*vs/editor/common/viewModel/viewModel*/]), function (require, exports, lifecycle_1, scrollable_1, linesLayout_1, viewModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var SMOOTH_SCROLLING_TIME = 125; var ViewLayout = /** @class */ (function (_super) { __extends(ViewLayout, _super); function ViewLayout(configuration, lineCount, scheduleAtNextAnimationFrame) { var _this = _super.call(this) || this; _this._configuration = configuration; _this._linesLayout = new linesLayout_1.LinesLayout(lineCount, _this._configuration.editor.lineHeight); _this.scrollable = _this._register(new scrollable_1.Scrollable(0, scheduleAtNextAnimationFrame)); _this._configureSmoothScrollDuration(); _this.scrollable.setScrollDimensions({ width: configuration.editor.layoutInfo.contentWidth, height: configuration.editor.layoutInfo.contentHeight }); _this.onDidScroll = _this.scrollable.onScroll; _this._updateHeight(); return _this; } ViewLayout.prototype.dispose = function () { _super.prototype.dispose.call(this); }; ViewLayout.prototype.onHeightMaybeChanged = function () { this._updateHeight(); }; ViewLayout.prototype._configureSmoothScrollDuration = function () { this.scrollable.setSmoothScrollDuration(this._configuration.editor.viewInfo.smoothScrolling ? SMOOTH_SCROLLING_TIME : 0); }; // ---- begin view event handlers ViewLayout.prototype.onConfigurationChanged = function (e) { if (e.lineHeight) { this._linesLayout.setLineHeight(this._configuration.editor.lineHeight); } if (e.layoutInfo) { this.scrollable.setScrollDimensions({ width: this._configuration.editor.layoutInfo.contentWidth, height: this._configuration.editor.layoutInfo.contentHeight }); } if (e.viewInfo) { this._configureSmoothScrollDuration(); } this._updateHeight(); }; 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 (scrollDimensions) { if (this._configuration.editor.viewInfo.scrollbar.horizontal === 2 /* Hidden */) { // horizontal scrollbar not visible return 0; } if (scrollDimensions.width >= scrollDimensions.scrollWidth) { // horizontal scrollbar not visible return 0; } return this._configuration.editor.viewInfo.scrollbar.horizontalScrollbarSize; }; ViewLayout.prototype._getTotalHeight = function () { var scrollDimensions = this.scrollable.getScrollDimensions(); var result = this._linesLayout.getLinesTotalHeight(); if (this._configuration.editor.viewInfo.scrollBeyondLastLine) { result += scrollDimensions.height - this._configuration.editor.lineHeight; } else { result += this._getHorizontalScrollbarHeight(scrollDimensions); } return Math.max(scrollDimensions.height, result); }; ViewLayout.prototype._updateHeight = function () { this.scrollable.setScrollDimensions({ scrollHeight: this._getTotalHeight() }); }; // ---- 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._computeScrollWidth = function (maxLineWidth, viewportWidth) { var isViewportWrapping = this._configuration.editor.wrappingInfo.isViewportWrapping; if (!isViewportWrapping) { var extraHorizontalSpace = this._configuration.editor.viewInfo.scrollBeyondLastColumn * this._configuration.editor.fontInfo.typicalHalfwidthCharacterWidth; var whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth(); return Math.max(maxLineWidth + extraHorizontalSpace, viewportWidth, whitespaceMinWidth); } return Math.max(maxLineWidth, viewportWidth); }; ViewLayout.prototype.onMaxLineWidthChanged = function (maxLineWidth) { var newScrollWidth = this._computeScrollWidth(maxLineWidth, this.getCurrentViewport().width); this.scrollable.setScrollDimensions({ scrollWidth: newScrollWidth }); // 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.addWhitespace = function (afterLineNumber, ordinal, height, minWidth) { return this._linesLayout.insertWhitespace(afterLineNumber, ordinal, height, minWidth); }; ViewLayout.prototype.changeWhitespace = function (id, newAfterLineNumber, newHeight) { return this._linesLayout.changeWhitespace(id, newAfterLineNumber, newHeight); }; ViewLayout.prototype.removeWhitespace = function (id) { return this._linesLayout.removeWhitespace(id); }; 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.getScrollWidth = function () { var scrollDimensions = this.scrollable.getScrollDimensions(); return scrollDimensions.scrollWidth; }; 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[240/*vs/editor/common/viewModel/viewModelDecorations*/], __M([0/*require*/,1/*exports*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,69/*vs/editor/common/viewModel/viewModel*/]), function (require, exports, position_1, range_1, viewModel_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._clearCachedModelDecorationsResolver(); } 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, this.configuration.editor.readOnly); 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; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[241/*vs/editor/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; } 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[151/*vs/editor/contrib/codeAction/codeActionTrigger*/], __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.contains = function (other) { return this.value === other.value || strings_1.startsWith(other.value, this.value + CodeActionKind.sep); }; CodeActionKind.prototype.intersects = function (other) { return this.contains(other) || other.contains(this); }; CodeActionKind.sep = '.'; CodeActionKind.Empty = new CodeActionKind(''); CodeActionKind.QuickFix = new CodeActionKind('quickfix'); CodeActionKind.Refactor = new CodeActionKind('refactor'); CodeActionKind.Source = new CodeActionKind('source'); CodeActionKind.SourceOrganizeImports = new CodeActionKind('source.organizeImports'); CodeActionKind.SourceFixAll = new CodeActionKind('source.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.kind && !filter.kind.intersects(providedKind)) { return false; } // Don't return source actions unless they are explicitly requested if (CodeActionKind.Source.contains(providedKind) && !filter.includeSourceActions) { 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.kind) { if (!actionKind || !filter.kind.contains(actionKind)) { 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; }); /*--------------------------------------------------------------------------------------------- * 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) { 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) : new P(function (resolve) { resolve(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[243/*vs/editor/contrib/codeAction/codeActionWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,49/*vs/base/common/actions*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,12/*vs/editor/common/core/position*/]), function (require, exports, dom_1, actions_1, errors_1, event_1, position_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CodeActionContextMenu = /** @class */ (function () { function CodeActionContextMenu(_editor, _contextMenuService, _onApplyCodeAction) { this._editor = _editor; this._contextMenuService = _contextMenuService; this._onApplyCodeAction = _onApplyCodeAction; this._onDidExecuteCodeAction = new event_1.Emitter(); this.onDidExecuteCodeAction = this._onDidExecuteCodeAction.event; } CodeActionContextMenu.prototype.show = function (actionsToShow, at) { return __awaiter(this, void 0, void 0, function () { var codeActions, actions; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, actionsToShow]; case 1: codeActions = _a.sent(); if (!this._editor.getDomNode()) { // cancel when editor went off-dom return [2 /*return*/, Promise.reject(errors_1.canceled())]; } this._visible = true; actions = codeActions.actions.map(function (action) { return _this.codeActionToAction(action); }); this._contextMenuService.showContextMenu({ getAnchor: function () { if (position_1.Position.isIPosition(at)) { at = _this._toCoords(at); } return at || { x: 0, y: 0 }; }, getActions: function () { return actions; }, onHide: function () { _this._visible = false; _this._editor.focus(); }, autoSelectFirstItem: true }); return [2 /*return*/]; } }); }); }; CodeActionContextMenu.prototype.codeActionToAction = function (action) { var _this = this; var id = action.command ? action.command.id : action.title; var title = action.title; return new actions_1.Action(id, title, undefined, true, function () { return _this._onApplyCodeAction(action) .finally(function () { return _this._onDidExecuteCodeAction.fire(undefined); }); }); }; Object.defineProperty(CodeActionContextMenu.prototype, "isVisible", { get: function () { return this._visible; }, enumerable: true, configurable: true }); CodeActionContextMenu.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 }; }; return CodeActionContextMenu; }()); exports.CodeActionContextMenu = CodeActionContextMenu; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[244/*vs/editor/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[214/*vs/editor/contrib/comment/blockCommentCommand*/], __M([0/*require*/,1/*exports*/,55/*vs/editor/common/core/editOperation*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,39/*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) { this._selection = selection; 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, 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 (startTokenIndex + startToken.length < startLineText.length) { if (startLineText.charCodeAt(startTokenIndex + startToken.length) === 32 /* Space */) { // Pretend the start token contains a trailing space startToken = startToken + ' '; } } if (endTokenIndex > 0) { if (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._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) { 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 + ' ')); // Insert block comment end res.push(editOperation_1.EditOperation.insert(new position_1.Position(r.endLineNumber, r.endColumn), ' ' + 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, 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[246/*vs/editor/contrib/comment/lineCommentCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,55/*vs/editor/common/core/editOperation*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,39/*vs/editor/common/modes/languageConfigurationRegistry*/,214/*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) { this._selection = selection; this._tabSize = tabSize; this._type = type; this._deltaColumn = 0; } /** * 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, 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) { 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, model, startLineNumber, endLineNumber) { var lines = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber); if (lines === null) { return { supported: false }; } return LineCommentCommand._analyzeLines(type, 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 = LineCommentCommand._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); } else { ops = blockCommentCommand_1.BlockCommentCommand._createAddBlockCommentOperations(new range_1.Range(s.startLineNumber, model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), startToken, endToken); } 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, 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._createAddLineCommentsOperations = 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.insert(new position_1.Position(startLineNumber + i, lineData.commentStrOffset + 1), lineData.commentStr + ' ')); } return res; }; // TODO@Alex -> duplicated in characterHardWrappingLineMapper 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 = Number.MAX_VALUE; 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[247/*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; } 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 postion. 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[248/*vs/editor/contrib/find/findState*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,3/*vs/editor/common/core/range*/]), function (require, exports, event_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 () { function FindReplaceState() { 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._searchScope = null; this._matchesPosition = 0; this._matchesCount = 0; this._currentMatch = null; this._onFindReplaceStateChange = new event_1.Emitter(); } 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, "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, "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 }); Object.defineProperty(FindReplaceState.prototype, "onFindReplaceStateChange", { get: function () { return this._onFindReplaceStateChange.event; }, enumerable: true, configurable: true }); FindReplaceState.prototype.dispose = function () { }; 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, 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, searchScope: false, matchesPosition: false, matchesCount: false, currentMatch: false }; var somethingChanged = false; var oldEffectiveIsRegex = this.isRegex; var oldEffectiveWholeWords = this.wholeWord; var oldEffectiveMatchCase = this.matchCase; 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.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 */); 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 (somethingChanged) { this._onFindReplaceStateChange.fire(changeEvent); } }; return FindReplaceState; }()); 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[249/*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; } 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[250/*vs/editor/contrib/find/replacePattern*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "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) { if (this._state.kind === 0 /* StaticValue */) { 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[149/*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; } 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[252/*vs/editor/contrib/folding/foldingModel*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,149/*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._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, "onDidChange", { get: function () { return this._updateEventEmitter.event; }, 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 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_1 = lineNumbers; _i < lineNumbers_1.length; _i++) { var lineNumber = lineNumbers_1[_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, or if not set, all regions in the model. */ function setCollapseStateLevelsUp(foldingModel, doCollapse, levels, lineNumbers) { var toToggle = []; for (var _i = 0, lineNumbers_2 = lineNumbers; _i < lineNumbers_2.length; _i++) { var lineNumber = lineNumbers_2[_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; /** * 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[253/*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[208/*vs/editor/contrib/folding/syntaxRangeProvider*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,149/*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[255/*vs/editor/contrib/folding/intializingRangeProvider*/], __M([0/*require*/,1/*exports*/,208/*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[207/*vs/editor/contrib/format/formattingEdit*/], __M([0/*require*/,1/*exports*/,55/*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[205/*vs/editor/contrib/goToDefinition/clickLinkGesture*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/,17/*vs/base/common/platform*/,190/*vs/css!vs/editor/contrib/goToDefinition/goToDefinitionMouse*/]), 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.getConfiguration().multiCursorModifier); _this.lastMouseMoveEvent = null; _this.hasTriggerKeyOnMouseDown = false; _this._register(_this._editor.onDidChangeConfiguration(function (e) { if (e.multiCursorModifier) { var newOpts = createOptions(_this._editor.getConfiguration().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[203/*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. *--------------------------------------------------------------------------------------------*/ define(__m[202/*vs/editor/contrib/hover/hoverWidgets*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,51/*vs/base/browser/ui/scrollbar/scrollableElement*/,44/*vs/base/browser/ui/widget*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom_1, scrollableElement_1, widget_1, lifecycle_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; _this.disposables = []; // Editor.IContentWidget.allowEditorOverflow _this.allowEditorOverflow = true; _this._id = id; _this._editor = editor; _this._isVisible = 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.disposables.push(_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.fontInfo) { _this.updateFont(); } })); _this._editor.onDidLayoutChange(function (e) { return _this.layout(); }); _this.layout(); _this._editor.addContentWidget(_this); _this._showAtPosition = null; _this._showAtRange = null; 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); this.disposables = lifecycle_1.dispose(this.disposables); _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.getConfiguration().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.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.getConfiguration().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')); codeTags.concat(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[260/*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[261/*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[262/*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; } 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[263/*vs/editor/contrib/linesOperations/sortLinesCommand*/], __M([0/*require*/,1/*exports*/,55/*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; } 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; }; 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(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }); // 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[201/*vs/editor/contrib/smartSelect/bracketSelections*/], __M([0/*require*/,1/*exports*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,84/*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; 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; 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, kind: 'statement.brackets' }); bucket.push({ range: outerBracket, kind: 'statement.brackets.full' }); 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()), kind: 'statement.brackets.leading' }); bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(startLine, 1), bracket.getEndPosition()), kind: 'statement.brackets.leading.full' }); } // 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()), kind: 'statement.brackets.leading' }); bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(aboveLine, 1), bracket.getEndPosition()), kind: 'statement.brackets.leading.full' }); } } }; 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[265/*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(), kind: 'statement.all' }); } 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), kind: 'statement.word.part' }); } }; 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), kind: 'statement.word' }); } }; 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)), kind: 'statement.line' }); } }; 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. *--------------------------------------------------------------------------------------------*/ define(__m[145/*vs/editor/contrib/snippet/snippetParser*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _a; var Scanner = /** @class */ (function () { function Scanner() { this.text(''); } 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, [idx, 1].concat(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() { return _super !== null && _super.apply(this, arguments) || this; } 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 = marker.slice(); 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(); } 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) { if (this._token.type === 14 /* EOF */) { return false; } var start = this._token; while (this._token.type !== type) { this._token = this._scanner.next(); if (this._token.type === 14 /* EOF */) { return false; } } var value = this._scanner.value.substring(start.pos, this._token.pos); 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[267/*vs/editor/contrib/suggest/wordDistance*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,3/*vs/editor/common/core/range*/,201/*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) { if (!editor.getConfiguration().contribInfo.suggest.localityBonus) { return Promise.resolve(WordDistance.None); } if (!editor.hasModel()) { return Promise.resolve(WordDistance.None); } var model = editor.getModel(); var position = editor.getPosition(); if (!service.canComputeWordRanges(model.uri)) { return Promise.resolve(WordDistance.None); } return new bracketSelections_1.BracketSelectionRangeProvider().provideSelectionRanges(model, [position]).then(function (ranges) { if (!ranges || ranges.length === 0 || ranges[0].length === 0) { return WordDistance.None; } return service.computeWordRanges(model.uri, ranges[0][0].range).then(function (wordRanges) { 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 = suggestion.label; 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[198/*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[269/*vs/editor/standalone/common/monarch/monarchCompile*/], __M([0/*require*/,1/*exports*/,198/*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 idx in obj) { if (obj.hasOwnProperty(idx)) { if (!(elemType(obj[idx]))) { 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 idx in action) { if (action.hasOwnProperty(idx)) { results[idx] = compileAction(lexer, ruleName, action[idx]); } } 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 idx in cases_1) { if (cases_1.hasOwnProperty(idx)) { var _case = cases_1[idx]; 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 idx in rules) { if (rules.hasOwnProperty(idx)) { var rule = rules[idx]; 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 bracketIdx in json.brackets) { if (json.brackets.hasOwnProperty(bracketIdx)) { var desc = json.brackets[bracketIdx]; 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[270/*vs/nls!vs/base/browser/ui/actionbar/actionbar*/], __M([6/*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[79/*vs/base/browser/ui/actionbar/actionbar*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,270/*vs/nls!vs/base/browser/ui/actionbar/actionbar*/,2/*vs/base/common/lifecycle*/,49/*vs/base/common/actions*/,7/*vs/base/browser/dom*/,20/*vs/base/common/types*/,78/*vs/base/browser/touch*/,52/*vs/base/browser/keyboardEvent*/,4/*vs/base/common/event*/,19/*vs/base/common/arrays*/,501/*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, arrays_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var BaseActionItem = /** @class */ (function (_super) { __extends(BaseActionItem, _super); function BaseActionItem(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; } BaseActionItem.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(BaseActionItem.prototype, "actionRunner", { get: function () { return this._actionRunner; }, set: function (actionRunner) { this._actionRunner = actionRunner; }, enumerable: true, configurable: true }); BaseActionItem.prototype.getAction = function () { return this._action; }; BaseActionItem.prototype.isEnabled = function () { return this._action.enabled; }; BaseActionItem.prototype.setActionContext = function (newContext) { this._context = newContext; }; BaseActionItem.prototype.render = function (container) { var _this = this; this.element = container; touch_1.Gesture.addTarget(container); var enableDragging = this.options && this.options.draggable; if (enableDragging) { container.draggable = true; } this._register(DOM.addDisposableListener(this.element, touch_1.EventType.Tap, function (e) { return _this.onClick(e); })); this._register(DOM.addDisposableListener(this.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 && _this.element) { DOM.addClass(_this.element, 'active'); } })); this._register(DOM.addDisposableListener(this.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(this.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(_this.element, event, function (e) { DOM.EventHelper.stop(e); DOM.removeClass(_this.element, 'active'); })); }); }; BaseActionItem.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); }; BaseActionItem.prototype.focus = function () { if (this.element) { this.element.focus(); DOM.addClass(this.element, 'focused'); } }; BaseActionItem.prototype.blur = function () { if (this.element) { this.element.blur(); DOM.removeClass(this.element, 'focused'); } }; BaseActionItem.prototype.updateEnabled = function () { // implement in subclass }; BaseActionItem.prototype.updateLabel = function () { // implement in subclass }; BaseActionItem.prototype.updateTooltip = function () { // implement in subclass }; BaseActionItem.prototype.updateClass = function () { // implement in subclass }; BaseActionItem.prototype.updateChecked = function () { // implement in subclass }; BaseActionItem.prototype.dispose = function () { if (this.element) { DOM.removeNode(this.element); this.element = undefined; } _super.prototype.dispose.call(this); }; return BaseActionItem; }(lifecycle_1.Disposable)); exports.BaseActionItem = BaseActionItem; 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.radio = false; _this.enabled = false; return _this; } Separator.ID = 'vs.actions.separator'; return Separator; }(actions_1.Action)); exports.Separator = Separator; var ActionItem = /** @class */ (function (_super) { __extends(ActionItem, _super); function ActionItem(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; } ActionItem.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._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(); }; ActionItem.prototype.focus = function () { _super.prototype.focus.call(this); this.label.focus(); }; ActionItem.prototype.updateLabel = function () { if (this.options.label) { this.label.textContent = this.getAction().label; } }; ActionItem.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.title = title; } }; ActionItem.prototype.updateClass = function () { if (this.cssClass) { DOM.removeClasses(this.label, this.cssClass); } if (this.options.icon) { this.cssClass = this.getAction().class; DOM.addClass(this.label, 'icon'); if (this.cssClass) { DOM.addClasses(this.label, this.cssClass); } this.updateEnabled(); } else { DOM.removeClass(this.label, 'icon'); } }; ActionItem.prototype.updateEnabled = function () { if (this.getAction().enabled) { this.label.removeAttribute('aria-disabled'); if (this.element) { DOM.removeClass(this.element, 'disabled'); } DOM.removeClass(this.label, 'disabled'); this.label.tabIndex = 0; } else { this.label.setAttribute('aria-disabled', 'true'); if (this.element) { DOM.addClass(this.element, 'disabled'); } DOM.addClass(this.label, 'disabled'); DOM.removeTabIndexAndUpdateFocus(this.label); } }; ActionItem.prototype.updateChecked = function () { if (this.getAction().checked) { DOM.addClass(this.label, 'checked'); } else { DOM.removeClass(this.label, 'checked'); } }; return ActionItem; }(BaseActionItem)); exports.ActionItem = ActionItem; 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._onDidCancel = _this._register(new event_1.Emitter()); _this._onDidRun = _this._register(new event_1.Emitter()); _this._onDidBeforeRun = _this._register(new event_1.Emitter()); _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.items = []; _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; } Object.defineProperty(ActionBar.prototype, "onDidBlur", { get: function () { return this._onDidBlur.event; }, enumerable: true, configurable: true }); Object.defineProperty(ActionBar.prototype, "onDidCancel", { get: function () { return this._onDidCancel.event; }, enumerable: true, configurable: true }); Object.defineProperty(ActionBar.prototype, "onDidRun", { get: function () { return this._onDidRun.event; }, enumerable: true, configurable: true }); Object.defineProperty(ActionBar.prototype, "onDidBeforeRun", { get: function () { return this._onDidBeforeRun.event; }, enumerable: true, configurable: true }); 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.items.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 = arrays_1.asArray(arg); var index = types.isNumber(options.index) ? options.index : null; actions.forEach(function (action) { var actionItemElement = document.createElement('li'); actionItemElement.className = 'action-item'; actionItemElement.setAttribute('role', 'presentation'); // Prevent native context menu on actions _this._register(DOM.addDisposableListener(actionItemElement, DOM.EventType.CONTEXT_MENU, function (e) { e.preventDefault(); e.stopPropagation(); })); var item; if (_this.options.actionItemProvider) { item = _this.options.actionItemProvider(action); } if (!item) { item = new ActionItem(_this.context, action, options); } item.actionRunner = _this._actionRunner; item.setActionContext(_this.context); item.render(actionItemElement); if (index === null || index < 0 || index >= _this.actionsList.children.length) { _this.actionsList.appendChild(actionItemElement); _this.items.push(item); } else { _this.actionsList.insertBefore(actionItemElement, _this.actionsList.children[index]); _this.items.splice(index, 0, item); index++; } }); }; ActionBar.prototype.clear = function () { this.items = lifecycle_1.dispose(this.items); DOM.clearNode(this.actionsList); }; ActionBar.prototype.isEmpty = function () { return this.items.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.items.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.items.length - 1; } var startIndex = this.focusedItem; var item; do { this.focusedItem = (this.focusedItem + 1) % this.items.length; item = this.items[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.items.length - 1; } item = this.items[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) { if (typeof this.focusedItem === 'undefined') { this.actionsList.focus(); } for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; var actionItem = item; if (i === this.focusedItem) { if (types.isFunction(actionItem.isEnabled)) { if (actionItem.isEnabled() && types.isFunction(actionItem.focus)) { actionItem.focus(fromRight); } else { this.actionsList.focus(); } } } else { if (types.isFunction(actionItem.blur)) { actionItem.blur(); } } } }; ActionBar.prototype.doTrigger = function (event) { if (typeof this.focusedItem === 'undefined') { return; //nothing to focus } // trigger action var actionItem = this.items[this.focusedItem]; if (actionItem instanceof BaseActionItem) { var context_1 = (actionItem._context === null || actionItem._context === undefined) ? event : actionItem._context; this.run(actionItem._action, context_1); } }; 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.items); this.items = []; DOM.removeNode(this.getContainer()); _super.prototype.dispose.call(this); }; return ActionBar; }(lifecycle_1.Disposable)); exports.ActionBar = ActionBar; }); define(__m[274/*vs/nls!vs/base/browser/ui/aria/aria*/], __M([6/*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[47/*vs/base/browser/ui/aria/aria*/], __M([0/*require*/,1/*exports*/,274/*vs/nls!vs/base/browser/ui/aria/aria*/,17/*vs/base/common/platform*/,7/*vs/base/browser/dom*/,498/*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[276/*vs/nls!vs/base/browser/ui/findinput/findInput*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/findInput", data); }); define(__m[277/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([6/*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[189/*vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([0/*require*/,1/*exports*/,492/*vs/base/browser/ui/checkbox/checkbox*/,277/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/,472/*vs/css!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: 'monaco-case-sensitive', title: NLS_CASE_SENSITIVE_CHECKBOX_LABEL + opts.appendTitle, isChecked: opts.isChecked, inputActiveOptionBorder: opts.inputActiveOptionBorder }) || 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: 'monaco-whole-word', title: NLS_WHOLE_WORD_CHECKBOX_LABEL + opts.appendTitle, isChecked: opts.isChecked, inputActiveOptionBorder: opts.inputActiveOptionBorder }) || 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: 'monaco-regex', title: NLS_REGEX_CHECKBOX_LABEL + opts.appendTitle, isChecked: opts.isChecked, inputActiveOptionBorder: opts.inputActiveOptionBorder }) || this; } return RegexCheckbox; }(checkbox_1.Checkbox)); exports.RegexCheckbox = RegexCheckbox; }); define(__m[279/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/], __M([6/*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[136/*vs/base/browser/ui/inputbox/inputBox*/], __M([0/*require*/,1/*exports*/,279/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/,30/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,119/*vs/base/browser/htmlContentRenderer*/,47/*vs/base/browser/ui/aria/aria*/,79/*vs/base/browser/ui/actionbar/actionbar*/,4/*vs/base/common/event*/,44/*vs/base/browser/ui/widget*/,28/*vs/base/common/color*/,31/*vs/base/common/objects*/,563/*vs/base/common/history*/,468/*vs/css!vs/base/browser/ui/inputbox/inputBox*/]), function (require, exports, nls, Bal, dom, htmlContentRenderer_1, aria, actionbar_1, event_1, widget_1, color_1, objects_1, history_1) { "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._onDidChange = _this._register(new event_1.Emitter()); _this.onDidChange = _this._onDidChange.event; _this._onDidHeightChange = _this._register(new event_1.Emitter()); _this.contextViewProvider = contextViewProvider; _this.options = options || Object.create(null); objects_1.mixin(_this.options, defaultOpts, false); _this.message = null; _this.cachedHeight = 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')); _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.mirror = dom.append(wrapper, $('div.mirror')); _this.mirror.innerHTML = ' '; } 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(); }); } setTimeout(function () { if (!_this.input) { 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) { if (this.input) { this.input.setAttribute('placeholder', placeHolder); this.input.title = placeHolder; } }; InputBox.prototype.setAriaLabel = function (label) { this.ariaLabel = label; if (this.input) { if (label) { this.input.setAttribute('aria-label', this.ariaLabel); } else { this.input.removeAttribute('aria-label'); } } }; Object.defineProperty(InputBox.prototype, "mirrorElement", { get: function () { return this.mirror; }, enumerable: true, configurable: true }); 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 }); 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.input.disabled = true; this._hideMessage(); }; InputBox.prototype.setEnabled = function (enabled) { if (enabled) { this.enable(); } else { this.disable(); } }; Object.defineProperty(InputBox.prototype, "width", { get: function () { return dom.getTotalWidth(this.input); }, set: function (width) { this.input.style.width = width + 'px'; if (this.mirror) { this.mirror.style.width = width + 'px'; } }, enumerable: true, configurable: true }); 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 : null; // 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.state = 'open'; 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 ? htmlContentRenderer_1.renderFormattedText(_this.message.content, renderOptions) : htmlContentRenderer_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() : null; spanElement.style.color = styles.foreground ? styles.foreground.toString() : null; spanElement.style.border = styles.border ? "1px solid " + styles.border : null; dom.append(div, spanElement); return null; }, layout: layout }); }; InputBox.prototype._hideMessage = function () { if (!this.contextViewProvider || this.state !== 'open') { return; } this.state = 'idle'; this.contextViewProvider.hideContextView(); }; InputBox.prototype.onValueChange = function () { this._onDidChange.fire(this.value); this.validate(); this.updateMirror(); if (this.state === 'open' && this.contextViewProvider) { this.contextViewProvider.layout(); } }; InputBox.prototype.updateMirror = function () { if (!this.mirror) { return; } var value = this.value || this.placeholder; 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 () { if (this.element) { var background = this.inputBackground ? this.inputBackground.toString() : null; var foreground = this.inputForeground ? this.inputForeground.toString() : null; var border = this.inputBorder ? this.inputBorder.toString() : null; 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' : null; this.element.style.borderStyle = border ? 'solid' : null; this.element.style.borderColor = border; } }; InputBox.prototype.layout = function () { if (!this.mirror) { return; } var previousHeight = this.cachedHeight; this.cachedHeight = dom.getTotalHeight(this.mirror); if (previousHeight !== this.cachedHeight) { this.input.style.height = this.cachedHeight + 'px'; this._onDidHeightChange.fire(this.cachedHeight); } }; InputBox.prototype.dispose = function () { this._hideMessage(); this.element = null; // StrictNullOverride: nulling out ok in dispose this.input = null; // StrictNullOverride: nulling out ok in dispose this.contextViewProvider = undefined; this.message = null; this.validation = undefined; this.state = null; this.actionbar = undefined; _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[281/*vs/base/browser/ui/findinput/findInput*/], __M([0/*require*/,1/*exports*/,276/*vs/nls!vs/base/browser/ui/findinput/findInput*/,7/*vs/base/browser/dom*/,136/*vs/base/browser/ui/inputbox/inputBox*/,44/*vs/base/browser/ui/widget*/,4/*vs/base/common/event*/,189/*vs/base/browser/ui/findinput/findInputCheckboxes*/,473/*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._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.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; _this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history || [], !!options.flexibleHeight); 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.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, }; 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.buildDomNode = function (appendCaseSensitiveLabel, appendWholeWordsLabel, appendRegexLabel, history, flexibleHeight) { var _this = this; 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 })); this.regex = this._register(new findInputCheckboxes_1.RegexCheckbox({ appendTitle: appendRegexLabel, isChecked: false, inputActiveOptionBorder: this.inputActiveOptionBorder })); 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 })); 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 })); 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) { var paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px'; this.inputBox.inputElement.style.paddingRight = paddingRight; if (this.inputBox.mirrorElement) { this.inputBox.mirrorElement.style.paddingRight = paddingRight; } } // 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); }; FindInput.prototype.validate = function () { if (this.inputBox) { this.inputBox.validate(); } }; FindInput.prototype.clearMessage = function () { if (this.inputBox) { this.inputBox.hideMessage(); } }; FindInput.prototype.dispose = function () { _super.prototype.dispose.call(this); }; return FindInput; }(widget_1.Widget)); exports.FindInput = FindInput; }); define(__m[282/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/keybindingLabel/keybindingLabel", data); }); define(__m[283/*vs/nls!vs/base/browser/ui/list/listWidget*/], __M([6/*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. *--------------------------------------------------------------------------------------------*/ define(__m[135/*vs/base/browser/ui/list/listWidget*/], __M([0/*require*/,1/*exports*/,283/*vs/nls!vs/base/browser/ui/list/listWidget*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,19/*vs/base/common/arrays*/,152/*vs/base/common/decorators*/,7/*vs/base/browser/dom*/,17/*vs/base/common/platform*/,78/*vs/base/browser/touch*/,52/*vs/base/browser/keyboardEvent*/,4/*vs/base/common/event*/,62/*vs/base/browser/event*/,581/*vs/base/browser/ui/list/list*/,117/*vs/base/browser/ui/list/listView*/,28/*vs/base/common/color*/,31/*vs/base/common/objects*/,574/*vs/base/browser/ui/list/splice*/,139/*vs/base/common/numbers*/,65/*vs/base/common/filters*/,462/*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(); } Object.defineProperty(Trait.prototype, "onChange", { get: function () { return this._onChange.event; }, enumerable: true, configurable: true }); 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 = this.sortedIndexes.filter(function (i) { return i < start; }).concat(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, indexes.slice().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 () { this._onChange = 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; var multipleSelectionSupport = !(options.multipleSelectionSupport === false); this.disposables = []; 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 = lifecycle_1.dispose(this.disposables); }; return KeyboardController; }()); var TypeLabelControllerState; (function (TypeLabelControllerState) { TypeLabelControllerState[TypeLabelControllerState["Idle"] = 0] = "Idle"; TypeLabelControllerState[TypeLabelControllerState["Typing"] = 1] = "Typing"; })(TypeLabelControllerState || (TypeLabelControllerState = {})); function mightProducePrintableCharacter(event) { if (event.ctrlKey || event.metaKey || event.altKey) { return false; } return (event.keyCode >= 31 /* KEY_A */ && event.keyCode <= 56 /* KEY_Z */) || (event.keyCode >= 21 /* KEY_0 */ && event.keyCode <= 30 /* KEY_9 */) || (event.keyCode >= 80 /* US_SEMICOLON */ && event.keyCode <= 90 /* US_QUOTE */); } exports.mightProducePrintableCharacter = mightProducePrintableCharacter; var TypeLabelController = /** @class */ (function () { function TypeLabelController(list, view, keyboardNavigationLabelProvider) { this.list = list; this.view = view; this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider; this.enabled = false; this.state = TypeLabelControllerState.Idle; this.automaticKeyboardNavigation = true; this.triggered = false; this.enabledDisposables = []; this.disposables = []; 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(this.keyboardNavigationLabelProvider.mightProducePrintableCharacter ? function (e) { return _this.keyboardNavigationLabelProvider.mightProducePrintableCharacter(e); } : function (e) { return 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 = lifecycle_1.dispose(this.enabledDisposables); 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.disposables = lifecycle_1.dispose(this.disposables); }; return TypeLabelController; }()); var DOMFocusController = /** @class */ (function () { function DOMFocusController(list, view) { this.list = list; this.view = view; this.disposables = []; this.disposables = []; 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 = lifecycle_1.dispose(this.disposables); }; 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 = []; 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); 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; }); if (selection.length === newSelection.length) { this.list.setSelection(newSelection.concat([focus]), e.browserEvent); } else { this.list.setSelection(newSelection, e.browserEvent); } } }; MouseController.prototype.dispose = function () { this.disposables = lifecycle_1.dispose(this.disposables); }; 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.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-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('#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 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, dynamicHeightProbing) { var i = 0; for (var _i = 0, _a = this.renderers; _i < _a.length; _i++) { var renderer = _a[_i]; renderer.renderElement(element, index, templateData[i++], dynamicHeightProbing); } }; PipelineRenderer.prototype.disposeElement = function (element, index, templateData, dynamicHeightProbing) { 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], dynamicHeightProbing); } 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) { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(elements); } 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.drop = function (data, targetElement, targetIndex, originalEvent) { this.dnd.drop(data, targetElement, targetIndex, originalEvent); }; return ListViewDragAndDrop; }()); var List = /** @class */ (function () { function List(container, virtualDelegate, renderers, _options) { if (_options === void 0) { _options = DefaultOptions; } this._options = _options; this.eventBufferer = new event_1.EventBufferer(); this._onDidOpen = new event_1.Emitter(); this.onDidOpen = this._onDidOpen.event; this._onPin = new event_1.Emitter(); this.didJustPressContextMenuKey = false; this._onDidDispose = new event_1.Emitter(); this.focus = new FocusTrait(); this.selection = new Trait('selected'); objects_1.mixin(_options, defaultStyles, false); var baseRenderers = [this.focus.renderer, this.selection.renderer]; if (_options.accessibilityProvider) { baseRenderers.push(new AccessibiltyRenderer(_options.accessibilityProvider)); } renderers = renderers.map(function (r) { return new PipelineRenderer(r.templateId, baseRenderers.concat([r])); }); var viewOptions = __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); } this.styleElement = DOM.createStyleSheet(this.view.domNode); this.styleController = _options.styleController || new DefaultStyleController(this.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 = [this.focus, this.selection, this.view, 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.push(new DOMFocusController(this, this.view)); if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { var controller = new KeyboardController(this, this.view, _options); this.disposables.push(controller); } if (_options.keyboardNavigationLabelProvider) { this.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider); this.disposables.push(this.typeLabelController); } this.disposables.push(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)); } this.style(_options); } 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, "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 }); Object.defineProperty(List.prototype, "onDidDispose", { get: function () { return this._onDidDispose.event; }, 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({}, 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 Error("Invalid start index: " + start); } if (deleteCount < 0) { throw new Error("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 Error("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 Error("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 Error("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) { 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 Error("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 Error("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) { 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 Error("Invalid index " + index); } } this._onPin.fire(indexes); }; 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(); if (focus.length > 0) { this.view.domNode.setAttribute('aria-activedescendant', this.view.getElementDomId(focus[0])); } else { this.view.domNode.removeAttribute('aria-activedescendant'); } this.view.domNode.setAttribute('role', 'tree'); DOM.toggleClass(this.view.domNode, 'element-focused', focus.length > 0); }; 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 = lifecycle_1.dispose(this.disposables); this._onDidOpen.dispose(); this._onPin.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[285/*vs/nls!vs/base/browser/ui/menu/menu*/], __M([6/*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. *--------------------------------------------------------------------------------------------*/ define(__m[286/*vs/base/browser/ui/menu/menu*/], __M([0/*require*/,1/*exports*/,285/*vs/nls!vs/base/browser/ui/menu/menu*/,5/*vs/base/common/strings*/,49/*vs/base/common/actions*/,79/*vs/base/browser/ui/actionbar/actionbar*/,7/*vs/base/browser/dom*/,52/*vs/base/browser/keyboardEvent*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,51/*vs/base/browser/ui/scrollbar/scrollableElement*/,4/*vs/base/common/event*/,17/*vs/base/common/platform*/,461/*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, event_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function createMenuMnemonicRegExp() { try { return new RegExp('\\(&([^\\s&])\\)|(? 1) { var action = actions_2.shift(); if (action) { _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.items.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.scrollTopHold = _this.menuElement.scrollTop; _this.updateFocus(); e.stopPropagation(); } })); _this._register(dom_1.addDisposableListener(_this.domNode, dom_1.EventType.MOUSE_UP, function (e) { // Absorb clicks in menu dead space https://github.com/Microsoft/vscode/issues/63575 dom_1.EventHelper.stop(e, true); })); _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.scrollTopHold = _this.menuElement.scrollTop; _this.setFocusedItem(target); if (lastFocusedItem !== _this.focusedItem) { _this.updateFocus(); } } })); var parentData = { parent: _this }; _this.mnemonics = new Map(); _this.push(actions, { icon: true, label: true, isMenu: true }); // 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 = null; menuElement.style.maxHeight = Math.max(10, window.innerHeight - container.getBoundingClientRect().top - 30) + "px"; _this.scrollableElement.onScroll(function () { _this._onScroll.fire(); }, _this, _this.menuDisposables); _this._register(dom_1.addDisposableListener(_this.menuElement, dom_1.EventType.SCROLL, function (e) { if (_this.scrollTopHold !== undefined) { _this.menuElement.scrollTop = _this.scrollTopHold; _this.scrollTopHold = undefined; } _this.scrollableElement.scanDomNode(); })); container.appendChild(_this.scrollableElement.getDomNode()); _this.scrollableElement.scanDomNode(); _this.items.filter(function (item) { return !(item instanceof MenuSeparatorActionItem); }).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 : null; var bgColor = style.backgroundColor ? "" + style.backgroundColor : null; var border = style.borderColor ? "2px solid " + style.borderColor : null; var shadow = style.shadowColor ? "0 2px 4px " + style.shadowColor : null; container.style.border = border; this.domNode.style.color = fgColor; this.domNode.style.backgroundColor = bgColor; container.style.boxShadow = shadow; if (this.items) { this.items.forEach(function (item) { if (item instanceof MenuActionItem || item instanceof MenuSeparatorActionItem) { item.style(style); } }); } }; Menu.prototype.getContainer = function () { return this.scrollableElement.getDomNode(); }; Object.defineProperty(Menu.prototype, "onScroll", { get: function () { return this._onScroll.event; }, 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.doGetActionItem = function (action, options, parentData) { if (action instanceof actionbar_1.Separator) { return new MenuSeparatorActionItem(options.context, action, { icon: true }); } else if (action instanceof SubmenuAction) { var menuActionItem = new SubmenuActionItem(action, action.entries, parentData, options); if (options.enableMnemonics) { var mnemonic = menuActionItem.getMnemonic(); if (mnemonic && menuActionItem.isEnabled()) { var actionItems = []; if (this.mnemonics.has(mnemonic)) { actionItems = this.mnemonics.get(mnemonic); } actionItems.push(menuActionItem); this.mnemonics.set(mnemonic, actionItems); } } return menuActionItem; } 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 menuActionItem = new MenuActionItem(options.context, action, menuItemOptions); if (options.enableMnemonics) { var mnemonic = menuActionItem.getMnemonic(); if (mnemonic && menuActionItem.isEnabled()) { var actionItems = []; if (this.mnemonics.has(mnemonic)) { actionItems = this.mnemonics.get(mnemonic); } actionItems.push(menuActionItem); this.mnemonics.set(mnemonic, actionItems); } } return menuActionItem; } }; return Menu; }(actionbar_1.ActionBar)); exports.Menu = Menu; var MenuActionItem = /** @class */ (function (_super) { __extends(MenuActionItem, _super); function MenuActionItem(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[2]).toLocaleLowerCase(); } } } return _this; } MenuActionItem.prototype.render = function (container) { var _this = this; _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')); 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; } this._register(dom_1.addDisposableListener(this.element, dom_1.EventType.MOUSE_UP, function (e) { dom_1.EventHelper.stop(e, true); _this.onClick(e); })); this.updateClass(); this.updateLabel(); this.updateTooltip(); this.updateEnabled(); this.updateChecked(); }; MenuActionItem.prototype.blur = function () { _super.prototype.blur.call(this); this.applyStyle(); }; MenuActionItem.prototype.focus = function () { _super.prototype.focus.call(this); this.item.focus(); this.applyStyle(); }; MenuActionItem.prototype.updatePositionInSet = function (pos, setSize) { this.item.setAttribute('aria-posinset', "" + pos); this.item.setAttribute('aria-setsize', "" + setSize); }; MenuActionItem.prototype.updateLabel = function () { if (this.options.label) { var label = this.getAction().label; if (label) { var cleanLabel = cleanMnemonic(label); if (!this.options.enableMnemonics) { label = cleanLabel; } this.label.setAttribute('aria-label', cleanLabel.replace(/&&/g, '&')); var matches = exports.MENU_MNEMONIC_REGEX.exec(label); if (matches) { label = strings.escape(label).replace(exports.MENU_ESCAPED_MNEMONIC_REGEX, ''); label = label.replace(/&&/g, '&'); this.item.setAttribute('aria-keyshortcuts', (!!matches[1] ? matches[1] : matches[2]).toLocaleLowerCase()); } else { label = label.replace(/&&/g, '&'); } } this.label.innerHTML = label.trim(); } }; MenuActionItem.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.title = title; } }; MenuActionItem.prototype.updateClass = function () { if (this.cssClass) { dom_1.removeClasses(this.item, this.cssClass); } if (this.options.icon) { this.cssClass = this.getAction().class || ''; dom_1.addClass(this.label, 'icon'); if (this.cssClass) { dom_1.addClasses(this.label, this.cssClass); } this.updateEnabled(); } else { dom_1.removeClass(this.label, 'icon'); } }; MenuActionItem.prototype.updateEnabled = function () { if (this.getAction().enabled) { if (this.element) { dom_1.removeClass(this.element, 'disabled'); } dom_1.removeClass(this.item, 'disabled'); this.item.tabIndex = 0; } else { if (this.element) { dom_1.addClass(this.element, 'disabled'); } dom_1.addClass(this.item, 'disabled'); dom_1.removeTabIndexAndUpdateFocus(this.item); } }; MenuActionItem.prototype.updateChecked = function () { 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'); } }; MenuActionItem.prototype.getMnemonic = function () { return this.mnemonic; }; MenuActionItem.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 : this.menuStyle.backgroundColor; var border = isSelected && this.menuStyle.selectionBorderColor ? "1px solid " + this.menuStyle.selectionBorderColor : null; this.item.style.color = fgColor ? "" + fgColor : null; this.check.style.backgroundColor = fgColor ? "" + fgColor : null; this.item.style.backgroundColor = bgColor ? "" + bgColor : null; this.container.style.border = border; }; MenuActionItem.prototype.style = function (style) { this.menuStyle = style; this.applyStyle(); }; return MenuActionItem; }(actionbar_1.BaseActionItem)); var SubmenuActionItem = /** @class */ (function (_super) { __extends(SubmenuActionItem, _super); function SubmenuActionItem(action, submenuActions, parentData, submenuOptions) { var _this = _super.call(this, action, action, submenuOptions) || this; _this.submenuActions = submenuActions; _this.parentData = parentData; _this.submenuOptions = submenuOptions; _this.submenuDisposables = []; _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; } SubmenuActionItem.prototype.render = function (container) { var _this = this; _super.prototype.render.call(this, container); if (!this.element) { return; } dom_1.addClass(this.item, 'monaco-submenu-item'); this.item.setAttribute('aria-haspopup', 'true'); this.submenuIndicator = dom_1.append(this.item, dom_1.$('span.submenu-indicator')); 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 (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); })); }; SubmenuActionItem.prototype.onClick = function (e) { // stop clicking from trying to run an action dom_1.EventHelper.stop(e, true); this.cleanupExistingSubmenu(false); this.createSubmenu(false); }; SubmenuActionItem.prototype.cleanupExistingSubmenu = function (force) { if (this.parentData.submenu && (force || (this.parentData.submenu !== this.mysubmenu))) { this.parentData.submenu.dispose(); this.parentData.submenu = undefined; if (this.submenuContainer) { this.submenuDisposables = lifecycle_1.dispose(this.submenuDisposables); this.submenuContainer = undefined; } } }; SubmenuActionItem.prototype.createSubmenu = function (selectFirstItem) { var _this = this; if (selectFirstItem === void 0) { selectFirstItem = true; } if (!this.element) { return; } if (!this.parentData.submenu) { this.submenuContainer = dom_1.append(this.element, dom_1.$('div.monaco-submenu')); dom_1.addClasses(this.submenuContainer, 'menubar-menu-items-holder', 'context-view'); 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(); var computedStyles = getComputedStyle(this.parentData.parent.domNode); var paddingTop = parseFloat(computedStyles.paddingTop || '0') || 0; 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"; } this.submenuDisposables.push(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(); if (_this.parentData.submenu) { _this.parentData.submenu.dispose(); _this.parentData.submenu = undefined; } _this.submenuDisposables = lifecycle_1.dispose(_this.submenuDisposables); _this.submenuContainer = undefined; } })); this.submenuDisposables.push(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.push(this.parentData.submenu.onDidCancel(function () { _this.parentData.parent.focus(); if (_this.parentData.submenu) { _this.parentData.submenu.dispose(); _this.parentData.submenu = undefined; } _this.submenuDisposables = lifecycle_1.dispose(_this.submenuDisposables); _this.submenuContainer = undefined; })); this.parentData.submenu.focus(selectFirstItem); this.mysubmenu = this.parentData.submenu; } else { this.parentData.submenu.focus(false); } }; SubmenuActionItem.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; this.submenuIndicator.style.backgroundColor = fgColor ? "" + fgColor : null; if (this.parentData.submenu) { this.parentData.submenu.style(this.menuStyle); } }; SubmenuActionItem.prototype.dispose = function () { _super.prototype.dispose.call(this); this.hideScheduler.dispose(); if (this.mysubmenu) { this.mysubmenu.dispose(); this.mysubmenu = null; } if (this.submenuContainer) { this.submenuDisposables = lifecycle_1.dispose(this.submenuDisposables); this.submenuContainer = undefined; } }; return SubmenuActionItem; }(MenuActionItem)); var MenuSeparatorActionItem = /** @class */ (function (_super) { __extends(MenuSeparatorActionItem, _super); function MenuSeparatorActionItem() { return _super !== null && _super.apply(this, arguments) || this; } MenuSeparatorActionItem.prototype.style = function (style) { this.label.style.borderBottomColor = style.separatorColor ? "" + style.separatorColor : null; }; return MenuSeparatorActionItem; }(actionbar_1.ActionItem)); function cleanMnemonic(label) { var regex = exports.MENU_MNEMONIC_REGEX; var matches = regex.exec(label); if (!matches) { return label; } var mnemonicInText = matches[0].charAt(0) === '&'; return label.replace(regex, mnemonicInText ? '$2' : '').trim(); } exports.cleanMnemonic = cleanMnemonic; }); define(__m[287/*vs/nls!vs/base/browser/ui/tree/abstractTree*/], __M([6/*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. *--------------------------------------------------------------------------------------------*/ define(__m[134/*vs/base/browser/ui/tree/abstractTree*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,135/*vs/base/browser/ui/list/listWidget*/,7/*vs/base/browser/dom*/,4/*vs/base/common/event*/,52/*vs/base/browser/keyboardEvent*/,126/*vs/base/browser/dnd*/,19/*vs/base/common/arrays*/,117/*vs/base/browser/ui/list/listView*/,62/*vs/base/browser/event*/,65/*vs/base/common/filters*/,209/*vs/base/browser/ui/tree/indexTreeModel*/,287/*vs/nls!vs/base/browser/ui/tree/abstractTree*/,15/*vs/base/common/async*/,17/*vs/base/common/platform*/,46/*vs/base/common/map*/,139/*vs/base/common/numbers*/,445/*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) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function asTreeDragAndDropData(data) { if (data instanceof listView_1.ElementsDragAndDropData) { var nodes = data.elements; return new listView_1.ElementsDragAndDropData(nodes.map(function (node) { return node.element; })); } 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) { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(nodes.map(function (node) { return node.element; })); } 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') { 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 parentNode = targetNode.parent; var model_1 = this.modelProvider(); var parentIndex = parentNode && model_1.getListIndex(model_1.getNodeLocation(parentNode)); 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({}, 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); }; return TreeNodeListDragAndDrop; }()); function asListOptions(modelProvider, options) { return options && __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({}, e, { element: e.element })); }, isSelectionRangeChangeEvent: function (e) { return options.multipleSelectionController.isSelectionRangeChangeEvent(__assign({}, e, { element: e.element })); } }, accessibilityProvider: options.accessibilityProvider && { getAriaLabel: function (e) { return options.accessibilityProvider.getAriaLabel(e.element); }, getAriaLevel: function (node) { return node.depth; } }, keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && __assign({}, options.keyboardNavigationLabelProvider, { getKeyboardNavigationLabel: function (node) { return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(node.element); } }), enableKeyboardNavigation: options.simpleKeyboardNavigation, ariaSetProvider: { getSetSize: function (node) { return node.parent.visibleChildrenCount; }, getPosInSet: function (node) { return node.visibleChildIndex + 1; } } }); } 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 TreeRenderer = /** @class */ (function () { function TreeRenderer(renderer, onDidChangeCollapseState, options) { if (options === void 0) { options = {}; } this.renderer = renderer; this.renderedElements = new Map(); this.renderedNodes = new Map(); this.indent = TreeRenderer.DefaultIndent; this.disposables = []; 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) { var _this = this; if (options === void 0) { options = {}; } if (typeof options.indent !== 'undefined') { this.indent = numbers_1.clamp(options.indent, 0, 40); } this.renderedNodes.forEach(function (templateData, node) { templateData.twistie.style.marginLeft = node.depth * _this.indent + "px"; }); }; TreeRenderer.prototype.renderTemplate = function (container) { var el = dom_1.append(container, dom_1.$('.monaco-tl-row')); 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, twistie: twistie, templateData: templateData }; }; TreeRenderer.prototype.renderElement = function (node, index, templateData, dynamicHeightProbing) { if (!dynamicHeightProbing) { this.renderedNodes.set(node, templateData); this.renderedElements.set(node.element, node); } var indent = TreeRenderer.DefaultIndent + (node.depth - 1) * this.indent; templateData.twistie.style.marginLeft = indent + "px"; this.update(node, templateData); this.renderer.renderElement(node, index, templateData.templateData, dynamicHeightProbing); }; TreeRenderer.prototype.disposeElement = function (node, index, templateData, dynamicHeightProbing) { if (this.renderer.disposeElement) { this.renderer.disposeElement(node, index, templateData.templateData, dynamicHeightProbing); } if (!dynamicHeightProbing) { 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 templateData = this.renderedNodes.get(node); if (!templateData) { return; } this.update(node, templateData); }; TreeRenderer.prototype.update = function (node, templateData) { if (this.renderer.renderTwistie) { this.renderer.renderTwistie(node.element, templateData.twistie); } dom_1.toggleClass(templateData.twistie, 'collapsible', node.collapsible); dom_1.toggleClass(templateData.twistie, 'collapsed', node.collapsible && node.collapsed); if (node.collapsible) { templateData.container.setAttribute('aria-expanded', String(!node.collapsed)); } else { templateData.container.removeAttribute('aria-expanded'); } }; TreeRenderer.prototype.dispose = function () { this.renderedNodes.clear(); this.renderedElements.clear(); this.disposables = 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.disposables = []; 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 () { this.disposables = lifecycle_1.dispose(this.disposables); }; return TypeFilter; }()); var TypeFilterController = /** @class */ (function () { function TypeFilterController(tree, model, view, filter, keyboardNavigationLabelProvider) { this.tree = tree; this.view = view; this.filter = filter; this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider; this._enabled = false; this._pattern = ''; this._onDidChangeEmptyState = new event_1.Emitter(); this.positionClassName = 'ne'; this.automaticKeyboardNavigation = true; this.triggered = false; this._onDidChangePattern = new event_1.Emitter(); this.enabledDisposables = []; this.disposables = []; 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')); 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')); 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 isPrintableCharEvent = this.keyboardNavigationLabelProvider.mightProducePrintableCharacter ? function (e) { return _this.keyboardNavigationLabelProvider.mightProducePrintableCharacter(e); } : function (e) { return listWidget_1.mightProducePrintableCharacter(e); }; var onKeyDown = event_1.Event.chain(event_2.domEvent(this.view.getHTMLElement(), 'keydown')) .filter(function (e) { return !isInputElement(e.target) || e.target === _this.filterOnTypeDomNode; }) .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 isPrintableCharEvent(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 = lifecycle_1.dispose(this.enabledDisposables); 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 = []; 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 = null; _this.domNode.style.left = null; lifecycle_1.dispose(disposables); }; updatePosition(); dom_1.removeClass(this.domNode, positionClassName); dom_1.addClass(this.domNode, 'dragging'); disposables.push(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.push(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 () { this.disable(); this._onDidChangePattern.dispose(); this.disposables = 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.nodes = nodes.slice(); this.elements = undefined; this._nodeSet = undefined; var that = this; this._onDidChange.fire({ get elements() { return that.get(); }, browserEvent: browserEvent }); }; Trait.prototype.get = function () { if (!this.elements) { this.elements = this.nodes.map(function (node) { return node.element; }); } return this.elements.slice(); }; 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); }; 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); } var model = this.tree.model; // internal var location = model.getNodeLocation(node); var recursive = e.browserEvent.altKey; model.setCollapsed(location, undefined, recursive); if (expandOnlyOnTwistieClick && onTwistie) { return; } _super.prototype.onPointer.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(container, virtualDelegate, renderers, focusTrait, selectionTrait, options) { var _this = _super.call(this, 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(_super.prototype.getFocus.call(this).concat(additionalFocus))); } if (additionalSelection.length > 0) { _super.prototype.setSelection.call(this, arrays_1.distinctES6(_super.prototype.getSelection.call(this).concat(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(container, delegate, renderers, _options) { var _this = this; var _a; if (_options === void 0) { _options = {}; } this._options = _options; this.eventBufferer = new event_1.EventBufferer(); this.disposables = []; 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(); this.renderers = renderers.map(function (r) { return new TreeRenderer(r, onDidChangeCollapseStateRelay.event, _options); }); (_a = this.disposables).push.apply(_a, this.renderers); var filter; if (_options.keyboardNavigationLabelProvider) { filter = new TypeFilter(this, _options.keyboardNavigationLabelProvider, _options.filter); _options = __assign({}, _options, { filter: filter }); // TODO need typescript help here this.disposables.push(filter); } this.focus = new Trait(_options.identityProvider); this.selection = new Trait(_options.identityProvider); this.view = new TreeNodeList(container, treeDelegate, this.renderers, this.focus, this.selection, __assign({}, asListOptions(function () { return _this.model; }, _options), { tree: this })); this.model = this.createModel(this.view, _options); onDidChangeCollapseStateRelay.input = this.model.onDidChangeCollapseState; this.model.onDidSplice(function (e) { _this.focus.onDidModelSplice(e); _this.selection.onDidModelSplice(e); }, null, this.disposables); 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) { this.typeFilterController = new TypeFilterController(this, this.model, this.view, filter, _options.keyboardNavigationLabelProvider); this.focusNavigationFilter = function (node) { return _this.typeFilterController.shouldAllowFocus(node); }; this.disposables.push(this.typeFilterController); } } 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", { // Options TODO@joao expose options only, not Optional<> 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({}, 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); }; 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) { this.view.style(styles); }; // Tree AbstractTree.prototype.getNode = function (location) { return this.model.getNode(location); }; 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.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 === null) { 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 () { this.disposables = 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[289/*vs/base/browser/ui/tree/dataTree*/], __M([0/*require*/,1/*exports*/,134/*vs/base/browser/ui/tree/abstractTree*/,216/*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(container, delegate, renderers, dataSource, options) { if (options === void 0) { options = {}; } var _this = _super.call(this, container, delegate, renderers, options) || this; _this.dataSource = dataSource; _this.identityProvider = options.identityProvider; return _this; } DataTree.prototype.createModel = function (view, options) { return new objectTreeModel_1.ObjectTreeModel(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[185/*vs/base/browser/ui/tree/objectTree*/], __M([0/*require*/,1/*exports*/,134/*vs/base/browser/ui/tree/abstractTree*/,216/*vs/base/browser/ui/tree/objectTreeModel*/]), function (require, exports, abstractTree_1, objectTreeModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ObjectTree = /** @class */ (function (_super) { __extends(ObjectTree, _super); function ObjectTree(container, delegate, renderers, options) { if (options === void 0) { options = {}; } return _super.call(this, container, delegate, renderers, options) || this; } ObjectTree.prototype.setChildren = function (element, children, onDidCreateNode, onDidDeleteNode) { return this.model.setChildren(element, children, onDidCreateNode, onDidDeleteNode); }; ObjectTree.prototype.rerender = function (element) { if (element === undefined) { this.view.rerender(); return; } this.model.rerender(element); }; ObjectTree.prototype.createModel = function (view, options) { return new objectTreeModel_1.ObjectTreeModel(view, options); }; return ObjectTree; }(abstractTree_1.AbstractTree)); exports.ObjectTree = ObjectTree; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[291/*vs/base/browser/ui/tree/asyncDataTree*/], __M([0/*require*/,1/*exports*/,134/*vs/base/browser/ui/tree/abstractTree*/,185/*vs/base/browser/ui/tree/objectTree*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/,15/*vs/base/common/async*/,57/*vs/base/common/iterator*/,117/*vs/base/browser/ui/list/listView*/,10/*vs/base/common/errors*/,7/*vs/base/browser/dom*/,46/*vs/base/common/map*/]), function (require, exports, abstractTree_1, objectTree_1, lifecycle_1, event_1, async_1, iterator_1, listView_1, errors_1, dom_1, map_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function createAsyncDataTreeNode(props) { return __assign({}, props, { children: [], loading: false, stale: true, slow: false }); } function isAncestor(ancestor, descendant) { if (!descendant.parent) { return false; } else if (descendant.parent === ancestor) { return true; } else { return isAncestor(ancestor, descendant.parent); } } function intersects(node, other) { return node === other || isAncestor(node, other) || isAncestor(other, node); } 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, "parent", { get: function () { return this.node.parent && new AsyncDataTreeNodeWrapper(this.node.parent); }, 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 DataTreeRenderer = /** @class */ (function () { function DataTreeRenderer(renderer, onDidChangeTwistieState) { this.renderer = renderer; this.onDidChangeTwistieState = onDidChangeTwistieState; this.renderedNodes = new Map(); this.disposables = []; this.templateId = renderer.templateId; } DataTreeRenderer.prototype.renderTemplate = function (container) { var templateData = this.renderer.renderTemplate(container); return { templateData: templateData }; }; DataTreeRenderer.prototype.renderElement = function (node, index, templateData, dynamicHeightProbing) { this.renderer.renderElement(new AsyncDataTreeNodeWrapper(node), index, templateData.templateData, dynamicHeightProbing); }; DataTreeRenderer.prototype.renderTwistie = function (element, twistieElement) { dom_1.toggleClass(twistieElement, 'loading', element.slow); return false; }; DataTreeRenderer.prototype.disposeElement = function (node, index, templateData, dynamicHeightProbing) { if (this.renderer.disposeElement) { this.renderer.disposeElement(new AsyncDataTreeNodeWrapper(node), index, templateData.templateData, dynamicHeightProbing); } }; DataTreeRenderer.prototype.disposeTemplate = function (templateData) { this.renderer.disposeTemplate(templateData.templateData); }; DataTreeRenderer.prototype.dispose = function () { this.renderedNodes.clear(); this.disposables = lifecycle_1.dispose(this.disposables); }; return DataTreeRenderer; }()); function asTreeEvent(e) { return { browserEvent: e.browserEvent, elements: e.elements.map(function (e) { return e.element; }) }; } var ChildrenResolutionReason; (function (ChildrenResolutionReason) { ChildrenResolutionReason[ChildrenResolutionReason["Refresh"] = 0] = "Refresh"; ChildrenResolutionReason[ChildrenResolutionReason["Expand"] = 1] = "Expand"; })(ChildrenResolutionReason = exports.ChildrenResolutionReason || (exports.ChildrenResolutionReason = {})); function asAsyncDataTreeDragAndDropData(data) { if (data instanceof listView_1.ElementsDragAndDropData) { var nodes = data.elements; return new listView_1.ElementsDragAndDropData(nodes.map(function (node) { return node.element; })); } 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) { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(nodes.map(function (node) { return node.element; })); } 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); }; return AsyncDataTreeNodeListDragAndDrop; }()); function asObjectTreeOptions(options) { return options && __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({}, e, { element: e.element })); }, isSelectionRangeChangeEvent: function (e) { return options.multipleSelectionController.isSelectionRangeChangeEvent(__assign({}, e, { element: e.element })); } }, accessibilityProvider: options.accessibilityProvider && { getAriaLabel: function (e) { return options.accessibilityProvider.getAriaLabel(e.element); } }, filter: options.filter && { filter: function (e, parentVisibility) { return options.filter.filter(e.element, parentVisibility); } }, keyboardNavigationLabelProvider: 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); })), ariaSetProvider: undefined }); } function asTreeElement(node, viewStateContext) { var collapsed; if (viewStateContext && viewStateContext.viewState.expanded && node.id) { collapsed = viewStateContext.viewState.expanded.indexOf(node.id) === -1; } return { element: node, children: node.hasChildren ? iterator_1.Iterator.map(iterator_1.Iterator.fromArray(node.children), function (child) { return asTreeElement(child, viewStateContext); }) : [], collapsible: node.hasChildren, collapsed: collapsed }; } function dfs(node, fn) { fn(node); node.children.forEach(function (child) { return dfs(child, fn); }); } var AsyncDataTree = /** @class */ (function () { function AsyncDataTree(container, delegate, renderers, dataSource, options) { var _this = this; if (options === void 0) { options = {}; } 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.disposables = []; this.identityProvider = options.identityProvider; this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === 'undefined' ? false : options.autoExpandSingleChildren; this.sorter = options.sorter; var objectTreeDelegate = new abstractTree_1.ComposedTreeDelegate(delegate); var objectTreeRenderers = renderers.map(function (r) { return new DataTreeRenderer(r, _this._onDidChangeNodeSlowState.event); }); var objectTreeOptions = asObjectTreeOptions(options) || {}; this.tree = new objectTree_1.ObjectTree(container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions); this.root = createAsyncDataTreeNode({ element: undefined, parent: null, hasChildren: true }); if (this.identityProvider) { this.root = __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.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, 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, viewStateContext) { if (element === void 0) { element = this.root.element; } if (recursive === void 0) { recursive = true; } return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (typeof this.root.element === 'undefined') { throw new Error('Tree input not set'); } if (!this.root.loading) return [3 /*break*/, 3]; return [4 /*yield*/, this.subTreeRefreshPromises.get(this.root)]; case 1: _a.sent(); return [4 /*yield*/, event_1.Event.toPromise(this._onDidRender.event)]; case 2: _a.sent(); _a.label = 3; case 3: return [4 /*yield*/, this.refreshAndRenderNode(this.getDataNode(element), recursive, ChildrenResolutionReason.Refresh, viewStateContext)]; case 4: _a.sent(); return [2 /*return*/]; } }); }); }; // View AsyncDataTree.prototype.rerender = function (element) { if (element === undefined) { 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 Error('Tree input not set'); } if (!this.root.loading) return [3 /*break*/, 3]; return [4 /*yield*/, this.subTreeRefreshPromises.get(this.root)]; 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 (node !== this.root && !node.loading && !this.tree.isCollapsed(node)) { return [2 /*return*/, false]; } result = this.tree.expand(node === this.root ? null : node, recursive); if (!node.loading) return [3 /*break*/, 6]; return [4 /*yield*/, this.subTreeRefreshPromises.get(node)]; case 4: _a.sent(); return [4 /*yield*/, event_1.Event.toPromise(this._onDidRender.event)]; case 5: _a.sent(); _a.label = 6; case 6: 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 Error("Data tree node not found: " + element); } return node; }; AsyncDataTree.prototype.refreshAndRenderNode = function (node, recursive, reason, viewStateContext) { return __awaiter(this, void 0, void 0, function () { var treeNode, visibleChildren; 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); if (!(node !== this.root && this.autoExpandSingleChildren && reason === ChildrenResolutionReason.Expand)) return [3 /*break*/, 3]; treeNode = this.tree.getNode(node); visibleChildren = treeNode.children.filter(function (node) { return node.visible; }); if (!(visibleChildren.length === 1)) return [3 /*break*/, 3]; return [4 /*yield*/, this.tree.expand(visibleChildren[0].element, false)]; case 2: _a.sent(); _a.label = 3; case 3: 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) { switch (_a.label) { case 0: 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]; } result = this.doRefreshSubTree(node, recursive, viewStateContext); this.subTreeRefreshPromises.set(node, result); _a.label = 1; case 1: _a.trys.push([1, , 3, 4]); return [4 /*yield*/, result]; case 2: _a.sent(); return [3 /*break*/, 4]; case 3: this.subTreeRefreshPromises.delete(node); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; AsyncDataTree.prototype.doRefreshSubTree = function (node, recursive, viewStateContext) { return __awaiter(this, void 0, void 0, function () { var childrenToRefresh; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: node.loading = true; _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: node.loading = false; 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(); if (this.sorter) { children.sort(this.sorter.compare.bind(this.sorter)); } return [2 /*return*/, 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, ChildrenResolutionReason.Expand) .catch(errors_1.onUnexpectedError); } } }; AsyncDataTree.prototype.setChildren = function (node, childrenElements, recursive, viewStateContext) { var _this = this; var _a; // 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) { childrenTreeNodesById.set(child.id, this.tree.getNode(child)); } } var childrenToRefresh = []; var children = childrenElements.map(function (element) { if (!_this.identityProvider) { return createAsyncDataTreeNode({ element: element, parent: node, hasChildren: !!_this.dataSource.hasChildren(element) }); } var id = _this.identityProvider.getId(element).toString(); var childNode = childrenTreeNodesById.get(id); if (childNode) { var asyncDataTreeNode = childNode.element; nodesToForget.delete(asyncDataTreeNode.element); _this.nodes.delete(asyncDataTreeNode.element); _this.nodes.set(element, asyncDataTreeNode); asyncDataTreeNode.element = element; asyncDataTreeNode.hasChildren = !!_this.dataSource.hasChildren(element); if (recursive) { if (childNode.collapsed) { dfs(asyncDataTreeNode, function (node) { return node.stale = true; }); } else { childrenToRefresh.push(asyncDataTreeNode); } } return asyncDataTreeNode; } var childAsyncDataTreeNode = createAsyncDataTreeNode({ element: element, parent: node, id: id, hasChildren: !!_this.dataSource.hasChildren(element) }); if (viewStateContext && viewStateContext.viewState.focus && viewStateContext.viewState.focus.indexOf(id) > -1) { viewStateContext.focus.push(childAsyncDataTreeNode); } if (viewStateContext && viewStateContext.viewState.selection && viewStateContext.viewState.selection.indexOf(id) > -1) { viewStateContext.selection.push(childAsyncDataTreeNode); } if (viewStateContext && viewStateContext.viewState.expanded && viewStateContext.viewState.expanded.indexOf(id) > -1) { childrenToRefresh.push(childAsyncDataTreeNode); } 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, [0, node.children.length].concat(children)); return childrenToRefresh; }; AsyncDataTree.prototype.render = function (node, viewStateContext) { var children = node.children.map(function (c) { return asTreeElement(c, viewStateContext); }); this.tree.setChildren(node === this.root ? null : node, children); this._onDidRender.fire(); }; AsyncDataTree.prototype.dispose = function () { lifecycle_1.dispose(this.disposables); }; return AsyncDataTree; }()); exports.AsyncDataTree = AsyncDataTree; }); define(__m[292/*vs/nls!vs/base/common/keybindingLabels*/], __M([6/*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[175/*vs/base/common/keybindingLabels*/], __M([0/*require*/,1/*exports*/,292/*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[294/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([0/*require*/,1/*exports*/,31/*vs/base/common/objects*/,175/*vs/base/common/keybindingLabels*/,7/*vs/base/browser/dom*/,282/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/,463/*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 && match.ctrlKey), modifierLabels.separator); } if (part.shiftKey) { this.renderKey(parent, modifierLabels.shiftKey, Boolean(match && match.shiftKey), modifierLabels.separator); } if (part.altKey) { this.renderKey(parent, modifierLabels.altKey, Boolean(match && match.altKey), modifierLabels.separator); } if (part.metaKey) { this.renderKey(parent, modifierLabels.metaKey, Boolean(match && match.metaKey), modifierLabels.separator); } var keyLabel = part.keyLabel; if (keyLabel) { this.renderKey(parent, keyLabel, Boolean(match && 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[295/*vs/nls!vs/base/common/severity*/], __M([6/*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[123/*vs/base/common/severity*/], __M([0/*require*/,1/*exports*/,295/*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[297/*vs/nls!vs/base/parts/quickopen/browser/quickOpenModel*/], __M([6/*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[120/*vs/base/parts/quickopen/browser/quickOpenModel*/], __M([0/*require*/,1/*exports*/,297/*vs/nls!vs/base/parts/quickopen/browser/quickOpenModel*/,20/*vs/base/common/types*/,155/*vs/base/browser/ui/iconLabel/iconLabel*/,79/*vs/base/browser/ui/actionbar/actionbar*/,178/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,7/*vs/base/browser/dom*/,294/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/,17/*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 null; }; /** * The options for the label to use for this entry */ QuickOpenEntry.prototype.getLabelOptions = function () { return null; }; /** * 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 null; }; /** * The icon of the entry to identify it from others in the list */ QuickOpenEntry.prototype.getIcon = function () { return null; }; /** * A secondary description that is optional and can be shown right to the label */ QuickOpenEntry.prototype.getDescription = function () { return null; }; /** * A tooltip to show when hovering over the entry. */ QuickOpenEntry.prototype.getTooltip = function () { return null; }; /** * A tooltip to show when hovering over the description portion of the entry. */ QuickOpenEntry.prototype.getDescriptionTooltip = function () { return null; }; /** * An optional keybinding to show for an entry. */ QuickOpenEntry.prototype.getKeybinding = function () { return null; }; /** * 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 }); // 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 = null; } // 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 = types.withNullAsUndefined(entry.getTooltip()); options.descriptionTitle = entry.getDescriptionTooltip() || types.withNullAsUndefined(entry.getDescription()); // tooltip over description because it could overflow options.descriptionMatches = descriptionHighlights || []; data.label.setLabel(types.withNullAsUndefined(entry.getLabel()), types.withNullAsUndefined(entry.getDescription()), options); // Meta data.detail.set(types.withNullAsUndefined(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 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[299/*vs/nls!vs/base/parts/quickopen/browser/quickOpenWidget*/], __M([6/*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[300/*vs/base/parts/quickopen/browser/quickOpenWidget*/], __M([0/*require*/,1/*exports*/,299/*vs/nls!vs/base/parts/quickopen/browser/quickOpenWidget*/,17/*vs/base/common/platform*/,20/*vs/base/common/types*/,525/*vs/base/parts/quickopen/browser/quickOpenViewer*/,136/*vs/base/browser/ui/inputbox/inputBox*/,441/*vs/base/parts/tree/browser/treeImpl*/,459/*vs/base/browser/ui/progressbar/progressbar*/,52/*vs/base/browser/keyboardEvent*/,116/*vs/base/parts/tree/browser/treeDefaults*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,28/*vs/base/common/color*/,31/*vs/base/common/objects*/,43/*vs/base/browser/mouseEvent*/,444/*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); } })); 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 = keyCode === 3 /* Enter */ || 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_2 = _this.tree.getFocus(); if (focus_2) { _this.elementSelected(focus_2, 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() : null; var background = this.styles.background ? this.styles.background.toString() : null; var borderColor = this.styles.borderColor ? this.styles.borderColor.toString() : null; var widgetShadow = this.styles.widgetShadow ? this.styles.widgetShadow.toString() : null; this.element.style.color = foreground; this.element.style.backgroundColor = background; this.element.style.borderColor = borderColor; this.element.style.borderWidth = borderColor ? '1px' : null; this.element.style.borderStyle = borderColor ? 'solid' : null; this.element.style.boxShadow = widgetShadow ? "0 5px 8px " + widgetShadow : null; } 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_1 = { event: event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration }; hide = this.model.runner.run(value, mode, context_1); } // 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(); } } }; 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[301/*vs/nls!vs/editor/browser/controller/coreCommands*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/controller/coreCommands", data); }); define(__m[302/*vs/nls!vs/editor/browser/widget/codeEditorWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/codeEditorWidget", data); }); define(__m[303/*vs/nls!vs/editor/browser/widget/diffEditorWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffEditorWidget", data); }); define(__m[304/*vs/nls!vs/editor/browser/widget/diffReview*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffReview", data); }); define(__m[305/*vs/nls!vs/editor/common/config/commonEditorConfig*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/config/commonEditorConfig", data); }); define(__m[306/*vs/nls!vs/editor/common/config/editorOptions*/], __M([6/*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[48/*vs/editor/common/config/editorOptions*/], __M([0/*require*/,1/*exports*/,306/*vs/nls!vs/editor/common/config/editorOptions*/,19/*vs/base/common/arrays*/,31/*vs/base/common/objects*/,17/*vs/base/common/platform*/,107/*vs/editor/common/model/wordHelper*/,20/*vs/base/common/types*/]), function (require, exports, nls, arrays, objects, platform, wordHelper_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * @internal */ function blinkingStyleToString(blinkingStyle) { if (blinkingStyle === 1 /* Blink */) { return 'blink'; } else if (blinkingStyle === 4 /* Expand */) { return 'expand'; } else if (blinkingStyle === 3 /* Phase */) { return 'phase'; } else if (blinkingStyle === 2 /* Smooth */) { return 'smooth'; } else if (blinkingStyle === 5 /* Solid */) { return 'solid'; } else { throw new Error('blinkingStyleToString: Unknown blinkingStyle'); } } exports.blinkingStyleToString = blinkingStyleToString; /** * 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 = {})); /** * @internal */ function cursorStyleToString(cursorStyle) { if (cursorStyle === TextEditorCursorStyle.Line) { return 'line'; } else if (cursorStyle === TextEditorCursorStyle.Block) { return 'block'; } else if (cursorStyle === TextEditorCursorStyle.Underline) { return 'underline'; } else if (cursorStyle === TextEditorCursorStyle.LineThin) { return 'line-thin'; } else if (cursorStyle === TextEditorCursorStyle.BlockOutline) { return 'block-outline'; } else if (cursorStyle === TextEditorCursorStyle.UnderlineThin) { return 'underline-thin'; } else { throw new Error('cursorStyleToString: Unknown cursorStyle'); } } exports.cursorStyleToString = cursorStyleToString; function _cursorStyleFromString(cursorStyle, defaultValue) { if (typeof cursorStyle !== 'string') { return defaultValue; } if (cursorStyle === 'line') { return TextEditorCursorStyle.Line; } else if (cursorStyle === 'block') { return TextEditorCursorStyle.Block; } else if (cursorStyle === 'underline') { return TextEditorCursorStyle.Underline; } else if (cursorStyle === 'line-thin') { return TextEditorCursorStyle.LineThin; } else if (cursorStyle === 'block-outline') { return TextEditorCursorStyle.BlockOutline; } else if (cursorStyle === 'underline-thin') { return TextEditorCursorStyle.UnderlineThin; } return TextEditorCursorStyle.Line; } /** * Internal configuration options (transformed or computed) for the editor. */ var InternalEditorOptions = /** @class */ (function () { /** * @internal */ function InternalEditorOptions(source) { this.canUseLayerHinting = source.canUseLayerHinting; this.pixelRatio = source.pixelRatio; this.editorClassName = source.editorClassName; this.lineHeight = source.lineHeight | 0; this.readOnly = source.readOnly; this.accessibilitySupport = source.accessibilitySupport; this.multiCursorModifier = source.multiCursorModifier; this.multiCursorMergeOverlapping = source.multiCursorMergeOverlapping; this.wordSeparators = source.wordSeparators; this.autoClosingBrackets = source.autoClosingBrackets; this.autoClosingQuotes = source.autoClosingQuotes; this.autoSurround = source.autoSurround; this.autoIndent = source.autoIndent; this.useTabStops = source.useTabStops; this.tabFocusMode = source.tabFocusMode; this.dragAndDrop = source.dragAndDrop; this.emptySelectionClipboard = source.emptySelectionClipboard; this.copyWithSyntaxHighlighting = source.copyWithSyntaxHighlighting; this.layoutInfo = source.layoutInfo; this.fontInfo = source.fontInfo; this.viewInfo = source.viewInfo; this.wrappingInfo = source.wrappingInfo; this.contribInfo = source.contribInfo; this.showUnused = source.showUnused; } /** * @internal */ InternalEditorOptions.prototype.equals = function (other) { return (this.canUseLayerHinting === other.canUseLayerHinting && this.pixelRatio === other.pixelRatio && this.editorClassName === other.editorClassName && this.lineHeight === other.lineHeight && this.readOnly === other.readOnly && this.accessibilitySupport === other.accessibilitySupport && this.multiCursorModifier === other.multiCursorModifier && this.multiCursorMergeOverlapping === other.multiCursorMergeOverlapping && this.wordSeparators === other.wordSeparators && this.autoClosingBrackets === other.autoClosingBrackets && this.autoClosingQuotes === other.autoClosingQuotes && this.autoSurround === other.autoSurround && this.autoIndent === other.autoIndent && this.useTabStops === other.useTabStops && this.tabFocusMode === other.tabFocusMode && this.dragAndDrop === other.dragAndDrop && this.showUnused === other.showUnused && this.emptySelectionClipboard === other.emptySelectionClipboard && this.copyWithSyntaxHighlighting === other.copyWithSyntaxHighlighting && InternalEditorOptions._equalsLayoutInfo(this.layoutInfo, other.layoutInfo) && this.fontInfo.equals(other.fontInfo) && InternalEditorOptions._equalsViewOptions(this.viewInfo, other.viewInfo) && InternalEditorOptions._equalsWrappingInfo(this.wrappingInfo, other.wrappingInfo) && InternalEditorOptions._equalsContribOptions(this.contribInfo, other.contribInfo)); }; /** * @internal */ InternalEditorOptions.prototype.createChangeEvent = function (newOpts) { return { canUseLayerHinting: (this.canUseLayerHinting !== newOpts.canUseLayerHinting), pixelRatio: (this.pixelRatio !== newOpts.pixelRatio), editorClassName: (this.editorClassName !== newOpts.editorClassName), lineHeight: (this.lineHeight !== newOpts.lineHeight), readOnly: (this.readOnly !== newOpts.readOnly), accessibilitySupport: (this.accessibilitySupport !== newOpts.accessibilitySupport), multiCursorModifier: (this.multiCursorModifier !== newOpts.multiCursorModifier), multiCursorMergeOverlapping: (this.multiCursorMergeOverlapping !== newOpts.multiCursorMergeOverlapping), wordSeparators: (this.wordSeparators !== newOpts.wordSeparators), autoClosingBrackets: (this.autoClosingBrackets !== newOpts.autoClosingBrackets), autoClosingQuotes: (this.autoClosingQuotes !== newOpts.autoClosingQuotes), autoSurround: (this.autoSurround !== newOpts.autoSurround), autoIndent: (this.autoIndent !== newOpts.autoIndent), useTabStops: (this.useTabStops !== newOpts.useTabStops), tabFocusMode: (this.tabFocusMode !== newOpts.tabFocusMode), dragAndDrop: (this.dragAndDrop !== newOpts.dragAndDrop), emptySelectionClipboard: (this.emptySelectionClipboard !== newOpts.emptySelectionClipboard), copyWithSyntaxHighlighting: (this.copyWithSyntaxHighlighting !== newOpts.copyWithSyntaxHighlighting), layoutInfo: (!InternalEditorOptions._equalsLayoutInfo(this.layoutInfo, newOpts.layoutInfo)), fontInfo: (!this.fontInfo.equals(newOpts.fontInfo)), viewInfo: (!InternalEditorOptions._equalsViewOptions(this.viewInfo, newOpts.viewInfo)), wrappingInfo: (!InternalEditorOptions._equalsWrappingInfo(this.wrappingInfo, newOpts.wrappingInfo)), contribInfo: (!InternalEditorOptions._equalsContribOptions(this.contribInfo, newOpts.contribInfo)) }; }; /** * @internal */ InternalEditorOptions._equalsLayoutInfo = function (a, b) { return (a.width === b.width && a.height === b.height && a.glyphMarginLeft === b.glyphMarginLeft && a.glyphMarginWidth === b.glyphMarginWidth && a.glyphMarginHeight === b.glyphMarginHeight && a.lineNumbersLeft === b.lineNumbersLeft && a.lineNumbersWidth === b.lineNumbersWidth && a.lineNumbersHeight === b.lineNumbersHeight && a.decorationsLeft === b.decorationsLeft && a.decorationsWidth === b.decorationsWidth && a.decorationsHeight === b.decorationsHeight && a.contentLeft === b.contentLeft && a.contentWidth === b.contentWidth && a.contentHeight === b.contentHeight && a.renderMinimap === b.renderMinimap && a.minimapLeft === b.minimapLeft && a.minimapWidth === b.minimapWidth && a.viewportColumn === b.viewportColumn && a.verticalScrollbarWidth === b.verticalScrollbarWidth && a.horizontalScrollbarHeight === b.horizontalScrollbarHeight && this._equalsOverviewRuler(a.overviewRuler, b.overviewRuler)); }; /** * @internal */ InternalEditorOptions._equalsOverviewRuler = function (a, b) { return (a.width === b.width && a.height === b.height && a.top === b.top && a.right === b.right); }; /** * @internal */ InternalEditorOptions._equalsViewOptions = function (a, b) { return (a.extraEditorClassName === b.extraEditorClassName && a.disableMonospaceOptimizations === b.disableMonospaceOptimizations && arrays.equals(a.rulers, b.rulers) && a.ariaLabel === b.ariaLabel && a.renderLineNumbers === b.renderLineNumbers && a.renderCustomLineNumbers === b.renderCustomLineNumbers && a.renderFinalNewline === b.renderFinalNewline && a.selectOnLineNumbers === b.selectOnLineNumbers && a.glyphMargin === b.glyphMargin && a.revealHorizontalRightPadding === b.revealHorizontalRightPadding && a.roundedSelection === b.roundedSelection && a.overviewRulerLanes === b.overviewRulerLanes && a.overviewRulerBorder === b.overviewRulerBorder && a.cursorBlinking === b.cursorBlinking && a.mouseWheelZoom === b.mouseWheelZoom && a.cursorSmoothCaretAnimation === b.cursorSmoothCaretAnimation && a.cursorStyle === b.cursorStyle && a.cursorWidth === b.cursorWidth && a.hideCursorInOverviewRuler === b.hideCursorInOverviewRuler && a.scrollBeyondLastLine === b.scrollBeyondLastLine && a.scrollBeyondLastColumn === b.scrollBeyondLastColumn && a.smoothScrolling === b.smoothScrolling && a.stopRenderingLineAfter === b.stopRenderingLineAfter && a.renderWhitespace === b.renderWhitespace && a.renderControlCharacters === b.renderControlCharacters && a.fontLigatures === b.fontLigatures && a.renderIndentGuides === b.renderIndentGuides && a.highlightActiveIndentGuide === b.highlightActiveIndentGuide && a.renderLineHighlight === b.renderLineHighlight && this._equalsScrollbarOptions(a.scrollbar, b.scrollbar) && this._equalsMinimapOptions(a.minimap, b.minimap) && a.fixedOverflowWidgets === b.fixedOverflowWidgets); }; /** * @internal */ InternalEditorOptions._equalsScrollbarOptions = function (a, b) { return (a.arrowSize === b.arrowSize && a.vertical === b.vertical && a.horizontal === b.horizontal && a.useShadows === b.useShadows && a.verticalHasArrows === b.verticalHasArrows && a.horizontalHasArrows === b.horizontalHasArrows && a.handleMouseWheel === b.handleMouseWheel && a.horizontalScrollbarSize === b.horizontalScrollbarSize && a.horizontalSliderSize === b.horizontalSliderSize && a.verticalScrollbarSize === b.verticalScrollbarSize && a.verticalSliderSize === b.verticalSliderSize && a.mouseWheelScrollSensitivity === b.mouseWheelScrollSensitivity && a.fastScrollSensitivity === b.fastScrollSensitivity); }; /** * @internal */ InternalEditorOptions._equalsMinimapOptions = function (a, b) { return (a.enabled === b.enabled && a.side === b.side && a.showSlider === b.showSlider && a.renderCharacters === b.renderCharacters && a.maxColumn === b.maxColumn); }; /** * @internal */ InternalEditorOptions._equalFindOptions = function (a, b) { return (a.seedSearchStringFromSelection === b.seedSearchStringFromSelection && a.autoFindInSelection === b.autoFindInSelection && a.globalFindClipboard === b.globalFindClipboard && a.addExtraSpaceOnTop === b.addExtraSpaceOnTop); }; /** * @internal */ InternalEditorOptions._equalsParameterHintOptions = function (a, b) { return (a.enabled === b.enabled && a.cycle === b.cycle); }; /** * @internal */ InternalEditorOptions._equalsHoverOptions = function (a, b) { return (a.enabled === b.enabled && a.delay === b.delay && a.sticky === b.sticky); }; /** * @internal */ InternalEditorOptions._equalsSuggestOptions = function (a, b) { if (a === b) { return true; } else if (!a || !b) { return false; } else { return a.filterGraceful === b.filterGraceful && a.snippets === b.snippets && a.snippetsPreventQuickSuggestions === b.snippetsPreventQuickSuggestions && a.localityBonus === b.localityBonus && a.shareSuggestSelections === b.shareSuggestSelections && a.showIcons === b.showIcons && a.maxVisibleSuggestions === b.maxVisibleSuggestions && objects.equals(a.filteredTypes, b.filteredTypes); } }; InternalEditorOptions._equalsGotoLocationOptions = function (a, b) { if (a === b) { return true; } else if (!a || !b) { return false; } else { return a.multiple === b.multiple; } }; /** * @internal */ InternalEditorOptions._equalsWrappingInfo = function (a, b) { return (a.inDiffEditor === b.inDiffEditor && a.isDominatedByLongLines === b.isDominatedByLongLines && a.isWordWrapMinified === b.isWordWrapMinified && a.isViewportWrapping === b.isViewportWrapping && a.wrappingColumn === b.wrappingColumn && a.wrappingIndent === b.wrappingIndent && a.wordWrapBreakBeforeCharacters === b.wordWrapBreakBeforeCharacters && a.wordWrapBreakAfterCharacters === b.wordWrapBreakAfterCharacters && a.wordWrapBreakObtrusiveCharacters === b.wordWrapBreakObtrusiveCharacters); }; /** * @internal */ InternalEditorOptions._equalsContribOptions = function (a, b) { return (a.selectionClipboard === b.selectionClipboard && this._equalsHoverOptions(a.hover, b.hover) && a.links === b.links && a.contextmenu === b.contextmenu && InternalEditorOptions._equalsQuickSuggestions(a.quickSuggestions, b.quickSuggestions) && a.quickSuggestionsDelay === b.quickSuggestionsDelay && this._equalsParameterHintOptions(a.parameterHints, b.parameterHints) && a.formatOnType === b.formatOnType && a.formatOnPaste === b.formatOnPaste && a.suggestOnTriggerCharacters === b.suggestOnTriggerCharacters && a.acceptSuggestionOnEnter === b.acceptSuggestionOnEnter && a.acceptSuggestionOnCommitCharacter === b.acceptSuggestionOnCommitCharacter && a.wordBasedSuggestions === b.wordBasedSuggestions && a.suggestSelection === b.suggestSelection && a.suggestFontSize === b.suggestFontSize && a.suggestLineHeight === b.suggestLineHeight && a.tabCompletion === b.tabCompletion && this._equalsSuggestOptions(a.suggest, b.suggest) && InternalEditorOptions._equalsGotoLocationOptions(a.gotoLocation, b.gotoLocation) && a.selectionHighlight === b.selectionHighlight && a.occurrencesHighlight === b.occurrencesHighlight && a.codeLens === b.codeLens && a.folding === b.folding && a.foldingStrategy === b.foldingStrategy && a.showFoldingControls === b.showFoldingControls && a.matchBrackets === b.matchBrackets && this._equalFindOptions(a.find, b.find) && a.colorDecorators === b.colorDecorators && objects.equals(a.codeActionsOnSave, b.codeActionsOnSave) && a.codeActionsOnSaveTimeout === b.codeActionsOnSaveTimeout && a.lightbulbEnabled === b.lightbulbEnabled); }; InternalEditorOptions._equalsQuickSuggestions = function (a, b) { if (typeof a === 'boolean') { if (typeof b !== 'boolean') { return false; } return a === b; } if (typeof b === 'boolean') { return false; } return (a.comments === b.comments && a.other === b.other && a.strings === b.strings); }; return InternalEditorOptions; }()); exports.InternalEditorOptions = InternalEditorOptions; function _boolean(value, defaultValue) { if (typeof value === 'undefined') { return defaultValue; } if (value === 'false') { // treat the string 'false' as false return false; } return Boolean(value); } function _booleanMap(value, defaultValue) { if (!value) { return defaultValue; } var out = Object.create(null); for (var _i = 0, _a = Object.keys(value); _i < _a.length; _i++) { var k = _a[_i]; var v = value[k]; if (typeof v === 'boolean') { out[k] = v; } } return out; } function _string(value, defaultValue) { if (typeof value !== 'string') { return defaultValue; } return value; } function _stringSet(value, defaultValue, allowedValues) { if (typeof value !== 'string') { return defaultValue; } if (allowedValues.indexOf(value) === -1) { return defaultValue; } return value; } function _clampedInt(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; } function _float(value, defaultValue) { var r = parseFloat(value); if (isNaN(r)) { r = defaultValue; } return r; } function _wrappingIndentFromString(wrappingIndent, defaultValue) { if (typeof wrappingIndent !== 'string') { return defaultValue; } if (wrappingIndent === 'same') { return 1 /* Same */; } else if (wrappingIndent === 'indent') { return 2 /* Indent */; } else if (wrappingIndent === 'deepIndent') { return 3 /* DeepIndent */; } else { return 0 /* None */; } } function _cursorBlinkingStyleFromString(cursorBlinkingStyle, defaultValue) { if (typeof cursorBlinkingStyle !== 'string') { return defaultValue; } switch (cursorBlinkingStyle) { case 'blink': return 1 /* Blink */; case 'smooth': return 2 /* Smooth */; case 'phase': return 3 /* Phase */; case 'expand': return 4 /* Expand */; case 'visible': // maintain compatibility case 'solid': return 5 /* Solid */; } return 1 /* Blink */; } 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 */; } } /** * @internal */ var EditorOptionsValidator = /** @class */ (function () { function EditorOptionsValidator() { } /** * Validate raw editor options. * i.e. since they can be defined by the user, they might be invalid. */ EditorOptionsValidator.validate = function (opts, defaults) { var wordWrap = opts.wordWrap; { // Compatibility with old true or false values if (wordWrap === true) { wordWrap = 'on'; } else if (wordWrap === false) { wordWrap = 'off'; } wordWrap = _stringSet(wordWrap, defaults.wordWrap, ['off', 'on', 'wordWrapColumn', 'bounded']); } var viewInfo = this._sanitizeViewInfo(opts, defaults.viewInfo); var contribInfo = this._sanitizeContribInfo(opts, defaults.contribInfo); var configuredMulticursorModifier = undefined; if (typeof opts.multiCursorModifier === 'string') { if (opts.multiCursorModifier === 'ctrlCmd') { configuredMulticursorModifier = platform.isMacintosh ? 'metaKey' : 'ctrlKey'; } else { configuredMulticursorModifier = 'altKey'; } } var multiCursorModifier = _stringSet(configuredMulticursorModifier, defaults.multiCursorModifier, ['altKey', 'metaKey', 'ctrlKey']); var autoClosingBrackets; var autoClosingQuotes; var autoSurround; if (typeof opts.autoClosingBrackets === 'boolean' && opts.autoClosingBrackets === false) { // backwards compatibility: disable all on boolean false autoClosingBrackets = 'never'; autoClosingQuotes = 'never'; autoSurround = 'never'; } else { autoClosingBrackets = _stringSet(opts.autoClosingBrackets, defaults.autoClosingBrackets, ['always', 'languageDefined', 'beforeWhitespace', 'never']); autoClosingQuotes = _stringSet(opts.autoClosingQuotes, defaults.autoClosingQuotes, ['always', 'languageDefined', 'beforeWhitespace', 'never']); autoSurround = _stringSet(opts.autoSurround, defaults.autoSurround, ['languageDefined', 'brackets', 'quotes', 'never']); } return { inDiffEditor: _boolean(opts.inDiffEditor, defaults.inDiffEditor), wordSeparators: _string(opts.wordSeparators, defaults.wordSeparators), lineNumbersMinChars: _clampedInt(opts.lineNumbersMinChars, defaults.lineNumbersMinChars, 1, 10), lineDecorationsWidth: (typeof opts.lineDecorationsWidth === 'undefined' ? defaults.lineDecorationsWidth : opts.lineDecorationsWidth), readOnly: _boolean(opts.readOnly, defaults.readOnly), mouseStyle: _stringSet(opts.mouseStyle, defaults.mouseStyle, ['text', 'default', 'copy']), disableLayerHinting: _boolean(opts.disableLayerHinting, defaults.disableLayerHinting), automaticLayout: _boolean(opts.automaticLayout, defaults.automaticLayout), wordWrap: wordWrap, wordWrapColumn: _clampedInt(opts.wordWrapColumn, defaults.wordWrapColumn, 1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */), wordWrapMinified: _boolean(opts.wordWrapMinified, defaults.wordWrapMinified), wrappingIndent: _wrappingIndentFromString(opts.wrappingIndent, defaults.wrappingIndent), wordWrapBreakBeforeCharacters: _string(opts.wordWrapBreakBeforeCharacters, defaults.wordWrapBreakBeforeCharacters), wordWrapBreakAfterCharacters: _string(opts.wordWrapBreakAfterCharacters, defaults.wordWrapBreakAfterCharacters), wordWrapBreakObtrusiveCharacters: _string(opts.wordWrapBreakObtrusiveCharacters, defaults.wordWrapBreakObtrusiveCharacters), autoClosingBrackets: autoClosingBrackets, autoClosingQuotes: autoClosingQuotes, autoSurround: autoSurround, autoIndent: _boolean(opts.autoIndent, defaults.autoIndent), dragAndDrop: _boolean(opts.dragAndDrop, defaults.dragAndDrop), emptySelectionClipboard: _boolean(opts.emptySelectionClipboard, defaults.emptySelectionClipboard), copyWithSyntaxHighlighting: _boolean(opts.copyWithSyntaxHighlighting, defaults.copyWithSyntaxHighlighting), useTabStops: _boolean(opts.useTabStops, defaults.useTabStops), multiCursorModifier: multiCursorModifier, multiCursorMergeOverlapping: _boolean(opts.multiCursorMergeOverlapping, defaults.multiCursorMergeOverlapping), accessibilitySupport: _stringSet(opts.accessibilitySupport, defaults.accessibilitySupport, ['auto', 'on', 'off']), showUnused: _boolean(opts.showUnused, defaults.showUnused), viewInfo: viewInfo, contribInfo: contribInfo, }; }; EditorOptionsValidator._sanitizeScrollbarOpts = function (opts, defaults, mouseWheelScrollSensitivity, fastScrollSensitivity) { if (typeof opts !== 'object') { return defaults; } var horizontalScrollbarSize = _clampedInt(opts.horizontalScrollbarSize, defaults.horizontalScrollbarSize, 0, 1000); var verticalScrollbarSize = _clampedInt(opts.verticalScrollbarSize, defaults.verticalScrollbarSize, 0, 1000); return { vertical: _scrollbarVisibilityFromString(opts.vertical, defaults.vertical), horizontal: _scrollbarVisibilityFromString(opts.horizontal, defaults.horizontal), arrowSize: _clampedInt(opts.arrowSize, defaults.arrowSize, 0, 1000), useShadows: _boolean(opts.useShadows, defaults.useShadows), verticalHasArrows: _boolean(opts.verticalHasArrows, defaults.verticalHasArrows), horizontalHasArrows: _boolean(opts.horizontalHasArrows, defaults.horizontalHasArrows), horizontalScrollbarSize: horizontalScrollbarSize, horizontalSliderSize: _clampedInt(opts.horizontalSliderSize, horizontalScrollbarSize, 0, 1000), verticalScrollbarSize: verticalScrollbarSize, verticalSliderSize: _clampedInt(opts.verticalSliderSize, verticalScrollbarSize, 0, 1000), handleMouseWheel: _boolean(opts.handleMouseWheel, defaults.handleMouseWheel), mouseWheelScrollSensitivity: mouseWheelScrollSensitivity, fastScrollSensitivity: fastScrollSensitivity, }; }; EditorOptionsValidator._sanitizeMinimapOpts = function (opts, defaults) { if (typeof opts !== 'object') { return defaults; } return { enabled: _boolean(opts.enabled, defaults.enabled), side: _stringSet(opts.side, defaults.side, ['right', 'left']), showSlider: _stringSet(opts.showSlider, defaults.showSlider, ['always', 'mouseover']), renderCharacters: _boolean(opts.renderCharacters, defaults.renderCharacters), maxColumn: _clampedInt(opts.maxColumn, defaults.maxColumn, 1, 10000), }; }; EditorOptionsValidator._sanitizeFindOpts = function (opts, defaults) { if (typeof opts !== 'object') { return defaults; } return { seedSearchStringFromSelection: _boolean(opts.seedSearchStringFromSelection, defaults.seedSearchStringFromSelection), autoFindInSelection: _boolean(opts.autoFindInSelection, defaults.autoFindInSelection), globalFindClipboard: _boolean(opts.globalFindClipboard, defaults.globalFindClipboard), addExtraSpaceOnTop: _boolean(opts.addExtraSpaceOnTop, defaults.addExtraSpaceOnTop) }; }; EditorOptionsValidator._sanitizeParameterHintOpts = function (opts, defaults) { if (typeof opts !== 'object') { return defaults; } return { enabled: _boolean(opts.enabled, defaults.enabled), cycle: _boolean(opts.cycle, defaults.cycle) }; }; EditorOptionsValidator._sanitizeHoverOpts = function (_opts, defaults) { var opts; if (typeof _opts === 'boolean') { opts = { enabled: _opts }; } else if (typeof _opts === 'object') { opts = _opts; } else { return defaults; } return { enabled: _boolean(opts.enabled, defaults.enabled), delay: _clampedInt(opts.delay, defaults.delay, 0, 10000), sticky: _boolean(opts.sticky, defaults.sticky) }; }; EditorOptionsValidator._sanitizeSuggestOpts = function (opts, defaults) { var suggestOpts = opts.suggest || {}; return { filterGraceful: _boolean(suggestOpts.filterGraceful, defaults.filterGraceful), snippets: _stringSet(opts.snippetSuggestions, defaults.snippets, ['top', 'bottom', 'inline', 'none']), snippetsPreventQuickSuggestions: _boolean(suggestOpts.snippetsPreventQuickSuggestions, defaults.filterGraceful), localityBonus: _boolean(suggestOpts.localityBonus, defaults.localityBonus), shareSuggestSelections: _boolean(suggestOpts.shareSuggestSelections, defaults.shareSuggestSelections), showIcons: _boolean(suggestOpts.showIcons, defaults.showIcons), maxVisibleSuggestions: _clampedInt(suggestOpts.maxVisibleSuggestions, defaults.maxVisibleSuggestions, 1, 15), filteredTypes: types_1.isObject(suggestOpts.filteredTypes) ? suggestOpts.filteredTypes : Object.create(null) }; }; EditorOptionsValidator._sanitizeGotoLocationOpts = function (opts, defaults) { var gotoOpts = opts.gotoLocation || {}; return { multiple: _stringSet(gotoOpts.multiple, defaults.multiple, ['peek', 'gotoAndPeek', 'goto']) }; }; EditorOptionsValidator._sanitizeTabCompletionOpts = function (opts, defaults) { if (opts === false) { return 'off'; } else if (opts === true) { return 'onlySnippets'; } else { return _stringSet(opts, defaults, ['on', 'off', 'onlySnippets']); } }; EditorOptionsValidator._sanitizeViewInfo = function (opts, defaults) { var rulers = []; if (Array.isArray(opts.rulers)) { for (var i = 0, len = opts.rulers.length; i < len; i++) { rulers.push(_clampedInt(opts.rulers[i], 0, 0, 10000)); } rulers.sort(); } var renderLineNumbers = defaults.renderLineNumbers; var renderCustomLineNumbers = defaults.renderCustomLineNumbers; if (typeof opts.lineNumbers !== 'undefined') { var lineNumbers = opts.lineNumbers; // Compatibility with old true or false values if (lineNumbers === true) { lineNumbers = 'on'; } else if (lineNumbers === false) { lineNumbers = 'off'; } if (typeof lineNumbers === 'function') { renderLineNumbers = 4 /* Custom */; renderCustomLineNumbers = lineNumbers; } else if (lineNumbers === 'interval') { renderLineNumbers = 3 /* Interval */; } else if (lineNumbers === 'relative') { renderLineNumbers = 2 /* Relative */; } else if (lineNumbers === 'on') { renderLineNumbers = 1 /* On */; } else { renderLineNumbers = 0 /* Off */; } } var fontLigatures = _boolean(opts.fontLigatures, defaults.fontLigatures); var disableMonospaceOptimizations = _boolean(opts.disableMonospaceOptimizations, defaults.disableMonospaceOptimizations) || fontLigatures; var renderWhitespace = opts.renderWhitespace; { // Compatibility with old true or false values if (renderWhitespace === true) { renderWhitespace = 'boundary'; } else if (renderWhitespace === false) { renderWhitespace = 'none'; } renderWhitespace = _stringSet(renderWhitespace, defaults.renderWhitespace, ['none', 'boundary', 'all']); } var renderLineHighlight = opts.renderLineHighlight; { // Compatibility with old true or false values if (renderLineHighlight === true) { renderLineHighlight = 'line'; } else if (renderLineHighlight === false) { renderLineHighlight = 'none'; } renderLineHighlight = _stringSet(renderLineHighlight, defaults.renderLineHighlight, ['none', 'gutter', 'line', 'all']); } var mouseWheelScrollSensitivity = _float(opts.mouseWheelScrollSensitivity, defaults.scrollbar.mouseWheelScrollSensitivity); if (mouseWheelScrollSensitivity === 0) { // Disallow 0, as it would prevent/block scrolling mouseWheelScrollSensitivity = 1; } var fastScrollSensitivity = _float(opts.fastScrollSensitivity, defaults.scrollbar.fastScrollSensitivity); if (fastScrollSensitivity <= 0) { fastScrollSensitivity = defaults.scrollbar.fastScrollSensitivity; } var scrollbar = this._sanitizeScrollbarOpts(opts.scrollbar, defaults.scrollbar, mouseWheelScrollSensitivity, fastScrollSensitivity); var minimap = this._sanitizeMinimapOpts(opts.minimap, defaults.minimap); return { extraEditorClassName: _string(opts.extraEditorClassName, defaults.extraEditorClassName), disableMonospaceOptimizations: disableMonospaceOptimizations, rulers: rulers, ariaLabel: _string(opts.ariaLabel, defaults.ariaLabel), renderLineNumbers: renderLineNumbers, renderCustomLineNumbers: renderCustomLineNumbers, renderFinalNewline: _boolean(opts.renderFinalNewline, defaults.renderFinalNewline), selectOnLineNumbers: _boolean(opts.selectOnLineNumbers, defaults.selectOnLineNumbers), glyphMargin: _boolean(opts.glyphMargin, defaults.glyphMargin), revealHorizontalRightPadding: _clampedInt(opts.revealHorizontalRightPadding, defaults.revealHorizontalRightPadding, 0, 1000), roundedSelection: _boolean(opts.roundedSelection, defaults.roundedSelection), overviewRulerLanes: _clampedInt(opts.overviewRulerLanes, defaults.overviewRulerLanes, 0, 3), overviewRulerBorder: _boolean(opts.overviewRulerBorder, defaults.overviewRulerBorder), cursorBlinking: _cursorBlinkingStyleFromString(opts.cursorBlinking, defaults.cursorBlinking), mouseWheelZoom: _boolean(opts.mouseWheelZoom, defaults.mouseWheelZoom), cursorSmoothCaretAnimation: _boolean(opts.cursorSmoothCaretAnimation, defaults.cursorSmoothCaretAnimation), cursorStyle: _cursorStyleFromString(opts.cursorStyle, defaults.cursorStyle), cursorWidth: _clampedInt(opts.cursorWidth, defaults.cursorWidth, 0, Number.MAX_VALUE), hideCursorInOverviewRuler: _boolean(opts.hideCursorInOverviewRuler, defaults.hideCursorInOverviewRuler), scrollBeyondLastLine: _boolean(opts.scrollBeyondLastLine, defaults.scrollBeyondLastLine), scrollBeyondLastColumn: _clampedInt(opts.scrollBeyondLastColumn, defaults.scrollBeyondLastColumn, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */), smoothScrolling: _boolean(opts.smoothScrolling, defaults.smoothScrolling), stopRenderingLineAfter: _clampedInt(opts.stopRenderingLineAfter, defaults.stopRenderingLineAfter, -1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */), renderWhitespace: renderWhitespace, renderControlCharacters: _boolean(opts.renderControlCharacters, defaults.renderControlCharacters), fontLigatures: fontLigatures, renderIndentGuides: _boolean(opts.renderIndentGuides, defaults.renderIndentGuides), highlightActiveIndentGuide: _boolean(opts.highlightActiveIndentGuide, defaults.highlightActiveIndentGuide), renderLineHighlight: renderLineHighlight, scrollbar: scrollbar, minimap: minimap, fixedOverflowWidgets: _boolean(opts.fixedOverflowWidgets, defaults.fixedOverflowWidgets), }; }; EditorOptionsValidator._sanitizeContribInfo = function (opts, defaults) { var quickSuggestions; if (typeof opts.quickSuggestions === 'object') { quickSuggestions = __assign({ other: true }, opts.quickSuggestions); } else { quickSuggestions = _boolean(opts.quickSuggestions, defaults.quickSuggestions); } // Compatibility support for acceptSuggestionOnEnter if (typeof opts.acceptSuggestionOnEnter === 'boolean') { opts.acceptSuggestionOnEnter = opts.acceptSuggestionOnEnter ? 'on' : 'off'; } var find = this._sanitizeFindOpts(opts.find, defaults.find); return { selectionClipboard: _boolean(opts.selectionClipboard, defaults.selectionClipboard), hover: this._sanitizeHoverOpts(opts.hover, defaults.hover), links: _boolean(opts.links, defaults.links), contextmenu: _boolean(opts.contextmenu, defaults.contextmenu), quickSuggestions: quickSuggestions, quickSuggestionsDelay: _clampedInt(opts.quickSuggestionsDelay, defaults.quickSuggestionsDelay, -1073741824 /* MIN_SAFE_SMALL_INTEGER */, 1073741824 /* MAX_SAFE_SMALL_INTEGER */), parameterHints: this._sanitizeParameterHintOpts(opts.parameterHints, defaults.parameterHints), formatOnType: _boolean(opts.formatOnType, defaults.formatOnType), formatOnPaste: _boolean(opts.formatOnPaste, defaults.formatOnPaste), suggestOnTriggerCharacters: _boolean(opts.suggestOnTriggerCharacters, defaults.suggestOnTriggerCharacters), acceptSuggestionOnEnter: _stringSet(opts.acceptSuggestionOnEnter, defaults.acceptSuggestionOnEnter, ['on', 'smart', 'off']), acceptSuggestionOnCommitCharacter: _boolean(opts.acceptSuggestionOnCommitCharacter, defaults.acceptSuggestionOnCommitCharacter), wordBasedSuggestions: _boolean(opts.wordBasedSuggestions, defaults.wordBasedSuggestions), suggestSelection: _stringSet(opts.suggestSelection, defaults.suggestSelection, ['first', 'recentlyUsed', 'recentlyUsedByPrefix']), suggestFontSize: _clampedInt(opts.suggestFontSize, defaults.suggestFontSize, 0, 1000), suggestLineHeight: _clampedInt(opts.suggestLineHeight, defaults.suggestLineHeight, 0, 1000), tabCompletion: this._sanitizeTabCompletionOpts(opts.tabCompletion, defaults.tabCompletion), suggest: this._sanitizeSuggestOpts(opts, defaults.suggest), gotoLocation: this._sanitizeGotoLocationOpts(opts, defaults.gotoLocation), selectionHighlight: _boolean(opts.selectionHighlight, defaults.selectionHighlight), occurrencesHighlight: _boolean(opts.occurrencesHighlight, defaults.occurrencesHighlight), codeLens: _boolean(opts.codeLens, defaults.codeLens), folding: _boolean(opts.folding, defaults.folding), foldingStrategy: _stringSet(opts.foldingStrategy, defaults.foldingStrategy, ['auto', 'indentation']), showFoldingControls: _stringSet(opts.showFoldingControls, defaults.showFoldingControls, ['always', 'mouseover']), matchBrackets: _boolean(opts.matchBrackets, defaults.matchBrackets), find: find, colorDecorators: _boolean(opts.colorDecorators, defaults.colorDecorators), lightbulbEnabled: _boolean(opts.lightbulb ? opts.lightbulb.enabled : false, defaults.lightbulbEnabled), codeActionsOnSave: _booleanMap(opts.codeActionsOnSave, {}), codeActionsOnSaveTimeout: _clampedInt(opts.codeActionsOnSaveTimeout, defaults.codeActionsOnSaveTimeout, 1, 10000) }; }; return EditorOptionsValidator; }()); exports.EditorOptionsValidator = EditorOptionsValidator; /** * @internal */ var InternalEditorOptionsFactory = /** @class */ (function () { function InternalEditorOptionsFactory() { } InternalEditorOptionsFactory._tweakValidatedOptions = function (opts, accessibilitySupport) { var accessibilityIsOn = (accessibilitySupport === 2 /* Enabled */); var accessibilityIsOff = (accessibilitySupport === 1 /* Disabled */); return { inDiffEditor: opts.inDiffEditor, wordSeparators: opts.wordSeparators, lineNumbersMinChars: opts.lineNumbersMinChars, lineDecorationsWidth: opts.lineDecorationsWidth, readOnly: opts.readOnly, mouseStyle: opts.mouseStyle, disableLayerHinting: opts.disableLayerHinting, automaticLayout: opts.automaticLayout, wordWrap: opts.wordWrap, wordWrapColumn: opts.wordWrapColumn, wordWrapMinified: opts.wordWrapMinified, wrappingIndent: opts.wrappingIndent, wordWrapBreakBeforeCharacters: opts.wordWrapBreakBeforeCharacters, wordWrapBreakAfterCharacters: opts.wordWrapBreakAfterCharacters, wordWrapBreakObtrusiveCharacters: opts.wordWrapBreakObtrusiveCharacters, autoClosingBrackets: opts.autoClosingBrackets, autoClosingQuotes: opts.autoClosingQuotes, autoSurround: opts.autoSurround, autoIndent: opts.autoIndent, dragAndDrop: opts.dragAndDrop, emptySelectionClipboard: opts.emptySelectionClipboard, copyWithSyntaxHighlighting: opts.copyWithSyntaxHighlighting, useTabStops: opts.useTabStops, multiCursorModifier: opts.multiCursorModifier, multiCursorMergeOverlapping: opts.multiCursorMergeOverlapping, accessibilitySupport: opts.accessibilitySupport, showUnused: opts.showUnused, viewInfo: { extraEditorClassName: opts.viewInfo.extraEditorClassName, disableMonospaceOptimizations: opts.viewInfo.disableMonospaceOptimizations, rulers: opts.viewInfo.rulers, ariaLabel: (accessibilityIsOff ? nls.localize(0, null) : opts.viewInfo.ariaLabel), renderLineNumbers: opts.viewInfo.renderLineNumbers, renderCustomLineNumbers: opts.viewInfo.renderCustomLineNumbers, renderFinalNewline: opts.viewInfo.renderFinalNewline, selectOnLineNumbers: opts.viewInfo.selectOnLineNumbers, glyphMargin: opts.viewInfo.glyphMargin, revealHorizontalRightPadding: opts.viewInfo.revealHorizontalRightPadding, roundedSelection: (accessibilityIsOn ? false : opts.viewInfo.roundedSelection), overviewRulerLanes: opts.viewInfo.overviewRulerLanes, overviewRulerBorder: opts.viewInfo.overviewRulerBorder, cursorBlinking: opts.viewInfo.cursorBlinking, mouseWheelZoom: opts.viewInfo.mouseWheelZoom, cursorSmoothCaretAnimation: opts.viewInfo.cursorSmoothCaretAnimation, cursorStyle: opts.viewInfo.cursorStyle, cursorWidth: opts.viewInfo.cursorWidth, hideCursorInOverviewRuler: opts.viewInfo.hideCursorInOverviewRuler, scrollBeyondLastLine: opts.viewInfo.scrollBeyondLastLine, scrollBeyondLastColumn: opts.viewInfo.scrollBeyondLastColumn, smoothScrolling: opts.viewInfo.smoothScrolling, stopRenderingLineAfter: opts.viewInfo.stopRenderingLineAfter, renderWhitespace: (accessibilityIsOn ? 'none' : opts.viewInfo.renderWhitespace), renderControlCharacters: (accessibilityIsOn ? false : opts.viewInfo.renderControlCharacters), fontLigatures: (accessibilityIsOn ? false : opts.viewInfo.fontLigatures), renderIndentGuides: (accessibilityIsOn ? false : opts.viewInfo.renderIndentGuides), highlightActiveIndentGuide: opts.viewInfo.highlightActiveIndentGuide, renderLineHighlight: opts.viewInfo.renderLineHighlight, scrollbar: opts.viewInfo.scrollbar, minimap: { enabled: (accessibilityIsOn ? false : opts.viewInfo.minimap.enabled), side: opts.viewInfo.minimap.side, renderCharacters: opts.viewInfo.minimap.renderCharacters, showSlider: opts.viewInfo.minimap.showSlider, maxColumn: opts.viewInfo.minimap.maxColumn }, fixedOverflowWidgets: opts.viewInfo.fixedOverflowWidgets }, contribInfo: { selectionClipboard: opts.contribInfo.selectionClipboard, hover: opts.contribInfo.hover, links: (accessibilityIsOn ? false : opts.contribInfo.links), contextmenu: opts.contribInfo.contextmenu, quickSuggestions: opts.contribInfo.quickSuggestions, quickSuggestionsDelay: opts.contribInfo.quickSuggestionsDelay, parameterHints: opts.contribInfo.parameterHints, formatOnType: opts.contribInfo.formatOnType, formatOnPaste: opts.contribInfo.formatOnPaste, suggestOnTriggerCharacters: opts.contribInfo.suggestOnTriggerCharacters, acceptSuggestionOnEnter: opts.contribInfo.acceptSuggestionOnEnter, acceptSuggestionOnCommitCharacter: opts.contribInfo.acceptSuggestionOnCommitCharacter, wordBasedSuggestions: opts.contribInfo.wordBasedSuggestions, suggestSelection: opts.contribInfo.suggestSelection, suggestFontSize: opts.contribInfo.suggestFontSize, suggestLineHeight: opts.contribInfo.suggestLineHeight, tabCompletion: opts.contribInfo.tabCompletion, suggest: opts.contribInfo.suggest, gotoLocation: opts.contribInfo.gotoLocation, selectionHighlight: (accessibilityIsOn ? false : opts.contribInfo.selectionHighlight), occurrencesHighlight: (accessibilityIsOn ? false : opts.contribInfo.occurrencesHighlight), codeLens: (accessibilityIsOn ? false : opts.contribInfo.codeLens), folding: (accessibilityIsOn ? false : opts.contribInfo.folding), foldingStrategy: opts.contribInfo.foldingStrategy, showFoldingControls: opts.contribInfo.showFoldingControls, matchBrackets: (accessibilityIsOn ? false : opts.contribInfo.matchBrackets), find: opts.contribInfo.find, colorDecorators: opts.contribInfo.colorDecorators, lightbulbEnabled: opts.contribInfo.lightbulbEnabled, codeActionsOnSave: opts.contribInfo.codeActionsOnSave, codeActionsOnSaveTimeout: opts.contribInfo.codeActionsOnSaveTimeout } }; }; InternalEditorOptionsFactory.createInternalEditorOptions = function (env, _opts) { var accessibilitySupport; if (_opts.accessibilitySupport === 'auto') { // The editor reads the `accessibilitySupport` from the environment accessibilitySupport = env.accessibilitySupport; } else if (_opts.accessibilitySupport === 'on') { accessibilitySupport = 2 /* Enabled */; } else { accessibilitySupport = 1 /* Disabled */; } // Disable some non critical features to get as best performance as possible // See https://github.com/Microsoft/vscode/issues/26730 var opts = this._tweakValidatedOptions(_opts, accessibilitySupport); var lineDecorationsWidth; if (typeof opts.lineDecorationsWidth === 'string' && /^\d+(\.\d+)?ch$/.test(opts.lineDecorationsWidth)) { var multiple = parseFloat(opts.lineDecorationsWidth.substr(0, opts.lineDecorationsWidth.length - 2)); lineDecorationsWidth = multiple * env.fontInfo.typicalHalfwidthCharacterWidth; } else { lineDecorationsWidth = _clampedInt(opts.lineDecorationsWidth, 0, 0, 1000); } if (opts.contribInfo.folding) { lineDecorationsWidth += 16; } var layoutInfo = EditorLayoutProvider.compute({ outerWidth: env.outerWidth, outerHeight: env.outerHeight, showGlyphMargin: opts.viewInfo.glyphMargin, lineHeight: env.fontInfo.lineHeight, showLineNumbers: (opts.viewInfo.renderLineNumbers !== 0 /* Off */), lineNumbersMinChars: opts.lineNumbersMinChars, lineNumbersDigitCount: env.lineNumbersDigitCount, lineDecorationsWidth: lineDecorationsWidth, typicalHalfwidthCharacterWidth: env.fontInfo.typicalHalfwidthCharacterWidth, maxDigitWidth: env.fontInfo.maxDigitWidth, verticalScrollbarWidth: opts.viewInfo.scrollbar.verticalScrollbarSize, horizontalScrollbarHeight: opts.viewInfo.scrollbar.horizontalScrollbarSize, scrollbarArrowSize: opts.viewInfo.scrollbar.arrowSize, verticalScrollbarHasArrows: opts.viewInfo.scrollbar.verticalHasArrows, minimap: opts.viewInfo.minimap.enabled, minimapSide: opts.viewInfo.minimap.side, minimapRenderCharacters: opts.viewInfo.minimap.renderCharacters, minimapMaxColumn: opts.viewInfo.minimap.maxColumn, pixelRatio: env.pixelRatio }); var bareWrappingInfo = null; { var wordWrap = opts.wordWrap; var wordWrapColumn = opts.wordWrapColumn; var wordWrapMinified = opts.wordWrapMinified; 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 }; } } var wrappingInfo = { inDiffEditor: opts.inDiffEditor, isDominatedByLongLines: env.isDominatedByLongLines, isWordWrapMinified: bareWrappingInfo.isWordWrapMinified, isViewportWrapping: bareWrappingInfo.isViewportWrapping, wrappingColumn: bareWrappingInfo.wrappingColumn, wrappingIndent: opts.wrappingIndent, wordWrapBreakBeforeCharacters: opts.wordWrapBreakBeforeCharacters, wordWrapBreakAfterCharacters: opts.wordWrapBreakAfterCharacters, wordWrapBreakObtrusiveCharacters: opts.wordWrapBreakObtrusiveCharacters, }; var className = 'monaco-editor'; if (opts.viewInfo.extraEditorClassName) { className += ' ' + opts.viewInfo.extraEditorClassName; } if (env.extraEditorClassName) { className += ' ' + env.extraEditorClassName; } if (opts.viewInfo.fontLigatures) { className += ' enable-ligatures'; } if (opts.mouseStyle === 'default') { className += ' mouse-default'; } else if (opts.mouseStyle === 'copy') { className += ' mouse-copy'; } return new InternalEditorOptions({ canUseLayerHinting: opts.disableLayerHinting ? false : true, pixelRatio: env.pixelRatio, editorClassName: className, lineHeight: env.fontInfo.lineHeight, readOnly: opts.readOnly, accessibilitySupport: accessibilitySupport, multiCursorModifier: opts.multiCursorModifier, multiCursorMergeOverlapping: opts.multiCursorMergeOverlapping, wordSeparators: opts.wordSeparators, autoClosingBrackets: opts.autoClosingBrackets, autoClosingQuotes: opts.autoClosingQuotes, autoSurround: opts.autoSurround, autoIndent: opts.autoIndent, useTabStops: opts.useTabStops, tabFocusMode: opts.readOnly ? true : env.tabFocusMode, dragAndDrop: opts.dragAndDrop, emptySelectionClipboard: opts.emptySelectionClipboard && env.emptySelectionClipboard, copyWithSyntaxHighlighting: opts.copyWithSyntaxHighlighting, layoutInfo: layoutInfo, fontInfo: env.fontInfo, viewInfo: opts.viewInfo, wrappingInfo: wrappingInfo, contribInfo: opts.contribInfo, showUnused: opts.showUnused, }); }; return InternalEditorOptionsFactory; }()); exports.InternalEditorOptionsFactory = InternalEditorOptionsFactory; /** * @internal */ var EditorLayoutProvider = /** @class */ (function () { function EditorLayoutProvider() { } EditorLayoutProvider.compute = function (_opts) { var outerWidth = _opts.outerWidth | 0; var outerHeight = _opts.outerHeight | 0; var showGlyphMargin = _opts.showGlyphMargin; var lineHeight = _opts.lineHeight | 0; var showLineNumbers = _opts.showLineNumbers; var lineNumbersMinChars = _opts.lineNumbersMinChars | 0; var lineNumbersDigitCount = _opts.lineNumbersDigitCount | 0; var lineDecorationsWidth = _opts.lineDecorationsWidth | 0; var typicalHalfwidthCharacterWidth = _opts.typicalHalfwidthCharacterWidth; var maxDigitWidth = _opts.maxDigitWidth; var verticalScrollbarWidth = _opts.verticalScrollbarWidth | 0; var verticalScrollbarHasArrows = _opts.verticalScrollbarHasArrows; var scrollbarArrowSize = _opts.scrollbarArrowSize | 0; var horizontalScrollbarHeight = _opts.horizontalScrollbarHeight | 0; var minimap = _opts.minimap; var minimapSide = _opts.minimapSide; var minimapRenderCharacters = _opts.minimapRenderCharacters; var minimapMaxColumn = _opts.minimapMaxColumn | 0; var pixelRatio = _opts.pixelRatio; 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 (!minimap) { minimapLeft = 0; minimapWidth = 0; renderMinimap = 0 /* None */; contentWidth = remainingWidth; } else { var minimapCharWidth = void 0; if (pixelRatio >= 2) { renderMinimap = minimapRenderCharacters ? 2 /* Large */ : 4 /* LargeBlocks */; minimapCharWidth = 2 / pixelRatio; } else { renderMinimap = minimapRenderCharacters ? 1 /* Small */ : 3 /* SmallBlocks */; minimapCharWidth = 1 / pixelRatio; } // 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))); 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, glyphMarginHeight: outerHeight, lineNumbersLeft: lineNumbersLeft, lineNumbersWidth: lineNumbersWidth, lineNumbersHeight: outerHeight, decorationsLeft: decorationsLeft, decorationsWidth: lineDecorationsWidth, decorationsHeight: outerHeight, contentLeft: contentLeft, contentWidth: contentWidth, contentHeight: outerHeight, renderMinimap: renderMinimap, minimapLeft: minimapLeft, minimapWidth: minimapWidth, viewportColumn: viewportColumn, verticalScrollbarWidth: verticalScrollbarWidth, horizontalScrollbarHeight: horizontalScrollbarHeight, overviewRuler: { top: verticalArrowSize, width: verticalScrollbarWidth, height: (outerHeight - 2 * verticalArrowSize), right: 0 } }; }; return EditorLayoutProvider; }()); exports.EditorLayoutProvider = EditorLayoutProvider; 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.EDITOR_DEFAULTS = { inDiffEditor: false, wordSeparators: wordHelper_1.USUAL_WORD_SEPARATORS, lineNumbersMinChars: 5, lineDecorationsWidth: 10, readOnly: false, mouseStyle: 'text', disableLayerHinting: false, automaticLayout: false, wordWrap: 'off', wordWrapColumn: 80, wordWrapMinified: true, wrappingIndent: 1 /* Same */, wordWrapBreakBeforeCharacters: '([{‘“〈《「『【〔([{「£¥$£¥++', wordWrapBreakAfterCharacters: ' \t})]?|/&,;¢°′″‰℃、。。、¢,.:;?!%・・ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ァィゥェォャュョッー”〉》」』】〕)]}」', wordWrapBreakObtrusiveCharacters: '.', autoClosingBrackets: 'languageDefined', autoClosingQuotes: 'languageDefined', autoSurround: 'languageDefined', autoIndent: true, dragAndDrop: true, emptySelectionClipboard: true, copyWithSyntaxHighlighting: true, useTabStops: true, multiCursorModifier: 'altKey', multiCursorMergeOverlapping: true, accessibilitySupport: 'auto', showUnused: true, viewInfo: { extraEditorClassName: '', disableMonospaceOptimizations: false, rulers: [], ariaLabel: nls.localize(1, null), renderLineNumbers: 1 /* On */, renderCustomLineNumbers: null, renderFinalNewline: true, selectOnLineNumbers: true, glyphMargin: true, revealHorizontalRightPadding: 30, roundedSelection: true, overviewRulerLanes: 2, overviewRulerBorder: true, cursorBlinking: 1 /* Blink */, mouseWheelZoom: false, cursorSmoothCaretAnimation: false, cursorStyle: TextEditorCursorStyle.Line, cursorWidth: 0, hideCursorInOverviewRuler: false, scrollBeyondLastLine: true, scrollBeyondLastColumn: 5, smoothScrolling: false, stopRenderingLineAfter: 10000, renderWhitespace: 'none', renderControlCharacters: false, fontLigatures: false, renderIndentGuides: true, highlightActiveIndentGuide: true, renderLineHighlight: 'line', 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, mouseWheelScrollSensitivity: 1, fastScrollSensitivity: 5, }, minimap: { enabled: true, side: 'right', showSlider: 'mouseover', renderCharacters: true, maxColumn: 120 }, fixedOverflowWidgets: false, }, contribInfo: { selectionClipboard: true, hover: { enabled: true, delay: 300, sticky: true }, links: true, contextmenu: true, quickSuggestions: { other: true, comments: false, strings: false }, quickSuggestionsDelay: 10, parameterHints: { enabled: true, cycle: false }, formatOnType: false, formatOnPaste: false, suggestOnTriggerCharacters: true, acceptSuggestionOnEnter: 'on', acceptSuggestionOnCommitCharacter: true, wordBasedSuggestions: true, suggestSelection: 'recentlyUsed', suggestFontSize: 0, suggestLineHeight: 0, tabCompletion: 'off', suggest: { filterGraceful: true, snippets: 'inline', snippetsPreventQuickSuggestions: true, localityBonus: false, shareSuggestSelections: false, showIcons: true, maxVisibleSuggestions: 12, filteredTypes: Object.create(null) }, gotoLocation: { multiple: 'peek' }, selectionHighlight: true, occurrencesHighlight: true, codeLens: true, folding: true, foldingStrategy: 'auto', showFoldingControls: 'mouseover', matchBrackets: true, find: { seedSearchStringFromSelection: true, autoFindInSelection: false, globalFindClipboard: false, addExtraSpaceOnTop: true }, colorDecorators: true, lightbulbEnabled: true, codeActionsOnSave: {}, codeActionsOnSaveTimeout: 750 }, }; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[114/*vs/editor/common/config/fontInfo*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,48/*vs/editor/common/config/editorOptions*/,101/*vs/editor/common/config/editorZoom*/]), function (require, exports, platform, editorOptions_1, 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; /** * Font settings maximum and minimum limits */ var MINIMUM_FONT_SIZE = 8; var MAXIMUM_FONT_SIZE = 100; var MINIMUM_LINE_HEIGHT = 8; var MAXIMUM_LINE_HEIGHT = 150; var MINIMUM_LETTER_SPACING = -5; var MAXIMUM_LETTER_SPACING = 20; function safeParseFloat(n, defaultValue) { if (typeof n === 'number') { return n; } if (typeof n === 'undefined') { return defaultValue; } var r = parseFloat(n); if (isNaN(r)) { return defaultValue; } return r; } function safeParseInt(n, defaultValue) { if (typeof n === 'number') { return Math.round(n); } if (typeof n === 'undefined') { return defaultValue; } var r = parseInt(n); if (isNaN(r)) { return defaultValue; } return r; } function clamp(n, min, max) { if (n < min) { return min; } if (n > max) { return max; } return n; } function _string(value, defaultValue) { if (typeof value !== 'string') { return defaultValue; } return value; } 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.lineHeight = opts.lineHeight | 0; this.letterSpacing = opts.letterSpacing; } /** * @internal */ BareFontInfo.createFromRawSettings = function (opts, zoomLevel, ignoreEditorZoom) { if (ignoreEditorZoom === void 0) { ignoreEditorZoom = false; } var fontFamily = _string(opts.fontFamily, editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily); var fontWeight = _string(opts.fontWeight, editorOptions_1.EDITOR_FONT_DEFAULTS.fontWeight); var fontSize = safeParseFloat(opts.fontSize, editorOptions_1.EDITOR_FONT_DEFAULTS.fontSize); fontSize = clamp(fontSize, 0, MAXIMUM_FONT_SIZE); if (fontSize === 0) { fontSize = editorOptions_1.EDITOR_FONT_DEFAULTS.fontSize; } else if (fontSize < MINIMUM_FONT_SIZE) { fontSize = MINIMUM_FONT_SIZE; } var lineHeight = safeParseInt(opts.lineHeight, 0); lineHeight = clamp(lineHeight, 0, MAXIMUM_LINE_HEIGHT); if (lineHeight === 0) { lineHeight = Math.round(GOLDEN_LINE_HEIGHT_RATIO * fontSize); } else if (lineHeight < MINIMUM_LINE_HEIGHT) { lineHeight = MINIMUM_LINE_HEIGHT; } var letterSpacing = safeParseFloat(opts.letterSpacing, 0); letterSpacing = clamp(letterSpacing, MINIMUM_LETTER_SPACING, MAXIMUM_LETTER_SPACING); 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, lineHeight: lineHeight, letterSpacing: letterSpacing }); }; /** * @internal */ BareFontInfo.prototype.getId = function () { return this.zoomLevel + '-' + this.fontFamily + '-' + this.fontWeight + '-' + this.fontSize + '-' + 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.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.lineHeight === other.lineHeight && this.letterSpacing === other.letterSpacing && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth && this.typicalFullwidthCharacterWidth === other.typicalFullwidthCharacterWidth && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.spaceWidth === other.spaceWidth && 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[309/*vs/editor/contrib/suggest/completionModel*/], __M([0/*require*/,1/*exports*/,65/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,48/*vs/editor/common/config/editorOptions*/]), function (require, exports, filters_1, lifecycle_1, editorOptions_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LineContext = /** @class */ (function () { function LineContext() { } return LineContext; }()); exports.LineContext = LineContext; var CompletionModel = /** @class */ (function () { function CompletionModel(items, column, lineContext, wordDistance, options) { if (options === void 0) { options = editorOptions_1.EDITOR_DEFAULTS.contribInfo.suggest; } this._snippetCompareFn = CompletionModel._compareCompletionItems; this._items = items; this._column = column; this._wordDistance = wordDistance; this._options = options; this._refilterKind = 1 /* All */; this._lineContext = lineContext; if (options.snippets === 'top') { this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsUp; } else if (options.snippets === 'bottom') { this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsDown; } } CompletionModel.prototype.dispose = function () { var seen = new Set(); for (var _i = 0, _a = this._items; _i < _a.length; _i++) { var container = _a[_i].container; if (!seen.has(container)) { seen.add(container); if (lifecycle_1.isDisposable(container)) { container.dispose(); } } } }; 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.completion.range.startColumn; 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; } } 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 } item.score = filters_1.anyScore(word, wordLow, 0, item.completion.label, 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, item.completion.label, 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; }); define(__m[310/*vs/nls!vs/editor/common/modes/modesRegistry*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/modes/modesRegistry", data); }); define(__m[311/*vs/nls!vs/editor/common/standaloneStrings*/], __M([6/*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[50/*vs/editor/common/standaloneStrings*/], __M([0/*require*/,1/*exports*/,311/*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[313/*vs/nls!vs/editor/common/view/editorColorRegistry*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/view/editorColorRegistry", data); }); define(__m[314/*vs/nls!vs/editor/contrib/bracketMatching/bracketMatching*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/bracketMatching/bracketMatching", data); }); define(__m[315/*vs/nls!vs/editor/contrib/caretOperations/caretOperations*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/caretOperations", data); }); define(__m[316/*vs/nls!vs/editor/contrib/caretOperations/transpose*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/transpose", data); }); define(__m[317/*vs/nls!vs/editor/contrib/clipboard/clipboard*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/clipboard/clipboard", data); }); define(__m[318/*vs/nls!vs/editor/contrib/codeAction/codeActionCommands*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codeAction/codeActionCommands", data); }); define(__m[319/*vs/nls!vs/editor/contrib/comment/comment*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/comment/comment", data); }); define(__m[320/*vs/nls!vs/editor/contrib/contextmenu/contextmenu*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/contextmenu/contextmenu", data); }); define(__m[321/*vs/nls!vs/editor/contrib/cursorUndo/cursorUndo*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/cursorUndo/cursorUndo", data); }); define(__m[322/*vs/nls!vs/editor/contrib/find/findController*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/findController", data); }); define(__m[323/*vs/nls!vs/editor/contrib/find/findWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/findWidget", data); }); define(__m[324/*vs/nls!vs/editor/contrib/folding/folding*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/folding/folding", data); }); define(__m[325/*vs/nls!vs/editor/contrib/fontZoom/fontZoom*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/fontZoom/fontZoom", data); }); define(__m[326/*vs/nls!vs/editor/contrib/format/format*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/format", data); }); define(__m[327/*vs/nls!vs/editor/contrib/format/formatActions*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/formatActions", data); }); define(__m[328/*vs/nls!vs/editor/contrib/goToDefinition/goToDefinitionCommands*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/goToDefinition/goToDefinitionCommands", data); }); define(__m[329/*vs/nls!vs/editor/contrib/goToDefinition/goToDefinitionMouse*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/goToDefinition/goToDefinitionMouse", data); }); define(__m[330/*vs/nls!vs/editor/contrib/gotoError/gotoError*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/gotoError", data); }); define(__m[331/*vs/nls!vs/editor/contrib/gotoError/gotoErrorWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/gotoErrorWidget", data); }); define(__m[332/*vs/nls!vs/editor/contrib/hover/hover*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/hover", data); }); define(__m[333/*vs/nls!vs/editor/contrib/hover/modesContentHover*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/modesContentHover", data); }); define(__m[334/*vs/nls!vs/editor/contrib/inPlaceReplace/inPlaceReplace*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inPlaceReplace/inPlaceReplace", data); }); define(__m[335/*vs/nls!vs/editor/contrib/linesOperations/linesOperations*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/linesOperations/linesOperations", data); }); define(__m[336/*vs/nls!vs/editor/contrib/links/links*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/links/links", data); }); define(__m[337/*vs/nls!vs/editor/contrib/message/messageController*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/message/messageController", data); }); define(__m[338/*vs/nls!vs/editor/contrib/multicursor/multicursor*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/multicursor/multicursor", data); }); define(__m[339/*vs/nls!vs/editor/contrib/parameterHints/parameterHints*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/parameterHints", data); }); define(__m[340/*vs/nls!vs/editor/contrib/parameterHints/parameterHintsWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/parameterHintsWidget", data); }); define(__m[341/*vs/nls!vs/editor/contrib/referenceSearch/peekViewWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/referenceSearch/peekViewWidget", data); }); define(__m[342/*vs/nls!vs/editor/contrib/referenceSearch/referenceSearch*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/referenceSearch/referenceSearch", data); }); define(__m[343/*vs/nls!vs/editor/contrib/referenceSearch/referencesController*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/referenceSearch/referencesController", data); }); define(__m[344/*vs/nls!vs/editor/contrib/referenceSearch/referencesModel*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/referenceSearch/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[90/*vs/editor/contrib/referenceSearch/referencesModel*/], __M([0/*require*/,1/*exports*/,344/*vs/nls!vs/editor/contrib/referenceSearch/referencesModel*/,4/*vs/base/common/event*/,54/*vs/base/common/resources*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,142/*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(parent, _range, isProviderFirst) { this.parent = parent; this._range = _range; this.isProviderFirst = isProviderFirst; this._onRefChanged = new event_1.Emitter(); this.onRefChanged = this._onRefChanged.event; 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._onRefChanged.fire(this); }, enumerable: true, configurable: true }); OneReference.prototype.getAriaMessage = function () { return nls_1.localize(0, null, resources_1.basename(this.uri), this.range.startLineNumber, this.range.startColumn); }; return OneReference; }()); exports.OneReference = OneReference; var FilePreview = /** @class */ (function () { function FilePreview(_modelReference) { this._modelReference = _modelReference; } FilePreview.prototype.dispose = function () { lifecycle_1.dispose(this._modelReference); }; 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, Number.MAX_VALUE); var ret = { before: model.getValueInRange(beforeRange).replace(/^\s+/, strings.empty), inside: model.getValueInRange(range), after: model.getValueInRange(afterRange).replace(/\s+$/, strings.empty) }; return ret; }; return FilePreview; }()); exports.FilePreview = FilePreview; var FileReferences = /** @class */ (function () { function FileReferences(_parent, _uri) { this._parent = _parent; this._uri = _uri; this._children = []; } Object.defineProperty(FileReferences.prototype, "id", { get: function () { return this._uri.toString(); }, enumerable: true, configurable: true }); Object.defineProperty(FileReferences.prototype, "parent", { get: function () { return this._parent; }, enumerable: true, configurable: true }); Object.defineProperty(FileReferences.prototype, "children", { get: function () { return this._children; }, enumerable: true, configurable: true }); Object.defineProperty(FileReferences.prototype, "uri", { get: function () { return this._uri; }, enumerable: true, configurable: true }); 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 }); FileReferences.prototype.getAriaMessage = 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); } }; 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 = []; _this._resolved = true; _this._loadFailure = err; return _this; })); }; FileReferences.prototype.dispose = function () { if (this._preview) { this._preview.dispose(); this._preview = undefined; } }; return FileReferences; }()); exports.FileReferences = FileReferences; var ReferencesModel = /** @class */ (function () { function ReferencesModel(references) { var _this = this; this.groups = []; this.references = []; this._onDidChangeReferenceRange = new event_1.Emitter(); this.onDidChangeReferenceRange = this._onDidChangeReferenceRange.event; this._disposables = []; // grouping and sorting var providersFirst = references[0]; references.sort(ReferencesModel._compareReferences); var current; for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { var ref = references_1[_i]; if (!current || current.uri.toString() !== ref.uri.toString()) { // new group current = new FileReferences(this, ref.uri); this.groups.push(current); } // append, check for equality first! if (current.children.length === 0 || !range_1.Range.equalsRange(ref.range, current.children[current.children.length - 1].range)) { var oneRef = new OneReference(current, ref.targetSelectionRange || ref.range, providersFirst === ref); this._disposables.push(oneRef.onRefChanged(function (e) { return _this._onDidChangeReferenceRange.fire(e); })); this.references.push(oneRef); current.children.push(oneRef); } } } Object.defineProperty(ReferencesModel.prototype, "empty", { get: function () { return this.groups.length === 0; }, enumerable: true, configurable: true }); ReferencesModel.prototype.getAriaMessage = function () { if (this.empty) { 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); } }; 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.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.prototype.dispose = function () { lifecycle_1.dispose(this.groups); lifecycle_1.dispose(this._disposables); this.groups.length = 0; this._disposables.length = 0; }; ReferencesModel._compareReferences = function (a, b) { var auri = a.uri.toString(); var buri = b.uri.toString(); if (auri < buri) { return -1; } else if (auri > buri) { return 1; } else { return range_1.Range.compareRangesUsingStarts(a.range, b.range); } }; return ReferencesModel; }()); exports.ReferencesModel = ReferencesModel; }); define(__m[346/*vs/nls!vs/editor/contrib/referenceSearch/referencesTree*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/referenceSearch/referencesTree", data); }); define(__m[347/*vs/nls!vs/editor/contrib/referenceSearch/referencesWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/referenceSearch/referencesWidget", data); }); define(__m[348/*vs/nls!vs/editor/contrib/rename/rename*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/rename", data); }); define(__m[349/*vs/nls!vs/editor/contrib/rename/renameInputField*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/renameInputField", data); }); define(__m[350/*vs/nls!vs/editor/contrib/smartSelect/smartSelect*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/smartSelect/smartSelect", data); }); define(__m[351/*vs/nls!vs/editor/contrib/snippet/snippetVariables*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/snippet/snippetVariables", data); }); define(__m[352/*vs/nls!vs/editor/contrib/suggest/suggestController*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestController", data); }); define(__m[353/*vs/nls!vs/editor/contrib/suggest/suggestWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestWidget", data); }); define(__m[354/*vs/nls!vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode", data); }); define(__m[355/*vs/nls!vs/editor/contrib/tokenization/tokenization*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/tokenization/tokenization", data); }); define(__m[356/*vs/nls!vs/editor/contrib/wordHighlighter/wordHighlighter*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/wordHighlighter/wordHighlighter", data); }); define(__m[357/*vs/nls!vs/platform/configuration/common/configurationRegistry*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/configuration/common/configurationRegistry", data); }); define(__m[358/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/keybinding/common/abstractKeybindingService", data); }); define(__m[359/*vs/nls!vs/platform/list/browser/listService*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/list/browser/listService", data); }); define(__m[360/*vs/nls!vs/platform/markers/common/markers*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/markers/common/markers", data); }); define(__m[361/*vs/nls!vs/platform/theme/common/colorRegistry*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/theme/common/colorRegistry", 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[362/*vs/platform/accessibility/common/accessibilityService*/], __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 BrowserAccessibilityService = /** @class */ (function (_super) { __extends(BrowserAccessibilityService, _super); function BrowserAccessibilityService() { var _this = _super !== null && _super.apply(this, arguments) || this; _this._accessibilitySupport = 0 /* Unknown */; _this._onDidChangeAccessibilitySupport = new event_1.Emitter(); _this.onDidChangeAccessibilitySupport = _this._onDidChangeAccessibilitySupport.event; return _this; } BrowserAccessibilityService.prototype.getAccessibilitySupport = function () { return this._accessibilitySupport; }; return BrowserAccessibilityService; }(lifecycle_1.Disposable)); exports.BrowserAccessibilityService = BrowserAccessibilityService; }); define(__m[363/*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[221/*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[219/*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[109/*vs/platform/instantiation/common/extensions*/], __M([0/*require*/,1/*exports*/,219/*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: id, descriptor: new descriptors_1.SyncDescriptor(ctor, [], supportsDelayedInstantiation) }); } exports.registerSingleton = registerSingleton; }); /*--------------------------------------------------------------------------------------------- * 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/platform/instantiation/common/graph*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/,572/*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[13/*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[98/*vs/editor/browser/services/bulkEditService*/], __M([0/*require*/,1/*exports*/,13/*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*/,13/*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[63/*vs/editor/common/services/editorWorkerService*/], __M([0/*require*/,1/*exports*/,13/*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[211/*vs/editor/common/services/markersDecorationService*/], __M([0/*require*/,1/*exports*/,13/*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[67/*vs/editor/common/services/modeService*/], __M([0/*require*/,1/*exports*/,13/*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[42/*vs/editor/common/services/modelService*/], __M([0/*require*/,1/*exports*/,13/*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[375/*vs/editor/common/modes/languageFeatureRegistry*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,271/*vs/editor/common/modes/languageSelector*/,42/*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[16/*vs/editor/common/modes*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,375/*vs/editor/common/modes/languageFeatureRegistry*/,254/*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 */ exports.symbolKindToCssClass = (function () { var _fromMapping = Object.create(null); _fromMapping[0 /* File */] = 'file'; _fromMapping[1 /* Module */] = 'module'; _fromMapping[2 /* Namespace */] = 'namespace'; _fromMapping[3 /* Package */] = 'package'; _fromMapping[4 /* Class */] = 'class'; _fromMapping[5 /* Method */] = 'method'; _fromMapping[6 /* Property */] = 'property'; _fromMapping[7 /* Field */] = 'field'; _fromMapping[8 /* Constructor */] = 'constructor'; _fromMapping[9 /* Enum */] = 'enum'; _fromMapping[10 /* Interface */] = 'interface'; _fromMapping[11 /* Function */] = 'function'; _fromMapping[12 /* Variable */] = 'variable'; _fromMapping[13 /* Constant */] = 'constant'; _fromMapping[14 /* String */] = 'string'; _fromMapping[15 /* Number */] = 'number'; _fromMapping[16 /* Boolean */] = 'boolean'; _fromMapping[17 /* Array */] = 'array'; _fromMapping[18 /* Object */] = 'object'; _fromMapping[19 /* Key */] = 'key'; _fromMapping[20 /* Null */] = 'null'; _fromMapping[21 /* EnumMember */] = 'enum-member'; _fromMapping[22 /* Struct */] = 'struct'; _fromMapping[23 /* Event */] = 'event'; _fromMapping[24 /* Operator */] = 'operator'; _fromMapping[25 /* TypeParameter */] = 'type-parameter'; return function toCssClassName(kind, inline) { return "symbol-icon " + (inline ? 'inline' : 'block') + " " + (_fromMapping[kind] || 'property'); }; })(); 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 */ function isResourceTextEdit(thing) { return types_1.isObject(thing) && thing.resource && Array.isArray(thing.edits); } exports.isResourceTextEdit = isResourceTextEdit; // --- 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.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[94/*vs/editor/common/core/lineTokens*/], __M([0/*require*/,1/*exports*/,16/*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.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[61/*vs/editor/common/modes/nullMode*/], __M([0/*require*/,1/*exports*/,103/*vs/editor/common/core/token*/,16/*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[379/*vs/editor/common/model/textModelTokens*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,10/*vs/base/common/errors*/,94/*vs/editor/common/core/lineTokens*/,12/*vs/editor/common/core/position*/,16/*vs/editor/common/modes*/,61/*vs/editor/common/modes/nullMode*/]), function (require, exports, arrays, errors_1, lineTokens_1, position_1, modes_1, nullMode_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 ModelLineTokens = /** @class */ (function () { function ModelLineTokens(state) { this._state = state; this._lineTokens = null; this._invalid = true; } ModelLineTokens.prototype.deleteBeginning = function (toChIndex) { if (this._lineTokens === null || this._lineTokens === EMPTY_LINE_TOKENS) { return; } this.delete(0, toChIndex); }; ModelLineTokens.prototype.deleteEnding = function (fromChIndex) { if (this._lineTokens === null || this._lineTokens === EMPTY_LINE_TOKENS) { return; } var tokens = new Uint32Array(this._lineTokens); var lineTextLength = tokens[tokens.length - 2]; this.delete(fromChIndex, lineTextLength); }; ModelLineTokens.prototype.delete = function (fromChIndex, toChIndex) { if (this._lineTokens === null || this._lineTokens === EMPTY_LINE_TOKENS || fromChIndex === toChIndex) { return; } var tokens = new Uint32Array(this._lineTokens); var tokensCount = (tokens.length >>> 1); // special case: deleting everything if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) { this._lineTokens = EMPTY_LINE_TOKENS; return; } 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; } 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; } var tmp = new Uint32Array(dest); tmp.set(tokens.subarray(0, dest), 0); this._lineTokens = tmp.buffer; }; ModelLineTokens.prototype.append = function (_otherTokens) { if (_otherTokens === EMPTY_LINE_TOKENS) { return; } if (this._lineTokens === EMPTY_LINE_TOKENS) { this._lineTokens = _otherTokens; return; } if (this._lineTokens === null) { return; } if (_otherTokens === null) { // cannot determine combined line length... this._lineTokens = null; return; } var myTokens = new Uint32Array(this._lineTokens); var otherTokens = new Uint32Array(_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]; } this._lineTokens = result.buffer; }; ModelLineTokens.prototype.insert = function (chIndex, textLength) { if (!this._lineTokens) { // nothing to do return; } var tokens = new Uint32Array(this._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 ModelLineTokens; }()); var ModelLinesTokens = /** @class */ (function () { function ModelLinesTokens(languageIdentifier, tokenizationSupport) { this.languageIdentifier = languageIdentifier; this.tokenizationSupport = tokenizationSupport; this._tokens = []; if (this.tokenizationSupport) { var initialState = null; try { initialState = this.tokenizationSupport.getInitialState(); } catch (e) { errors_1.onUnexpectedError(e); this.tokenizationSupport = null; } if (initialState) { this._tokens[0] = new ModelLineTokens(initialState); } } this._invalidLineStartIndex = 0; this._lastState = null; } Object.defineProperty(ModelLinesTokens.prototype, "inValidLineStartIndex", { get: function () { return this._invalidLineStartIndex; }, enumerable: true, configurable: true }); ModelLinesTokens.prototype.getTokens = function (topLevelLanguageId, lineIndex, lineText) { var rawLineTokens = null; if (lineIndex < this._tokens.length && this._tokens[lineIndex]) { rawLineTokens = this._tokens[lineIndex]._lineTokens; } if (rawLineTokens !== null && rawLineTokens !== EMPTY_LINE_TOKENS) { return new lineTokens_1.LineTokens(new Uint32Array(rawLineTokens), lineText); } var lineTokens = new Uint32Array(2); lineTokens[0] = lineText.length; lineTokens[1] = getDefaultMetadata(topLevelLanguageId); return new lineTokens_1.LineTokens(lineTokens, lineText); }; ModelLinesTokens.prototype.isCheapToTokenize = function (lineNumber) { var firstInvalidLineNumber = this._invalidLineStartIndex + 1; return (firstInvalidLineNumber >= lineNumber); }; ModelLinesTokens.prototype.hasLinesToTokenize = function (buffer) { return (this._invalidLineStartIndex < buffer.getLineCount()); }; ModelLinesTokens.prototype.invalidateLine = function (lineIndex) { this._setIsInvalid(lineIndex, true); if (lineIndex < this._invalidLineStartIndex) { this._setIsInvalid(this._invalidLineStartIndex, true); this._invalidLineStartIndex = lineIndex; } }; ModelLinesTokens.prototype._setIsInvalid = function (lineIndex, invalid) { if (lineIndex < this._tokens.length && this._tokens[lineIndex]) { this._tokens[lineIndex]._invalid = invalid; } }; ModelLinesTokens.prototype._isInvalid = function (lineIndex) { if (lineIndex < this._tokens.length && this._tokens[lineIndex]) { return this._tokens[lineIndex]._invalid; } return true; }; ModelLinesTokens.prototype._getState = function (lineIndex) { if (lineIndex < this._tokens.length && this._tokens[lineIndex]) { return this._tokens[lineIndex]._state; } return null; }; ModelLinesTokens.prototype._setTokens = function (topLevelLanguageId, lineIndex, lineTextLength, tokens) { var target; if (lineIndex < this._tokens.length && this._tokens[lineIndex]) { target = this._tokens[lineIndex]; } else { target = new ModelLineTokens(null); this._tokens[lineIndex] = target; } if (lineTextLength === 0) { var hasDifferentLanguageId = false; if (tokens && tokens.length > 1) { hasDifferentLanguageId = (modes_1.TokenMetadata.getLanguageId(tokens[1]) !== topLevelLanguageId); } if (!hasDifferentLanguageId) { target._lineTokens = EMPTY_LINE_TOKENS; return; } } if (!tokens || tokens.length === 0) { tokens = new Uint32Array(2); tokens[0] = 0; tokens[1] = getDefaultMetadata(topLevelLanguageId); } lineTokens_1.LineTokens.convertToEndOffset(tokens, lineTextLength); target._lineTokens = tokens.buffer; }; ModelLinesTokens.prototype._setState = function (lineIndex, state) { if (lineIndex < this._tokens.length && this._tokens[lineIndex]) { this._tokens[lineIndex]._state = state; } else { var tmp = new ModelLineTokens(state); this._tokens[lineIndex] = tmp; } }; //#region Editing ModelLinesTokens.prototype.applyEdits = function (range, eolCount, firstLineLength) { 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, firstLineLength); }; ModelLinesTokens.prototype._acceptDeleteRange = function (range) { var firstLineIndex = range.startLineNumber - 1; if (firstLineIndex >= this._tokens.length) { return; } if (range.startLineNumber === range.endLineNumber) { if (range.startColumn === range.endColumn) { // Nothing to delete return; } this._tokens[firstLineIndex].delete(range.startColumn - 1, range.endColumn - 1); return; } var firstLine = this._tokens[firstLineIndex]; firstLine.deleteEnding(range.startColumn - 1); var lastLineIndex = range.endLineNumber - 1; var lastLineTokens = null; if (lastLineIndex < this._tokens.length) { var lastLine = this._tokens[lastLineIndex]; lastLine.deleteBeginning(range.endColumn - 1); lastLineTokens = lastLine._lineTokens; } // Take remaining text on last line and append it to remaining text on first line firstLine.append(lastLineTokens); // Delete middle lines this._tokens.splice(range.startLineNumber, range.endLineNumber - range.startLineNumber); }; ModelLinesTokens.prototype._acceptInsertText = function (position, eolCount, firstLineLength) { if (eolCount === 0 && firstLineLength === 0) { // Nothing to insert return; } var lineIndex = position.lineNumber - 1; if (lineIndex >= this._tokens.length) { return; } if (eolCount === 0) { // Inserting text on one line this._tokens[lineIndex].insert(position.column - 1, firstLineLength); return; } var line = this._tokens[lineIndex]; line.deleteEnding(position.column - 1); line.insert(position.column - 1, firstLineLength); var insert = new Array(eolCount); for (var i = eolCount - 1; i >= 0; i--) { insert[i] = new ModelLineTokens(null); } this._tokens = arrays.arrayInsert(this._tokens, position.lineNumber, insert); }; //#endregion //#region Tokenization ModelLinesTokens.prototype._tokenizeOneLine = function (buffer, eventBuilder) { if (!this.hasLinesToTokenize(buffer)) { return buffer.getLineCount() + 1; } var lineNumber = this._invalidLineStartIndex + 1; this._updateTokensUntilLine(buffer, eventBuilder, lineNumber); return lineNumber; }; ModelLinesTokens.prototype._tokenizeText = function (buffer, text, state) { var r = null; if (this.tokenizationSupport) { try { r = this.tokenizationSupport.tokenize2(text, state, 0); } catch (e) { errors_1.onUnexpectedError(e); } } if (!r) { r = nullMode_1.nullTokenize2(this.languageIdentifier.id, text, state, 0); } return r; }; ModelLinesTokens.prototype._updateTokensUntilLine = function (buffer, eventBuilder, lineNumber) { if (!this.tokenizationSupport) { this._invalidLineStartIndex = buffer.getLineCount(); return; } var linesLength = buffer.getLineCount(); var endLineIndex = lineNumber - 1; // Validate all states up to and including endLineIndex for (var lineIndex = this._invalidLineStartIndex; lineIndex <= endLineIndex; lineIndex++) { var endStateIndex = lineIndex + 1; var text = buffer.getLineContent(lineIndex + 1); var lineStartState = this._getState(lineIndex); var r = null; try { // Tokenize only the first X characters var freshState = lineStartState.clone(); r = this.tokenizationSupport.tokenize2(text, freshState, 0); } catch (e) { errors_1.onUnexpectedError(e); } if (!r) { r = nullMode_1.nullTokenize2(this.languageIdentifier.id, text, lineStartState, 0); } this._setTokens(this.languageIdentifier.id, lineIndex, text.length, r.tokens); eventBuilder.registerChangedTokens(lineIndex + 1); this._setIsInvalid(lineIndex, false); if (endStateIndex < linesLength) { var previousEndState = this._getState(endStateIndex); if (previousEndState !== null && r.endState.equals(previousEndState)) { // The end state of this line remains the same var nextInvalidLineIndex = lineIndex + 1; while (nextInvalidLineIndex < linesLength) { if (this._isInvalid(nextInvalidLineIndex)) { break; } if (nextInvalidLineIndex + 1 < linesLength) { if (this._getState(nextInvalidLineIndex + 1) === null) { break; } } else { if (this._lastState === null) { break; } } nextInvalidLineIndex++; } this._invalidLineStartIndex = Math.max(this._invalidLineStartIndex, nextInvalidLineIndex); lineIndex = nextInvalidLineIndex - 1; // -1 because the outer loop increments it } else { this._setState(endStateIndex, r.endState); } } else { this._lastState = r.endState; } } this._invalidLineStartIndex = Math.max(this._invalidLineStartIndex, endLineIndex + 1); }; return ModelLinesTokens; }()); exports.ModelLinesTokens = ModelLinesTokens; var ModelTokensChangedEventBuilder = /** @class */ (function () { function ModelTokensChangedEventBuilder() { this._ranges = []; } ModelTokensChangedEventBuilder.prototype.registerChangedTokens = function (lineNumber) { var ranges = this._ranges; var rangesLength = ranges.length; var previousRange = rangesLength > 0 ? ranges[rangesLength - 1] : null; if (previousRange && previousRange.toLineNumber === lineNumber - 1) { // extend previous range previousRange.toLineNumber++; } else { // insert new range ranges[rangesLength] = { fromLineNumber: lineNumber, toLineNumber: lineNumber }; } }; ModelTokensChangedEventBuilder.prototype.build = function () { if (this._ranges.length === 0) { return null; } return { tokenizationSupportChanged: false, ranges: this._ranges }; }; return ModelTokensChangedEventBuilder; }()); exports.ModelTokensChangedEventBuilder = ModelTokensChangedEventBuilder; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[29/*vs/editor/common/model/textModel*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,122/*vs/base/common/stopwatch*/,5/*vs/base/common/strings*/,25/*vs/base/common/uri*/,48/*vs/editor/common/config/editorOptions*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,45/*vs/editor/common/model*/,290/*vs/editor/common/model/editStack*/,288/*vs/editor/common/model/indentationGuesser*/,284/*vs/editor/common/model/intervalTree*/,273/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/,278/*vs/editor/common/model/textModelEvents*/,137/*vs/editor/common/model/textModelSearch*/,379/*vs/editor/common/model/textModelTokens*/,107/*vs/editor/common/model/wordHelper*/,16/*vs/editor/common/modes*/,39/*vs/editor/common/modes/languageConfigurationRegistry*/,61/*vs/editor/common/modes/nullMode*/,144/*vs/editor/common/modes/supports*/,146/*vs/editor/common/modes/supports/richEditBrackets*/,20/*vs/base/common/types*/]), function (require, exports, errors_1, event_1, lifecycle_1, stopwatch_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, modes_1, languageConfigurationRegistry_1, nullMode_1, supports_1, richEditBrackets_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CHEAP_TOKENIZATION_LENGTH_LIMIT = 2048; 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; /** * Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc. */ function singleLetter(result) { var LETTERS_CNT = (90 /* Z */ - 65 /* A */ + 1); result = result % (2 * LETTERS_CNT); if (result < LETTERS_CNT) { return String.fromCharCode(97 /* a */ + result); } return String.fromCharCode(65 /* A */ + result - LETTERS_CNT); } 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._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._setVersionId(1); _this._isDisposed = false; _this._isDisposing = false; _this._languageIdentifier = languageIdentifier || nullMode_1.NULL_LANGUAGE_IDENTIFIER; _this._tokenizationListener = modes_1.TokenizationRegistry.onDidChange(function (e) { if (e.changedLanguages.indexOf(_this._languageIdentifier.language) === -1) { return; } _this._resetTokenizationState(); _this.emitModelTokensChangedEvent({ tokenizationSupportChanged: true, ranges: [{ fromLineNumber: 1, toLineNumber: _this.getLineCount() }] }); if (_this._shouldAutoTokenize()) { _this._warmUpTokens(); } }); _this._revalidateTokensTimeout = -1; _this._languageRegistryListener = languageConfigurationRegistry_1.LanguageConfigurationRegistry.onDidChange(function (e) { if (e.languageIdentifier.id === _this._languageIdentifier.id) { _this._onDidChangeLanguageConfiguration.fire({}); } }); _this._resetTokenizationState(); _this._instanceId = singleLetter(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; 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.onDidChangeContent = function (listener) { return this._eventEmitter.slowEvent(function (e) { return listener(e.contentChangedEvent); }); }; TextModel.prototype.dispose = function () { this._isDisposing = true; this._onWillDispose.fire(); this._tokenizationListener.dispose(); this._languageRegistryListener.dispose(); this._clearTimers(); this._isDisposed = true; // Null out members, such that any use of a disposed model will throw exceptions sooner rather than later _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(); // Cancel tokenization, clear all tokens and begin tokenizing this._resetTokenizationState(); // 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._resetTokenizationState = function () { this._clearTimers(); var tokenizationSupport = (this._isTooLargeForTokenization ? null : modes_1.TokenizationRegistry.get(this._languageIdentifier.language)); this._tokens = new textModelTokens_1.ModelLinesTokens(this._languageIdentifier, tokenizationSupport); this._beginBackgroundTokenization(); }; TextModel.prototype._clearTimers = function () { if (this._revalidateTokensTimeout !== -1) { clearTimeout(this._revalidateTokensTimeout); this._revalidateTokensTimeout = -1; } }; TextModel.prototype.onBeforeAttached = function () { this._attachedEditorCount++; // Warm up tokens for the editor this._warmUpTokens(); }; TextModel.prototype.onBeforeDetached = function () { this._attachedEditorCount--; }; TextModel.prototype._shouldAutoTokenize = function () { return this.isAttachedToEditor(); }; 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, false); 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._setVersionId(this._versionId + 1); }; TextModel.prototype._setVersionId = function (newVersionId) { this._versionId = newVersionId; 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.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); }; /** * @param strict Do NOT allow a position inside a high-low surrogate pair */ TextModel.prototype._isValidPosition = function (lineNumber, column, strict) { 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; } var maxColumn = this.getLineMaxColumn(lineNumber); if (column > maxColumn) { return false; } if (strict) { if (column > 1) { var charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2); if (strings.isHighSurrogate(charCodeBefore)) { return false; } } } return true; }; /** * @param strict Do NOT allow a position inside a high-low surrogate pair */ TextModel.prototype._validatePosition = function (_lineNumber, _column, strict) { 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 (strict) { // 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) { this._assertNotDisposed(); // Avoid object allocation and cover most likely case if (position instanceof position_1.Position) { if (this._isValidPosition(position.lineNumber, position.column, true)) { return position; } } return this._validatePosition(position.lineNumber, position.column, true); }; /** * @param strict Do NOT allow a range to have its boundaries inside a high-low surrogate pair */ TextModel.prototype._isValidRange = function (range, strict) { var startLineNumber = range.startLineNumber; var startColumn = range.startColumn; var endLineNumber = range.endLineNumber; var endColumn = range.endColumn; if (!this._isValidPosition(startLineNumber, startColumn, false)) { return false; } if (!this._isValidPosition(endLineNumber, endColumn, false)) { return false; } if (strict) { 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) { 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, true)) { return _range; } } var start = this._validatePosition(_range.startLineNumber, _range.startColumn, false); var end = this._validatePosition(_range.endLineNumber, _range.endColumn, false); var startLineNumber = start.lineNumber; var startColumn = start.column; var endLineNumber = end.lineNumber; var endColumn = end.column; 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); }; 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._eolCount = function (text) { var eolCount = 0; var firstLineLength = 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 } } else if (chr === 10 /* LineFeed */) { if (eolCount === 0) { firstLineLength = i; } eolCount++; } } if (eolCount === 0) { firstLineLength = text.length; } return [eolCount, firstLineLength]; }; 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 = TextModel._eolCount(change.text), eolCount = _a[0], firstLineLength = _a[1]; try { this._tokens.applyEdits(change.range, eolCount, firstLineLength); } catch (err) { // emergency recovery => reset tokens this._tokens = new textModelTokens_1.ModelLinesTokens(this._tokens.languageIdentifier, this._tokens.tokenizationSupport); } 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 }); } if (this._tokens.hasLinesToTokenize(this._buffer)) { this._beginBackgroundTokenization(); } 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.tokenizeViewport = function (startLineNumber, endLineNumber) { if (!this._tokens.tokenizationSupport) { // nothing to do return; } startLineNumber = Math.max(1, startLineNumber); endLineNumber = Math.min(this.getLineCount(), endLineNumber); if (endLineNumber <= this._tokens.inValidLineStartIndex) { // nothing to do return; } if (startLineNumber <= this._tokens.inValidLineStartIndex) { // tokenization has reached the viewport start... this.forceTokenization(endLineNumber); return; } var nonWhitespaceColumn = this.getLineFirstNonWhitespaceColumn(startLineNumber); var fakeLines = []; var initialState = null; for (var i = startLineNumber - 1; nonWhitespaceColumn > 0 && i >= 1; i--) { var newNonWhitespaceIndex = this.getLineFirstNonWhitespaceColumn(i); if (newNonWhitespaceIndex === 0) { continue; } if (newNonWhitespaceIndex < nonWhitespaceColumn) { initialState = this._tokens._getState(i - 1); if (initialState) { break; } fakeLines.push(this.getLineContent(i)); nonWhitespaceColumn = newNonWhitespaceIndex; } } if (!initialState) { initialState = this._tokens.tokenizationSupport.getInitialState(); } var state = initialState.clone(); for (var i = fakeLines.length - 1; i >= 0; i--) { var r = this._tokens._tokenizeText(this._buffer, fakeLines[i], state); if (r) { state = r.endState.clone(); } else { state = initialState.clone(); } } var eventBuilder = new textModelTokens_1.ModelTokensChangedEventBuilder(); for (var i = startLineNumber; i <= endLineNumber; i++) { var text = this.getLineContent(i); var r = this._tokens._tokenizeText(this._buffer, text, state); if (r) { this._tokens._setTokens(this._tokens.languageIdentifier.id, i - 1, text.length, r.tokens); // We cannot trust these states/tokens to be valid! // (see https://github.com/Microsoft/vscode/issues/67607) this._tokens._setIsInvalid(i - 1, true); this._tokens._setState(i - 1, state); state = r.endState.clone(); eventBuilder.registerChangedTokens(i); } else { state = initialState.clone(); } } var e = eventBuilder.build(); if (e) { this._onDidChangeTokens.fire(e); } }; TextModel.prototype.flushTokens = function () { this._resetTokenizationState(); this.emitModelTokensChangedEvent({ tokenizationSupportChanged: false, ranges: [{ fromLineNumber: 1, toLineNumber: this.getLineCount() }] }); }; TextModel.prototype.forceTokenization = function (lineNumber) { if (lineNumber < 1 || lineNumber > this.getLineCount()) { throw new Error('Illegal value for lineNumber'); } var eventBuilder = new textModelTokens_1.ModelTokensChangedEventBuilder(); this._tokens._updateTokensUntilLine(this._buffer, eventBuilder, lineNumber); var e = eventBuilder.build(); if (e) { this._onDidChangeTokens.fire(e); } }; TextModel.prototype.isCheapToTokenize = function (lineNumber) { if (!this._tokens.isCheapToTokenize(lineNumber)) { return false; } if (lineNumber < this._tokens.inValidLineStartIndex + 1) { return true; } if (this.getLineLength(lineNumber) < CHEAP_TOKENIZATION_LENGTH_LIMIT) { return true; } return false; }; 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._buffer.getLineContent(lineNumber); return this._tokens.getTokens(this._languageIdentifier.id, lineNumber - 1, lineText); }; 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; // Cancel tokenization, clear all tokens and begin tokenizing this._resetTokenizationState(); this.emitModelTokensChangedEvent({ tokenizationSupportChanged: true, ranges: [{ fromLineNumber: 1, toLineNumber: this.getLineCount() }] }); this._onDidChangeLanguage.fire(e); this._onDidChangeLanguageConfiguration.fire({}); }; TextModel.prototype.getLanguageIdAtPosition = function (_lineNumber, _column) { if (!this._tokens.tokenizationSupport) { return this._languageIdentifier.id; } var _a = this.validatePosition({ lineNumber: _lineNumber, column: _column }), lineNumber = _a.lineNumber, column = _a.column; var lineTokens = this._getLineTokens(lineNumber); return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(column - 1)); }; TextModel.prototype._beginBackgroundTokenization = function () { var _this = this; if (this._shouldAutoTokenize() && this._revalidateTokensTimeout === -1) { this._revalidateTokensTimeout = setTimeout(function () { _this._revalidateTokensTimeout = -1; _this._revalidateTokensNow(); }, 0); } }; TextModel.prototype._warmUpTokens = function () { // Warm up first 100 lines (if it takes less than 50ms) var maxLineNumber = Math.min(100, this.getLineCount()); this._revalidateTokensNow(maxLineNumber); if (this._tokens.hasLinesToTokenize(this._buffer)) { this._beginBackgroundTokenization(); } }; TextModel.prototype._revalidateTokensNow = function (toLineNumber) { if (toLineNumber === void 0) { toLineNumber = this._buffer.getLineCount(); } var MAX_ALLOWED_TIME = 20; var eventBuilder = new textModelTokens_1.ModelTokensChangedEventBuilder(); var sw = stopwatch_1.StopWatch.create(false); while (this._tokens.hasLinesToTokenize(this._buffer)) { if (sw.elapsed() > MAX_ALLOWED_TIME) { // Stop if MAX_ALLOWED_TIME is reached break; } var tokenizedLineNumber = this._tokens._tokenizeOneLine(this._buffer, eventBuilder); if (tokenizedLineNumber >= toLineNumber) { break; } } if (this._tokens.hasLinesToTokenize(this._buffer)) { this._beginBackgroundTokenization(); } var e = eventBuilder.build(); if (e) { this._onDidChangeTokens.fire(e); } }; TextModel.prototype.emitModelTokensChangedEvent = function (e) { if (!this._isDisposing) { this._onDidChangeTokens.fire(e); } }; // 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 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(lineTokens.getStartOffset(tokenIndex), position.column - 1 - currentModeBrackets.maxBracketLength); // limit search to not go after `maxBracketLength` var searchEndOffset = Math.min(lineTokens.getEndOffset(tokenIndex), 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.findNextBracketInToken(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); foundBracketText = foundBracketText.toLowerCase(); var r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText]); // check that we can actually match this bracket 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 searchEndOffset = lineTokens.getStartOffset(tokenIndex); tokenIndex--; var prevModeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(tokenIndex)); // check that previous token is not to be ignored if (prevModeBrackets && !supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex))) { // limit search in case previous token is very large, there's no need to go beyond `maxBracketLength` var searchStartOffset = Math.max(lineTokens.getStartOffset(tokenIndex), position.column - 1 - prevModeBrackets.maxBracketLength); var foundBracket = richEditBrackets_1.BracketsUtils.findPrevBracketInToken(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); foundBracketText = foundBracketText.toLowerCase(); var r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText]); // check that we can actually match this bracket 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; 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 searchStopOffset = -1; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStopOffset = position.column - 1; } for (; tokenIndex >= 0; tokenIndex--) { var tokenLanguageId = lineTokens.getLanguageId(tokenIndex); var tokenType = lineTokens.getStandardTokenType(tokenIndex); var tokenStartOffset = lineTokens.getStartOffset(tokenIndex); var tokenEndOffset = lineTokens.getEndOffset(tokenIndex); if (searchStopOffset === -1) { searchStopOffset = tokenEndOffset; } if (tokenLanguageId === languageId && !supports_1.ignoreBracketsInToken(tokenType)) { while (true) { var r = richEditBrackets_1.BracketsUtils.findPrevBracketInToken(reversedBracketRegex, lineNumber, lineText, tokenStartOffset, searchStopOffset); if (!r) { break; } var hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1); hitText = hitText.toLowerCase(); if (hitText === bracket.open) { count++; } else if (hitText === bracket.close) { count--; } if (count === 0) { return r; } searchStopOffset = r.startColumn - 1; } } searchStopOffset = -1; } } 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; for (var lineNumber = position.lineNumber, lineCount = this.getLineCount(); lineNumber <= lineCount; lineNumber++) { var lineTokens = this._getLineTokens(lineNumber); var tokenCount = lineTokens.getCount(); var lineText = this._buffer.getLineContent(lineNumber); var tokenIndex = 0; var searchStartOffset = 0; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; } for (; tokenIndex < tokenCount; tokenIndex++) { var tokenLanguageId = lineTokens.getLanguageId(tokenIndex); var tokenType = lineTokens.getStandardTokenType(tokenIndex); var tokenStartOffset = lineTokens.getStartOffset(tokenIndex); var tokenEndOffset = lineTokens.getEndOffset(tokenIndex); if (searchStartOffset === 0) { searchStartOffset = tokenStartOffset; } if (tokenLanguageId === languageId && !supports_1.ignoreBracketsInToken(tokenType)) { while (true) { var r = richEditBrackets_1.BracketsUtils.findNextBracketInToken(bracketRegex, lineNumber, lineText, searchStartOffset, tokenEndOffset); if (!r) { break; } var hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1); hitText = hitText.toLowerCase(); if (hitText === bracket.open) { count++; } else if (hitText === bracket.close) { count--; } if (count === 0) { return r; } searchStartOffset = r.endColumn - 1; } } searchStartOffset = 0; } } 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 searchStopOffset = -1; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStopOffset = position.column - 1; } for (; tokenIndex >= 0; tokenIndex--) { var tokenLanguageId = lineTokens.getLanguageId(tokenIndex); var tokenType = lineTokens.getStandardTokenType(tokenIndex); var tokenStartOffset = lineTokens.getStartOffset(tokenIndex); var tokenEndOffset = lineTokens.getEndOffset(tokenIndex); if (searchStopOffset === -1) { searchStopOffset = tokenEndOffset; } if (languageId !== tokenLanguageId) { languageId = tokenLanguageId; modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); } if (modeBrackets && !supports_1.ignoreBracketsInToken(tokenType)) { var r = richEditBrackets_1.BracketsUtils.findPrevBracketInToken(modeBrackets.reversedRegex, lineNumber, lineText, tokenStartOffset, searchStopOffset); if (r) { return this._toFoundBracket(modeBrackets, r); } } searchStopOffset = -1; } } return null; }; TextModel.prototype.findNextBracket = function (_position) { var position = this.validatePosition(_position); var languageId = -1; var modeBrackets = null; for (var lineNumber = position.lineNumber, lineCount = this.getLineCount(); lineNumber <= lineCount; lineNumber++) { var lineTokens = this._getLineTokens(lineNumber); var tokenCount = lineTokens.getCount(); var lineText = this._buffer.getLineContent(lineNumber); var tokenIndex = 0; var searchStartOffset = 0; if (lineNumber === position.lineNumber) { tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); searchStartOffset = position.column - 1; } for (; tokenIndex < tokenCount; tokenIndex++) { var tokenLanguageId = lineTokens.getLanguageId(tokenIndex); var tokenType = lineTokens.getStandardTokenType(tokenIndex); var tokenStartOffset = lineTokens.getStartOffset(tokenIndex); var tokenEndOffset = lineTokens.getEndOffset(tokenIndex); if (searchStartOffset === 0) { searchStartOffset = tokenStartOffset; } if (languageId !== tokenLanguageId) { languageId = tokenLanguageId; modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); } if (modeBrackets && !supports_1.ignoreBracketsInToken(tokenType)) { var r = richEditBrackets_1.BracketsUtils.findNextBracketInToken(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, tokenEndOffset); if (r) { return this._toFoundBracket(modeBrackets, r); } } searchStartOffset = 0; } } 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 ModelDecorationOverviewRulerOptions = /** @class */ (function () { function ModelDecorationOverviewRulerOptions(options) { this.color = options.color || strings.empty; this.darkColor = options.darkColor || strings.empty; this.position = (typeof options.position === 'number' ? options.position : model.OverviewRulerLane.Center); this._resolvedColor = null; } 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 strings.empty; } return c.toString(); }; return ModelDecorationOverviewRulerOptions; }()); exports.ModelDecorationOverviewRulerOptions = ModelDecorationOverviewRulerOptions; 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.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[38/*vs/editor/common/controller/cursorCommon*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,5/*vs/base/common/strings*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,29/*vs/editor/common/model/textModel*/,39/*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'); }; var CursorConfiguration = /** @class */ (function () { function CursorConfiguration(languageIdentifier, modelOptions, configuration) { this._languageIdentifier = languageIdentifier; var c = configuration.editor; this.readOnly = c.readOnly; this.tabSize = modelOptions.tabSize; this.indentSize = modelOptions.indentSize; this.insertSpaces = modelOptions.insertSpaces; this.pageSize = Math.max(1, Math.floor(c.layoutInfo.height / c.fontInfo.lineHeight) - 2); this.lineHeight = c.lineHeight; this.useTabStops = c.useTabStops; this.wordSeparators = c.wordSeparators; this.emptySelectionClipboard = c.emptySelectionClipboard; this.copyWithSyntaxHighlighting = c.copyWithSyntaxHighlighting; this.multiCursorMergeOverlapping = c.multiCursorMergeOverlapping; this.autoClosingBrackets = c.autoClosingBrackets; this.autoClosingQuotes = c.autoClosingQuotes; this.autoSurround = c.autoSurround; this.autoIndent = c.autoIndent; this.autoClosingPairsOpen = {}; this.autoClosingPairsClose = {}; 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]; this.autoClosingPairsOpen[pair.open] = pair.close; this.autoClosingPairsClose[pair.close] = pair.open; } } 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.layoutInfo || e.wordSeparators || e.emptySelectionClipboard || e.multiCursorMergeOverlapping || e.autoClosingBrackets || e.autoClosingQuotes || e.autoSurround || e.useTabStops || e.lineHeight || e.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.isLowSurrogate = function (model, lineNumber, charOffset) { var lineContent = model.getLineContent(lineNumber); if (charOffset < 0 || charOffset >= lineContent.length) { return false; } return strings.isLowSurrogate(lineContent.charCodeAt(charOffset)); }; CursorColumns.isHighSurrogate = function (model, lineNumber, charOffset) { var lineContent = model.getLineContent(lineNumber); if (charOffset < 0 || charOffset >= lineContent.length) { return false; } return strings.isHighSurrogate(lineContent.charCodeAt(charOffset)); }; CursorColumns.isInsideSurrogatePair = function (model, lineNumber, column) { return this.isHighSurrogate(model, lineNumber, column - 2); }; CursorColumns.visibleColumnFromColumn = function (lineContent, column, tabSize) { var endOffset = lineContent.length; if (endOffset > column - 1) { endOffset = column - 1; } var result = 0; for (var i = 0; i < endOffset; i++) { var charCode = lineContent.charCodeAt(i); if (charCode === 9 /* Tab */) { result = this.nextRenderTabStop(result, tabSize); } else if (strings.isFullWidthCharacter(charCode)) { 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; for (var i = 0; i < lineLength; i++) { var charCode = lineContent.charCodeAt(i); var afterVisibleColumn = void 0; if (charCode === 9 /* Tab */) { afterVisibleColumn = this.nextRenderTabStop(beforeVisibleColumn, tabSize); } else if (strings.isFullWidthCharacter(charCode)) { afterVisibleColumn = beforeVisibleColumn + 2; } else { afterVisibleColumn = beforeVisibleColumn + 1; } if (afterVisibleColumn >= visibleColumn) { var prevDelta = visibleColumn - beforeVisibleColumn; var afterDelta = afterVisibleColumn - visibleColumn; if (afterDelta < prevDelta) { return i + 2; } else { return i + 1; } } beforeVisibleColumn = afterVisibleColumn; } // 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[195/*vs/editor/common/commands/shiftCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,38/*vs/editor/common/controller/cursorCommon*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,39/*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._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.getRawEnterActionAtPosition(model, 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) { // 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) { // 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[383/*vs/editor/common/controller/cursorColumnSelection*/], __M([0/*require*/,1/*exports*/,38/*vs/editor/common/controller/cursorCommon*/,12/*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)); } return { viewStates: result, reversed: reversed, toLineNumber: toLineNumber, toVisualColumn: toVisibleColumn }; }; ColumnSelection.columnSelect = function (config, model, fromViewSelection, toViewLineNumber, toViewVisualColumn) { var fromViewPosition = new position_1.Position(fromViewSelection.selectionStartLineNumber, fromViewSelection.selectionStartColumn); var fromViewVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, fromViewPosition); return ColumnSelection._columnSelect(config, model, fromViewPosition.lineNumber, fromViewVisibleColumn, toViewLineNumber, toViewVisualColumn); }; ColumnSelection.columnSelectLeft = function (config, model, cursor, toViewLineNumber, toViewVisualColumn) { if (toViewVisualColumn > 1) { toViewVisualColumn--; } return this.columnSelect(config, model, cursor.selection, toViewLineNumber, toViewVisualColumn); }; ColumnSelection.columnSelectRight = function (config, model, cursor, toViewLineNumber, toViewVisualColumn) { var maxVisualViewColumn = 0; var minViewLineNumber = Math.min(cursor.position.lineNumber, toViewLineNumber); var maxViewLineNumber = Math.max(cursor.position.lineNumber, 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); } if (toViewVisualColumn < maxVisualViewColumn) { toViewVisualColumn++; } return this.columnSelect(config, model, cursor.selection, toViewLineNumber, toViewVisualColumn); }; ColumnSelection.columnSelectUp = function (config, model, cursor, isPaged, toViewLineNumber, toViewVisualColumn) { var linesCount = isPaged ? config.pageSize : 1; toViewLineNumber -= linesCount; if (toViewLineNumber < 1) { toViewLineNumber = 1; } return this.columnSelect(config, model, cursor.selection, toViewLineNumber, toViewVisualColumn); }; ColumnSelection.columnSelectDown = function (config, model, cursor, isPaged, toViewLineNumber, toViewVisualColumn) { var linesCount = isPaged ? config.pageSize : 1; toViewLineNumber += linesCount; if (toViewLineNumber > model.getLineCount()) { toViewLineNumber = model.getLineCount(); } return this.columnSelect(config, model, cursor.selection, toViewLineNumber, 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[194/*vs/editor/common/controller/cursorMoveOperations*/], __M([0/*require*/,1/*exports*/,38/*vs/editor/common/controller/cursorCommon*/,12/*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 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.left = function (config, model, lineNumber, column) { if (column > model.getLineMinColumn(lineNumber)) { if (cursorCommon_1.CursorColumns.isLowSurrogate(model, lineNumber, column - 2)) { // character before column is a low surrogate column = column - 2; } else { column = column - 1; } } else if (lineNumber > 1) { lineNumber = lineNumber - 1; column = model.getLineMaxColumn(lineNumber); } return new CursorPosition(lineNumber, 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.right = function (config, model, lineNumber, column) { if (column < model.getLineMaxColumn(lineNumber)) { if (cursorCommon_1.CursorColumns.isHighSurrogate(model, lineNumber, column - 1)) { // character after column is a high surrogate column = column + 2; } else { column = column + 1; } } else if (lineNumber < model.getLineCount()) { lineNumber = lineNumber + 1; column = model.getLineMinColumn(lineNumber); } return new CursorPosition(lineNumber, 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); if (cursorCommon_1.CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) { column = column - 1; } } } else { column = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn); if (cursorCommon_1.CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) { column = column - 1; } } 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); if (cursorCommon_1.CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) { column = column - 1; } } } else { column = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn); if (cursorCommon_1.CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) { column = column - 1; } } 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[193/*vs/editor/common/controller/cursorDeleteOperations*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,77/*vs/editor/common/commands/replaceCommand*/,38/*vs/editor/common/controller/cursorCommon*/,194/*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]; if (!config.autoClosingPairsOpen.hasOwnProperty(character)) { 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 closeCharacter = config.autoClosingPairsOpen[character]; if (afterCharacter !== closeCharacter) { 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[130/*vs/editor/common/controller/cursorTypeOperations*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,5/*vs/base/common/strings*/,77/*vs/editor/common/commands/replaceCommand*/,195/*vs/editor/common/commands/shiftCommand*/,296/*vs/editor/common/commands/surroundSelectionCommand*/,38/*vs/editor/common/controller/cursorCommon*/,83/*vs/editor/common/controller/wordCharacterClassifier*/,3/*vs/editor/common/core/range*/,81/*vs/editor/common/modes/languageConfiguration*/,39/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, errors_1, strings, replaceCommand_1, shiftCommand_1, surroundSelectionCommand_1, cursorCommon_1, wordCharacterClassifier_1, range_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 }); } 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 }); } 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 && text.indexOf('\n') !== text.length - 1) { pasteOnNewLine = false; } if (pasteOnNewLine && selection.startLineNumber !== selection.endLineNumber) { pasteOnNewLine = false; } if (pasteOnNewLine && selection.startColumn === model.getLineMinColumn(selection.startLineNumber) && selection.endColumn === model.getLineMaxColumn(selection.startLineNumber)) { 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.ReplaceCommand(typeSelection, text); } else { commands[i] = new replaceCommand_1.ReplaceCommand(selection, text); } } return new cursorCommon_1.EditOperationResult(0 /* Other */, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: true }); }; TypeOperations._distributePasteToCursors = function (selections, text, pasteOnNewLine, multicursorText) { if (pasteOnNewLine) { return null; } if (selections.length === 1) { return null; } if (multicursorText && multicursorText.length === selections.length) { return multicursorText; } // Remove trailing \n if present if (text.charCodeAt(text.length - 1) === 10 /* LineFeed */) { 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(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 = config.autoIndent ? languageConfigurationRegistry_1.LanguageConfigurationRegistry.getInheritIndentForLine(model, lineNumber, false) : null; 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(model, new range_1.Range(lastLineNumber, maxColumn, lastLineNumber, maxColumn)); if (expectedEnterAction) { indentation = expectedEnterAction.indentation; action = expectedEnterAction.enterAction; if (action) { indentation += action.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 }); } } 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 (!model.isCheapToTokenize(range.getStartPosition().lineNumber)) { 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(model, range); if (r) { var enterAction = r.enterAction; var indentation_2 = r.indentation; if (enterAction.indentAction === languageConfiguration_1.IndentAction.None) { // Nothing special return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation_2 + enterAction.appendText), keepPosition); } else if (enterAction.indentAction === languageConfiguration_1.IndentAction.Indent) { // Indent once return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation_2 + enterAction.appendText), keepPosition); } else if (enterAction.indentAction === languageConfiguration_1.IndentAction.IndentOutdent) { // Ultra special var normalIndent = config.normalizeIndentation(indentation_2); var increasedIndent = config.normalizeIndentation(indentation_2 + enterAction.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 (enterAction.indentAction === languageConfiguration_1.IndentAction.Outdent) { var actualIndentation = TypeOperations.unshiftIndent(config, indentation_2); return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(actualIndentation + enterAction.appendText), keepPosition); } } // no enter rules applied, we should check indentation rules then. if (!config.autoIndent) { // Nothing special var lineText_2 = model.getLineContent(range.startLineNumber); var indentation_3 = strings.getLeadingWhitespace(lineText_2).substring(0, range.startColumn - 1); return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation_3), keepPosition); } var ir = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentForEnter(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); } }, config.autoIndent); var lineText = model.getLineContent(range.startLineNumber); var indentation = strings.getLeadingWhitespace(lineText).substring(0, range.startColumn - 1); 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); } } else { return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation), keepPosition); } }; TypeOperations._isAutoIndentType = function (config, model, selections) { if (!config.autoIndent) { 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(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._isAutoClosingCloseCharType = function (config, model, selections, ch) { var autoCloseConfig = cursorCommon_1.isQuote(ch) ? config.autoClosingQuotes : config.autoClosingBrackets; if (autoCloseConfig === 'never' || !config.autoClosingPairsClose.hasOwnProperty(ch)) { return false; } var isEqualPair = (ch === config.autoClosingPairsClose[ch]); 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; } if (isEqualPair) { var lineTextBeforeCursor = lineText.substr(0, position.column - 1); var chCntBefore = this._countNeedlesInHaystack(lineTextBeforeCursor, ch); if (chCntBefore % 2 === 0) { return false; } } } return true; }; TypeOperations._countNeedlesInHaystack = function (haystack, needle) { var cnt = 0; var lastIndex = -1; while ((lastIndex = haystack.indexOf(needle, lastIndex + 1)) !== -1) { cnt++; } return cnt; }; TypeOperations._runAutoClosingCloseCharType = 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._isBeforeClosingBrace = function (config, ch, characterAfter) { var thisBraceIsSymmetric = (config.autoClosingPairsOpen[ch] === ch); var isBeforeCloseBrace = false; for (var otherCloseBrace in config.autoClosingPairsClose) { var otherBraceIsSymmetric = (config.autoClosingPairsOpen[otherCloseBrace] === otherCloseBrace); if (!thisBraceIsSymmetric && otherBraceIsSymmetric) { continue; } if (characterAfter === otherCloseBrace) { isBeforeCloseBrace = true; break; } } return isBeforeCloseBrace; }; TypeOperations._isAutoClosingOpenCharType = function (config, model, selections, ch) { var chIsQuote = cursorCommon_1.isQuote(ch); var autoCloseConfig = chIsQuote ? config.autoClosingQuotes : config.autoClosingBrackets; if (autoCloseConfig === 'never' || !config.autoClosingPairsOpen.hasOwnProperty(ch)) { return false; } 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 false; } var position = selection.getPosition(); var lineText = model.getLineContent(position.lineNumber); // Do not auto-close ' or " after a word character if ((chIsQuote && position.column > 1) && autoCloseConfig !== 'always') { var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(config.wordSeparators); var characterBeforeCode = lineText.charCodeAt(position.column - 2); var characterBeforeType = wordSeparators.get(characterBeforeCode); if (characterBeforeType === 0 /* Regular */) { return false; } } // Only consider auto closing the pair if a space follows or if another autoclosed pair follows var characterAfter = lineText.charAt(position.column - 1); if (characterAfter) { var isBeforeCloseBrace = TypeOperations._isBeforeClosingBrace(config, ch, characterAfter); if (!isBeforeCloseBrace && !shouldAutoCloseBefore(characterAfter)) { return false; } } if (!model.isCheapToTokenize(position.lineNumber)) { // Do not force tokenization return false; } model.forceTokenization(position.lineNumber); var lineTokens = model.getLineTokens(position.lineNumber); var shouldAutoClosePair = false; try { shouldAutoClosePair = languageConfigurationRegistry_1.LanguageConfigurationRegistry.shouldAutoClosePair(ch, lineTokens, position.column); } catch (e) { errors_1.onUnexpectedError(e); } if (!shouldAutoClosePair) { return false; } } return true; }; TypeOperations._runAutoClosingOpenCharType = 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.autoClosingPairsOpen[ch]; commands[i] = new replaceCommand_1.ReplaceCommandWithOffsetCursorState(selection, ch + closeCharacter, 0, -closeCharacter.length); } 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.appendText) { var command = new replaceCommand_1.ReplaceCommandWithOffsetCursorState(selection, ch + electricAction.appendText, 0, -electricAction.appendText.length); return new cursorCommon_1.EditOperationResult(1 /* Typing */, [command], { shouldPushStackElementBefore: false, shouldPushStackElementAfter: true }); } 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; }; TypeOperations.compositionEndWithInterceptors = function (prevEditOperationType, config, model, selections) { if (config.autoClosingQuotes === 'never') { return null; } var commands = []; for (var i = 0; i < selections.length; i++) { if (!selections[i].isEmpty()) { continue; } var position = selections[i].getPosition(); var lineText = model.getLineContent(position.lineNumber); var ch = lineText.charAt(position.column - 2); if (config.autoClosingPairsClose.hasOwnProperty(ch)) { // first of all, it's a closing tag if (ch === config.autoClosingPairsClose[ch] /** isEqualPair */) { var lineTextBeforeCursor = lineText.substr(0, position.column - 2); var chCntBefore = this._countNeedlesInHaystack(lineTextBeforeCursor, ch); if (chCntBefore % 2 === 1) { continue; // it pairs with the opening tag. } } } // As we are not typing in a new character, so we don't need to run `_runAutoClosingCloseCharType` // Next step, let's try to check if it's an open char. if (config.autoClosingPairsOpen.hasOwnProperty(ch)) { if (cursorCommon_1.isQuote(ch) && position.column > 2) { var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(config.wordSeparators); var characterBeforeCode = lineText.charCodeAt(position.column - 3); var characterBeforeType = wordSeparators.get(characterBeforeCode); if (characterBeforeType === 0 /* Regular */) { continue; } } var characterAfter = lineText.charAt(position.column - 1); if (characterAfter) { var isBeforeCloseBrace = TypeOperations._isBeforeClosingBrace(config, ch, characterAfter); var shouldAutoCloseBefore = cursorCommon_1.isQuote(ch) ? config.shouldAutoCloseBefore.quote : config.shouldAutoCloseBefore.bracket; if (isBeforeCloseBrace) { // In normal auto closing logic, we will auto close if the cursor is even before a closing brace intentionally. // However for composition mode, we do nothing here as users might clear all the characters for composition and we don't want to do a unnecessary auto close. // Related: microsoft/vscode#57250. continue; } if (!shouldAutoCloseBefore(characterAfter)) { continue; } } if (!model.isCheapToTokenize(position.lineNumber)) { // Do not force tokenization continue; } model.forceTokenization(position.lineNumber); var lineTokens = model.getLineTokens(position.lineNumber); var shouldAutoClosePair = false; try { shouldAutoClosePair = languageConfigurationRegistry_1.LanguageConfigurationRegistry.shouldAutoClosePair(ch, lineTokens, position.column - 1); } catch (e) { errors_1.onUnexpectedError(e); } if (shouldAutoClosePair) { var closeCharacter = config.autoClosingPairsOpen[ch]; commands[i] = new replaceCommand_1.ReplaceCommandWithOffsetCursorState(selections[i], closeCharacter, 0, -closeCharacter.length); } } } return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false }); }; TypeOperations.typeWithInterceptors = function (prevEditOperationType, config, model, selections, 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._isAutoClosingCloseCharType(config, model, selections, ch)) { return this._runAutoClosingCloseCharType(prevEditOperationType, config, model, selections, ch); } if (this._isAutoClosingOpenCharType(config, model, selections, ch)) { return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch); } 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; }); /*--------------------------------------------------------------------------------------------- * 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/editor/common/controller/cursorWordOperations*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,38/*vs/editor/common/controller/cursorCommon*/,83/*vs/editor/common/controller/wordCharacterClassifier*/,12/*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); } // 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 (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[187/*vs/editor/common/controller/cursorMoveCommands*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/,38/*vs/editor/common/controller/cursorCommon*/,194/*vs/editor/common/controller/cursorMoveOperations*/,127/*vs/editor/common/controller/cursorWordOperations*/,12/*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 viewSelection = cursor.viewState.selection; var startLineNumber = viewSelection.startLineNumber; var lineCount = context.viewModel.getLineCount(); var endLineNumber = viewSelection.endLineNumber; var endColumn = void 0; if (endLineNumber === lineCount) { endColumn = context.viewModel.getLineMaxColumn(lineCount); } else { endLineNumber++; endColumn = 1; } result[i] = cursorCommon_1.CursorState.fromViewState(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[389/*vs/editor/common/controller/oneCursor*/], __M([0/*require*/,1/*exports*/,38/*vs/editor/common/controller/cursorCommon*/,12/*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[390/*vs/editor/common/controller/cursorCollection*/], __M([0/*require*/,1/*exports*/,38/*vs/editor/common/controller/cursorCommon*/,389/*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[391/*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*/,390/*vs/editor/common/controller/cursorCollection*/,38/*vs/editor/common/controller/cursorCommon*/,193/*vs/editor/common/controller/cursorDeleteOperations*/,130/*vs/editor/common/controller/cursorTypeOperations*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,70/*vs/editor/common/editorCommon*/,73/*vs/editor/common/view/viewEvents*/]), function (require, exports, errors_1, event_1, strings, cursorCollection_1, cursorCommon_1, cursorDeleteOperations_1, cursorTypeOperations_1, range_1, selection_1, editorCommon, viewEvents) { "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 === 6 /* ViewLineMappingChanged */) { return true; } } return false; } var CursorStateChangedEvent = /** @class */ (function () { function CursorStateChangedEvent(selections, source, reason) { this.selections = selections; 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 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._columnSelectData = null; _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(); _super.prototype.dispose.call(this); }; // ------ 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._emitStateChangedIfNecessary(source, reason, oldState); }; Cursor.prototype.setColumnSelectData = function (columnSelectData) { this._columnSelectData = columnSelectData; }; Cursor.prototype.reveal = function (horizontal, target, scrollType) { this._revealRange(target, 0 /* Simple */, horizontal, scrollType); }; Cursor.prototype.revealRange = function (revealHorizontal, viewRange, verticalType, scrollType) { this.emitCursorRevealRange(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(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._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.position; return { toViewLineNumber: primaryPos.lineNumber, toViewVisualColumn: cursorCommon_1.CursorColumns.visibleColumnFromColumn2(this.context.config, this.context.viewModel, primaryPos) }; }; 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._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); 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)); } 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); })) { this._onDidChange.fire(new CursorStateChangedEvent(selections, source || 'keyboard', reason)); } return true; }; Cursor.prototype._revealRange = function (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(viewRange, verticalType, revealHorizontal, scrollType); }; Cursor.prototype.emitCursorRevealRange = function (viewRange, verticalType, revealHorizontal, scrollType) { try { var eventsCollector = this._beginEmit(); eventsCollector.emit(new viewEvents.ViewRevealRangeRequestEvent(viewRange, verticalType, revealHorizontal, scrollType)); } finally { this._endEmit(); } }; // ----------------------------------------------------------------------------------------------------------- // ----- handlers beyond this point Cursor.prototype.trigger = function (source, handlerId, payload) { var H = editorCommon.Handler; if (handlerId === H.CompositionStart) { this._isDoingComposition = true; return; } if (handlerId === H.CompositionEnd) { this._isDoingComposition = false; } if (this._configuration.editor.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(); } if (this._emitStateChangedIfNecessary(source, cursorChangeReason, oldState)) { this._revealRange(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. this._executeEditOperation(cursorTypeOperations_1.TypeOperations.compositionEndWithInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections())); } }; 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 for (var i = 0, len = text.length; i < len; i++) { var charCode = text.charCodeAt(i); var chr = void 0; if (strings.isHighSurrogate(charCode) && i + 1 < len) { chr = text.charAt(i) + text.charAt(i + 1); i++; } else { chr = text.charAt(i); } // Here we must interpret each typed character individually, that's why we create a new context this._executeEditOperation(cursorTypeOperations_1.TypeOperations.typeWithInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), chr)); } } 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) { 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: false, isAutoWhitespaceEdit: command.insertsAutoWhitespace }); }; var hadTrackedEditOperation = false; var addTrackedEditOperation = function (selection, text) { hadTrackedEditOperation = true; addEditOperation(selection, text); }; 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[186/*vs/editor/common/modes/textToHtmlTokenizer*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,94/*vs/editor/common/core/lineTokens*/,61/*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) { 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 += ' '; 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; 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[80/*vs/editor/common/services/resolverService*/], __M([0/*require*/,1/*exports*/,13/*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[115/*vs/editor/common/services/resourceConfiguration*/], __M([0/*require*/,1/*exports*/,13/*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[110/*vs/editor/common/view/minimapCharRenderer*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,298/*vs/editor/common/core/rgba*/,16/*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; var MinimapCharRenderer = /** @class */ (function () { function MinimapCharRenderer(x2CharData, x1CharData) { var x2ExpectedLen = 4 /* x2_CHAR_HEIGHT */ * 2 /* x2_CHAR_WIDTH */ * 95 /* CHAR_COUNT */; if (x2CharData.length !== x2ExpectedLen) { throw new Error('Invalid x2CharData'); } var x1ExpectedLen = 2 /* x1_CHAR_HEIGHT */ * 1 /* x1_CHAR_WIDTH */ * 95 /* CHAR_COUNT */; if (x1CharData.length !== x1ExpectedLen) { throw new Error('Invalid x1CharData'); } this.x2charData = x2CharData; this.x1charData = x1CharData; this.x2charDataLight = MinimapCharRenderer.soften(x2CharData, 12 / 15); this.x1charDataLight = MinimapCharRenderer.soften(x1CharData, 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._getChIndex = function (chCode) { chCode -= 32 /* START_CH_CODE */; if (chCode < 0) { chCode += 95 /* CHAR_COUNT */; } return (chCode % 95 /* CHAR_COUNT */); }; MinimapCharRenderer.prototype.x2RenderChar = function (target, dx, dy, chCode, color, backgroundColor, useLighterFont) { if (dx + 2 /* x2_CHAR_WIDTH */ > target.width || dy + 4 /* x2_CHAR_HEIGHT */ > target.height) { console.warn('bad render request outside image data'); return; } var x2CharData = useLighterFont ? this.x2charDataLight : this.x2charData; var chIndex = MinimapCharRenderer._getChIndex(chCode); var outWidth = 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 = chIndex * 4 /* x2_CHAR_HEIGHT */ * 2 /* x2_CHAR_WIDTH */; var destOffset = dy * outWidth + dx * 4 /* RGBA_CHANNELS_CNT */; { var c = x2CharData[sourceOffset] / 255; dest[destOffset + 0] = backgroundR + deltaR * c; dest[destOffset + 1] = backgroundG + deltaG * c; dest[destOffset + 2] = backgroundB + deltaB * c; } { var c = x2CharData[sourceOffset + 1] / 255; dest[destOffset + 4] = backgroundR + deltaR * c; dest[destOffset + 5] = backgroundG + deltaG * c; dest[destOffset + 6] = backgroundB + deltaB * c; } destOffset += outWidth; { var c = x2CharData[sourceOffset + 2] / 255; dest[destOffset + 0] = backgroundR + deltaR * c; dest[destOffset + 1] = backgroundG + deltaG * c; dest[destOffset + 2] = backgroundB + deltaB * c; } { var c = x2CharData[sourceOffset + 3] / 255; dest[destOffset + 4] = backgroundR + deltaR * c; dest[destOffset + 5] = backgroundG + deltaG * c; dest[destOffset + 6] = backgroundB + deltaB * c; } destOffset += outWidth; { var c = x2CharData[sourceOffset + 4] / 255; dest[destOffset + 0] = backgroundR + deltaR * c; dest[destOffset + 1] = backgroundG + deltaG * c; dest[destOffset + 2] = backgroundB + deltaB * c; } { var c = x2CharData[sourceOffset + 5] / 255; dest[destOffset + 4] = backgroundR + deltaR * c; dest[destOffset + 5] = backgroundG + deltaG * c; dest[destOffset + 6] = backgroundB + deltaB * c; } destOffset += outWidth; { var c = x2CharData[sourceOffset + 6] / 255; dest[destOffset + 0] = backgroundR + deltaR * c; dest[destOffset + 1] = backgroundG + deltaG * c; dest[destOffset + 2] = backgroundB + deltaB * c; } { var c = x2CharData[sourceOffset + 7] / 255; dest[destOffset + 4] = backgroundR + deltaR * c; dest[destOffset + 5] = backgroundG + deltaG * c; dest[destOffset + 6] = backgroundB + deltaB * c; } }; MinimapCharRenderer.prototype.x1RenderChar = function (target, dx, dy, chCode, color, backgroundColor, useLighterFont) { if (dx + 1 /* x1_CHAR_WIDTH */ > target.width || dy + 2 /* x1_CHAR_HEIGHT */ > target.height) { console.warn('bad render request outside image data'); return; } var x1CharData = useLighterFont ? this.x1charDataLight : this.x1charData; var chIndex = MinimapCharRenderer._getChIndex(chCode); var outWidth = 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 = chIndex * 2 /* x1_CHAR_HEIGHT */ * 1 /* x1_CHAR_WIDTH */; var destOffset = dy * outWidth + dx * 4 /* RGBA_CHANNELS_CNT */; { var c = x1CharData[sourceOffset] / 255; dest[destOffset + 0] = backgroundR + deltaR * c; dest[destOffset + 1] = backgroundG + deltaG * c; dest[destOffset + 2] = backgroundB + deltaB * c; } destOffset += outWidth; { var c = x1CharData[sourceOffset + 1] / 255; dest[destOffset + 0] = backgroundR + deltaR * c; dest[destOffset + 1] = backgroundG + deltaG * c; dest[destOffset + 2] = backgroundB + deltaB * c; } }; MinimapCharRenderer.prototype.x2BlockRenderChar = function (target, dx, dy, color, backgroundColor, useLighterFont) { if (dx + 2 /* x2_CHAR_WIDTH */ > target.width || dy + 4 /* x2_CHAR_HEIGHT */ > target.height) { console.warn('bad render request outside image data'); return; } var outWidth = 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 destOffset = dy * outWidth + dx * 4 /* RGBA_CHANNELS_CNT */; { dest[destOffset + 0] = colorR; dest[destOffset + 1] = colorG; dest[destOffset + 2] = colorB; } { dest[destOffset + 4] = colorR; dest[destOffset + 5] = colorG; dest[destOffset + 6] = colorB; } destOffset += outWidth; { dest[destOffset + 0] = colorR; dest[destOffset + 1] = colorG; dest[destOffset + 2] = colorB; } { dest[destOffset + 4] = colorR; dest[destOffset + 5] = colorG; dest[destOffset + 6] = colorB; } destOffset += outWidth; { dest[destOffset + 0] = colorR; dest[destOffset + 1] = colorG; dest[destOffset + 2] = colorB; } { dest[destOffset + 4] = colorR; dest[destOffset + 5] = colorG; dest[destOffset + 6] = colorB; } destOffset += outWidth; { dest[destOffset + 0] = colorR; dest[destOffset + 1] = colorG; dest[destOffset + 2] = colorB; } { dest[destOffset + 4] = colorR; dest[destOffset + 5] = colorG; dest[destOffset + 6] = colorB; } }; MinimapCharRenderer.prototype.x1BlockRenderChar = function (target, dx, dy, color, backgroundColor, useLighterFont) { if (dx + 1 /* x1_CHAR_WIDTH */ > target.width || dy + 2 /* x1_CHAR_HEIGHT */ > target.height) { console.warn('bad render request outside image data'); return; } var outWidth = 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 destOffset = dy * outWidth + dx * 4 /* RGBA_CHANNELS_CNT */; { dest[destOffset + 0] = colorR; dest[destOffset + 1] = colorG; dest[destOffset + 2] = colorB; } destOffset += outWidth; { dest[destOffset + 0] = colorR; dest[destOffset + 1] = colorG; dest[destOffset + 2] = colorB; } }; 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[396/*vs/editor/common/view/runtimeMinimapCharRenderer*/], __M([0/*require*/,1/*exports*/,110/*vs/editor/common/view/minimapCharRenderer*/]), function (require, exports, minimapCharRenderer_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function toUint8ClampedArrat(arr) { var r = new Uint8ClampedArray(arr.length); for (var i = 0, len = arr.length; i < len; i++) { r[i] = arr[i]; } return r; } var minimapCharRenderer = null; function getOrCreateMinimapCharRenderer() { if (!minimapCharRenderer) { var _x1Data = toUint8ClampedArrat(x1Data); x1Data = null; var _x2Data = toUint8ClampedArrat(x2Data); x2Data = null; minimapCharRenderer = new minimapCharRenderer_1.MinimapCharRenderer(_x2Data, _x1Data); } return minimapCharRenderer; } exports.getOrCreateMinimapCharRenderer = getOrCreateMinimapCharRenderer; var x2Data = [ // 0, 0, 0, 0, 0, 0, 0, 0, // ! 39, 14, 39, 14, 14, 5, 29, 10, // " 96, 96, 29, 29, 0, 0, 0, 0, // # 49, 113, 195, 214, 227, 166, 135, 42, // $ 40, 29, 194, 38, 75, 148, 197, 187, // % 145, 0, 160, 61, 75, 143, 2, 183, // & 138, 58, 163, 6, 177, 223, 197, 227, // ' 38, 13, 11, 4, 0, 0, 0, 0, // ( 10, 54, 52, 8, 62, 4, 71, 122, // ) 73, 2, 19, 40, 10, 50, 155, 36, // * 79, 70, 145, 121, 7, 5, 0, 0, // + 2, 1, 36, 12, 204, 166, 16, 5, // , 0, 0, 0, 0, 1, 0, 154, 34, // - 0, 0, 0, 0, 96, 83, 0, 0, // . 0, 0, 0, 0, 0, 0, 46, 34, // / 0, 82, 2, 56, 53, 3, 146, 0, // 0 146, 119, 152, 132, 152, 131, 145, 119, // 1 170, 42, 15, 42, 15, 42, 172, 194, // 2 131, 132, 0, 139, 80, 28, 227, 143, // 3 159, 135, 15, 118, 11, 126, 171, 144, // 4 20, 124, 88, 106, 217, 196, 0, 106, // 5 189, 92, 168, 43, 5, 130, 164, 133, // 6 130, 115, 183, 65, 134, 120, 141, 141, // 7 170, 196, 2, 106, 31, 32, 105, 2, // 8 145, 130, 116, 114, 132, 135, 138, 140, // 9 138, 113, 147, 137, 81, 183, 129, 94, // : 0, 0, 21, 16, 4, 3, 46, 34, // ; 0, 0, 45, 34, 1, 0, 160, 49, // < 0, 0, 43, 143, 203, 23, 1, 76, // = 0, 0, 38, 28, 131, 96, 38, 28, // > 0, 0, 168, 31, 29, 191, 98, 0, // ? 118, 139, 5, 113, 45, 13, 37, 6, // @ 97, 115, 161, 179, 204, 105, 223, 224, // A 83, 52, 111, 100, 184, 186, 120, 132, // B 212, 145, 180, 139, 174, 161, 212, 182, // C 104, 162, 131, 0, 131, 0, 104, 161, // D 219, 120, 110, 116, 110, 116, 219, 120, // E 207, 154, 163, 40, 147, 22, 207, 154, // F 202, 159, 161, 47, 145, 23, 111, 0, // G 139, 154, 144, 30, 144, 135, 139, 187, // H 110, 110, 168, 161, 150, 145, 110, 110, // I 185, 162, 43, 16, 43, 16, 185, 162, // J 73, 129, 0, 110, 0, 110, 191, 87, // K 149, 149, 236, 48, 195, 91, 146, 149, // L 146, 0, 146, 0, 146, 0, 187, 173, // M 200, 201, 222, 215, 172, 147, 95, 95, // N 193, 97, 224, 129, 159, 206, 97, 192, // O 155, 139, 153, 115, 153, 115, 156, 140, // P 189, 158, 123, 136, 190, 64, 111, 0, // Q 155, 139, 153, 115, 153, 114, 156, 241, // R 197, 148, 150, 152, 170, 116, 110, 157, // S 156, 128, 169, 14, 13, 159, 158, 149, // T 212, 189, 43, 16, 43, 16, 43, 16, // U 148, 110, 148, 110, 147, 109, 182, 151, // V 133, 121, 106, 118, 114, 103, 89, 66, // W 94, 94, 211, 188, 205, 207, 139, 168, // X 151, 152, 87, 76, 101, 79, 151, 152, // Y 130, 156, 125, 116, 47, 29, 43, 16, // Z 169, 228, 11, 103, 120, 6, 230, 176, // [ 55, 49, 55, 6, 55, 6, 193, 102, // \ 92, 0, 71, 0, 13, 30, 0, 147, // ] 63, 43, 12, 43, 12, 43, 142, 152, // ^ 71, 53, 61, 61, 0, 0, 0, 0, // _ 0, 0, 0, 0, 0, 0, 158, 146, // ` 25, 2, 0, 0, 0, 0, 0, 0, // a 0, 0, 107, 130, 170, 194, 176, 188, // b 109, 0, 203, 159, 113, 111, 202, 158, // c 0, 0, 135, 135, 114, 0, 136, 135, // d 0, 109, 187, 190, 148, 126, 177, 187, // e 0, 0, 149, 130, 218, 105, 169, 135, // f 37, 113, 146, 113, 49, 13, 49, 13, // g 0, 0, 178, 195, 147, 114, 255, 255, // h 109, 0, 193, 149, 110, 109, 109, 109, // i 12, 15, 125, 41, 33, 41, 144, 188, // j 1, 6, 75, 53, 10, 53, 210, 161, // k 110, 0, 152, 148, 210, 60, 110, 156, // l 213, 5, 63, 5, 63, 5, 45, 111, // m 0, 0, 232, 172, 190, 168, 190, 169, // n 0, 0, 190, 144, 109, 109, 109, 109, // o 0, 0, 168, 140, 148, 111, 168, 140, // p 0, 0, 200, 151, 113, 110, 255, 158, // q 0, 0, 184, 188, 147, 139, 186, 255, // r 0, 0, 122, 130, 111, 0, 109, 0, // s 0, 0, 132, 69, 109, 93, 110, 136, // t 51, 5, 205, 103, 61, 6, 47, 106, // u 0, 0, 110, 109, 110, 122, 155, 179, // v 0, 0, 132, 120, 113, 114, 84, 63, // w 0, 0, 124, 108, 202, 189, 160, 174, // x 0, 0, 144, 142, 79, 57, 159, 146, // y 0, 0, 138, 138, 119, 117, 255, 69, // z 0, 0, 97, 198, 47, 38, 208, 84, // { 23, 112, 41, 14, 157, 7, 121, 192, // | 35, 11, 35, 11, 35, 11, 160, 61, // } 129, 9, 40, 19, 20, 139, 236, 44, // ~ 0, 0, 15, 3, 97, 93, 0, 0, ]; var x1Data = [ // 0, 0, // ! 23, 12, // " 53, 0, // # 130, 127, // $ 58, 149, // % 67, 77, // & 72, 198, // ' 13, 0, // ( 25, 51, // ) 25, 49, // * 94, 2, // + 8, 64, // , 0, 24, // - 0, 21, // . 0, 9, // / 19, 27, // 0 126, 126, // 1 51, 80, // 2 72, 105, // 3 87, 98, // 4 73, 93, // 5 106, 85, // 6 111, 123, // 7 87, 30, // 8 116, 126, // 9 123, 110, // : 4, 16, // ; 9, 28, // < 21, 53, // = 8, 62, // > 23, 52, // ? 73, 21, // @ 132, 183, // A 78, 142, // B 168, 175, // C 70, 70, // D 128, 128, // E 123, 110, // F 125, 43, // G 100, 139, // H 125, 119, // I 78, 78, // J 54, 77, // K 139, 139, // L 33, 87, // M 201, 117, // N 162, 149, // O 130, 130, // P 138, 60, // Q 130, 172, // R 149, 127, // S 95, 98, // T 95, 25, // U 118, 135, // V 110, 85, // W 147, 175, // X 105, 110, // Y 121, 30, // Z 101, 113, // [ 34, 68, // \ 20, 26, // ] 34, 68, // ^ 56, 0, // _ 0, 44, // ` 3, 0, // a 27, 175, // b 80, 133, // c 31, 66, // d 85, 147, // e 32, 150, // f 90, 25, // g 45, 230, // h 77, 101, // i 36, 83, // j 22, 84, // k 71, 118, // l 44, 44, // m 52, 172, // n 38, 101, // o 35, 130, // p 40, 197, // q 43, 197, // r 29, 26, // s 23, 103, // t 67, 44, // u 25, 129, // v 29, 85, // w 27, 177, // x 33, 97, // y 32, 145, // z 33, 77, // { 38, 96, // | 20, 55, // } 36, 95, // ~ 2, 22, ]; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[180/*vs/editor/common/viewModel/splitLinesCollection*/], __M([0/*require*/,1/*exports*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,29/*vs/editor/common/model/textModel*/,73/*vs/editor/common/view/viewEvents*/,158/*vs/editor/common/viewModel/prefixSumComputer*/,69/*vs/editor/common/viewModel/viewModel*/]), function (require, exports, 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 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) { var start = this._lines.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn); var end = this._lines.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn); return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column); }; CoordinatesConverter.prototype.validateViewPosition = function (viewPosition, expectedModelPosition) { return this._lines.validateViewPosition(viewPosition.lineNumber, viewPosition.column, expectedModelPosition); }; CoordinatesConverter.prototype.validateViewRange = function (viewRange, expectedModelRange) { var validViewStart = this._lines.validateViewPosition(viewRange.startLineNumber, viewRange.startColumn, expectedModelRange.getStartPosition()); var validViewEnd = this._lines.validateViewPosition(viewRange.endLineNumber, viewRange.endColumn, expectedModelRange.getEndPosition()); return new range_1.Range(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column); }; // Model -> View conversion and related methods CoordinatesConverter.prototype.convertModelPositionToViewPosition = function (modelPosition) { return this._lines.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column); }; CoordinatesConverter.prototype.convertModelRangeToViewRange = function (modelRange) { var start = this._lines.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn); var end = this._lines.convertModelPositionToViewPosition(modelRange.endLineNumber, modelRange.endColumn); return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column); }; CoordinatesConverter.prototype.modelPositionIsVisible = function (modelPosition) { return this._lines.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column); }; return CoordinatesConverter; }()); exports.CoordinatesConverter = CoordinatesConverter; var SplitLinesCollection = /** @class */ (function () { function SplitLinesCollection(model, linePositionMapperFactory, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent) { this.model = model; this._validModelVersionId = -1; this.tabSize = tabSize; this.wrappingColumn = wrappingColumn; this.columnsForFullWidthChar = columnsForFullWidthChar; this.wrappingIndent = wrappingIndent; this.linePositionMapperFactory = linePositionMapperFactory; this._constructLines(true); } SplitLinesCollection.prototype.dispose = function () { this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, []); }; SplitLinesCollection.prototype.createCoordinatesConverter = function () { return new CoordinatesConverter(this); }; SplitLinesCollection.prototype._ensureValidState = function () { var modelVersion = this.model.getVersionId(); if (modelVersion !== this._validModelVersionId) { // This is pretty bad, it means we lost track of the model... throw new Error("ViewModel is out of sync with Model!"); } if (this.lines.length !== this.model.getLineCount()) { // This is pretty bad, it means we lost track of the model... this._constructLines(false); } }; SplitLinesCollection.prototype._constructLines = function (resetHiddenAreas) { var _this = this; this.lines = []; if (resetHiddenAreas) { this.hiddenAreasIds = []; } var linesContent = this.model.getLinesContent(); var lineCount = linesContent.length; var values = new Uint32Array(lineCount); 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(this.linePositionMapperFactory, linesContent[i], this.tabSize, this.wrappingColumn, this.columnsForFullWidthChar, this.wrappingIndent, !isInHiddenArea); values[i] = line.getViewLineCount(); this.lines[i] = line; } this._validModelVersionId = this.model.getVersionId(); this.prefixSumComputer = new prefixSumComputer_1.PrefixSumComputerWithCache(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(false); return true; }; SplitLinesCollection.prototype.setWrappingSettings = function (wrappingIndent, wrappingColumn, columnsForFullWidthChar) { if (this.wrappingIndent === wrappingIndent && this.wrappingColumn === wrappingColumn && this.columnsForFullWidthChar === columnsForFullWidthChar) { return false; } this.wrappingIndent = wrappingIndent; this.wrappingColumn = wrappingColumn; this.columnsForFullWidthChar = columnsForFullWidthChar; this._constructLines(false); return true; }; SplitLinesCollection.prototype.onModelFlushed = function () { this._constructLines(true); }; 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, text) { 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 = new Uint32Array(text.length); for (var i = 0, len = text.length; i < len; i++) { var line = createSplitLine(this.linePositionMapperFactory, text[i], this.tabSize, this.wrappingColumn, this.columnsForFullWidthChar, this.wrappingIndent, !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, newText) { 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(this.linePositionMapperFactory, newText, this.tabSize, this.wrappingColumn, this.columnsForFullWidthChar, this.wrappingIndent, 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 () { this._ensureValidState(); 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; }; /** * Gives a hint that a lot of requests are about to come in for these line numbers. */ SplitLinesCollection.prototype.warmUpLookupCache = function (viewStartLineNumber, viewEndLineNumber) { this.prefixSumComputer.warmUpCache(viewStartLineNumber - 1, viewEndLineNumber - 1); }; SplitLinesCollection.prototype.getActiveIndentGuide = function (viewLineNumber, minLineNumber, maxLineNumber) { this._ensureValidState(); 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) { this._ensureValidState(); 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) { this._ensureValidState(); 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) { this._ensureValidState(); 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) { this._ensureValidState(); 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) { this._ensureValidState(); 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) { this._ensureValidState(); 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) { this._ensureValidState(); 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) { this._ensureValidState(); 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.convertViewPositionToModelPosition = function (viewLineNumber, viewColumn) { this._ensureValidState(); 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.convertModelPositionToViewPosition = function (_modelLineNumber, _modelColumn) { this._ensureValidState(); 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._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.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, 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.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(positionMapper, isVisible) { this.positionMapper = positionMapper; this.wrappedIndent = this.positionMapper.getWrappedLinesIndent(); this.wrappedIndentLength = this.wrappedIndent.length; this.outputLineCount = this.positionMapper.getOutputLineCount(); this._isVisible = isVisible; } SplitLine.prototype.isVisible = function () { return this._isVisible; }; SplitLine.prototype.setVisible = function (isVisible) { this._isVisible = isVisible; return this; }; SplitLine.prototype.getViewLineCount = function () { if (!this._isVisible) { return 0; } return this.outputLineCount; }; SplitLine.prototype.getInputStartOffsetOfOutputLineIndex = function (outputLineIndex) { return this.positionMapper.getInputOffsetOfOutputPosition(outputLineIndex, 0); }; SplitLine.prototype.getInputEndOffsetOfOutputLineIndex = function (model, modelLineNumber, outputLineIndex) { if (outputLineIndex + 1 === this.outputLineCount) { return model.getLineMaxColumn(modelLineNumber) - 1; } return this.positionMapper.getInputOffsetOfOutputPosition(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 = this.wrappedIndent + 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.wrappedIndent.length + r; } return r; }; SplitLine.prototype.getViewLineMinColumn = function (_model, _modelLineNumber, outputLineIndex) { if (!this._isVisible) { throw new Error('Not supported'); } if (outputLineIndex > 0) { return this.wrappedIndentLength + 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 = this.wrappedIndent + lineContent; } var minColumn = (outputLineIndex > 0 ? this.wrappedIndentLength + 1 : 1); var maxColumn = lineContent.length + 1; var continuesWithWrappedLine = (outputLineIndex + 1 < this.getViewLineCount()); var deltaStartIndex = 0; if (outputLineIndex > 0) { deltaStartIndex = this.wrappedIndentLength; } var lineTokens = model.getLineTokens(modelLineNumber); return new viewModel_1.ViewLineData(lineContent, continuesWithWrappedLine, minColumn, maxColumn, 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.wrappedIndentLength) { adjustedColumn = 0; } else { adjustedColumn -= this.wrappedIndentLength; } } return this.positionMapper.getInputOffsetOfOutputPosition(outputLineIndex, adjustedColumn) + 1; }; SplitLine.prototype.getViewPositionOfModelPosition = function (deltaLineNumber, inputColumn) { if (!this._isVisible) { throw new Error('Not supported'); } var r = this.positionMapper.getOutputPositionOfInputOffset(inputColumn - 1); var outputLineIndex = r.outputLineIndex; var outputColumn = r.outputOffset + 1; if (outputLineIndex > 0) { outputColumn += this.wrappedIndentLength; } // 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 = this.positionMapper.getOutputPositionOfInputOffset(inputColumn - 1); return (deltaLineNumber + r.outputLineIndex); }; return SplitLine; }()); exports.SplitLine = SplitLine; function createSplitLine(linePositionMapperFactory, text, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent, isVisible) { var positionMapper = linePositionMapperFactory.createLineMapping(text, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent); if (positionMapper === null) { // No mapping needed if (isVisible) { return VisibleIdentitySplitLine.INSTANCE; } return InvisibleIdentitySplitLine.INSTANCE; } else { return new SplitLine(positionMapper, 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 (_wrappingIndent, _wrappingColumn, _columnsForFullWidthChar) { return false; }; IdentityLinesCollection.prototype.onModelFlushed = function () { }; IdentityLinesCollection.prototype.onModelLinesDeleted = function (_versionId, fromLineNumber, toLineNumber) { return new viewEvents.ViewLinesDeletedEvent(fromLineNumber, toLineNumber); }; IdentityLinesCollection.prototype.onModelLinesInserted = function (_versionId, fromLineNumber, toLineNumber, _text) { return new viewEvents.ViewLinesInsertedEvent(fromLineNumber, toLineNumber); }; IdentityLinesCollection.prototype.onModelLineChanged = function (_versionId, lineNumber, _newText) { return [false, new viewEvents.ViewLinesChangedEvent(lineNumber, lineNumber), null, null]; }; IdentityLinesCollection.prototype.acceptVersionId = function (_versionId) { }; IdentityLinesCollection.prototype.getViewLineCount = function () { return this.model.getLineCount(); }; IdentityLinesCollection.prototype.warmUpLookupCache = function (_viewStartLineNumber, _viewEndLineNumber) { }; 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, 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[398/*vs/editor/common/viewModel/characterHardWrappingLineMapper*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,76/*vs/editor/common/core/characterClassifier*/,104/*vs/editor/common/core/uint*/,158/*vs/editor/common/viewModel/prefixSumComputer*/,180/*vs/editor/common/viewModel/splitLinesCollection*/]), function (require, exports, strings, characterClassifier_1, uint_1, prefixSumComputer_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, BREAK_OBTRUSIVE) { 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 */); } for (var i = 0; i < BREAK_OBTRUSIVE.length; i++) { _this.set(BREAK_OBTRUSIVE.charCodeAt(i), 3 /* BREAK_OBTRUSIVE */); } return _this; } WrappingCharacterClassifier.prototype.get = function (charCode) { // 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 4 /* BREAK_IDEOGRAPHIC */; } return _super.prototype.get.call(this, charCode); }; return WrappingCharacterClassifier; }(characterClassifier_1.CharacterClassifier)); var CharacterHardWrappingLineMapperFactory = /** @class */ (function () { function CharacterHardWrappingLineMapperFactory(breakBeforeChars, breakAfterChars, breakObtrusiveChars) { this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars, breakObtrusiveChars); } // TODO@Alex -> duplicated in lineCommentCommand CharacterHardWrappingLineMapperFactory.nextVisibleColumn = function (currentVisibleColumn, tabSize, isTab, columnSize) { currentVisibleColumn = +currentVisibleColumn; //@perf tabSize = +tabSize; //@perf columnSize = +columnSize; //@perf if (isTab) { return currentVisibleColumn + (tabSize - (currentVisibleColumn % tabSize)); } return currentVisibleColumn + columnSize; }; CharacterHardWrappingLineMapperFactory.prototype.createLineMapping = function (lineText, tabSize, breakingColumn, columnsForFullWidthChar, hardWrappingIndent) { if (breakingColumn === -1) { return null; } tabSize = +tabSize; //@perf breakingColumn = +breakingColumn; //@perf columnsForFullWidthChar = +columnsForFullWidthChar; //@perf hardWrappingIndent = +hardWrappingIndent; //@perf var wrappedTextIndentVisibleColumn = 0; var wrappedTextIndent = ''; var firstNonWhitespaceIndex = -1; if (hardWrappingIndent !== 0 /* None */) { firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineText); if (firstNonWhitespaceIndex !== -1) { // Track existing indent wrappedTextIndent = lineText.substring(0, firstNonWhitespaceIndex); for (var i = 0; i < firstNonWhitespaceIndex; i++) { wrappedTextIndentVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(wrappedTextIndentVisibleColumn, tabSize, lineText.charCodeAt(i) === 9 /* Tab */, 1); } // Increase indent of continuation lines, if desired var numberOfAdditionalTabs = 0; if (hardWrappingIndent === 2 /* Indent */) { numberOfAdditionalTabs = 1; } else if (hardWrappingIndent === 3 /* DeepIndent */) { numberOfAdditionalTabs = 2; } for (var i = 0; i < numberOfAdditionalTabs; i++) { wrappedTextIndent += '\t'; wrappedTextIndentVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(wrappedTextIndentVisibleColumn, tabSize, true, 1); } // Force sticking to beginning of line if no character would fit except for the indentation if (wrappedTextIndentVisibleColumn + columnsForFullWidthChar > breakingColumn) { wrappedTextIndent = ''; wrappedTextIndentVisibleColumn = 0; } } } var classifier = this.classifier; var lastBreakingOffset = 0; // Last 0-based offset in the lineText at which a break happened var breakingLengths = []; // The length of each broken-up line text var breakingLengthsIndex = 0; // The count of breaks already done var visibleColumn = 0; // Visible column since the beginning of the current line var niceBreakOffset = -1; // Last index of a character that indicates a break should happen before it (more desirable) var niceBreakVisibleColumn = 0; // visible column if a break were to be later introduced before `niceBreakOffset` var obtrusiveBreakOffset = -1; // Last index of a character that indicates a break should happen before it (less desirable) var obtrusiveBreakVisibleColumn = 0; // visible column if a break were to be later introduced before `obtrusiveBreakOffset` var len = lineText.length; for (var i = 0; i < len; i++) { // At this point, there is a certainty that the character before `i` fits on the current line, // but the character at `i` might not fit var charCode = lineText.charCodeAt(i); var charCodeIsTab = (charCode === 9 /* Tab */); var charCodeClass = classifier.get(charCode); if (charCodeClass === 1 /* BREAK_BEFORE */) { // This is a character that indicates that a break should happen before it // Since we are certain the character before `i` fits, there's no extra checking needed, // just mark it as a nice breaking opportunity niceBreakOffset = i; niceBreakVisibleColumn = wrappedTextIndentVisibleColumn; } // CJK breaking : before break if (charCodeClass === 4 /* BREAK_IDEOGRAPHIC */ && i > 0) { var prevCode = lineText.charCodeAt(i - 1); var prevClass = classifier.get(prevCode); if (prevClass !== 1 /* BREAK_BEFORE */) { // Kinsoku Shori: Don't break after a leading character, like an open bracket niceBreakOffset = i; niceBreakVisibleColumn = wrappedTextIndentVisibleColumn; } } var charColumnSize = 1; if (strings.isFullWidthCharacter(charCode)) { charColumnSize = columnsForFullWidthChar; } // Advance visibleColumn with character at `i` visibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(visibleColumn, tabSize, charCodeIsTab, charColumnSize); if (visibleColumn > breakingColumn && i !== 0) { // We need to break at least before character at `i`: // - break before niceBreakLastOffset if it exists (and re-establish a correct visibleColumn by using niceBreakVisibleColumn + charAt(i)) // - otherwise, break before obtrusiveBreakLastOffset if it exists (and re-establish a correct visibleColumn by using obtrusiveBreakVisibleColumn + charAt(i)) // - otherwise, break before i (and re-establish a correct visibleColumn by charAt(i)) var breakBeforeOffset = void 0; var restoreVisibleColumnFrom = void 0; if (niceBreakOffset !== -1 && niceBreakVisibleColumn <= breakingColumn) { // We will break before `niceBreakLastOffset` breakBeforeOffset = niceBreakOffset; restoreVisibleColumnFrom = niceBreakVisibleColumn; } else if (obtrusiveBreakOffset !== -1 && obtrusiveBreakVisibleColumn <= breakingColumn) { // We will break before `obtrusiveBreakLastOffset` breakBeforeOffset = obtrusiveBreakOffset; restoreVisibleColumnFrom = obtrusiveBreakVisibleColumn; } else { // We will break before `i` breakBeforeOffset = i; restoreVisibleColumnFrom = wrappedTextIndentVisibleColumn; } // Break before character at `breakBeforeOffset` breakingLengths[breakingLengthsIndex++] = breakBeforeOffset - lastBreakingOffset; lastBreakingOffset = breakBeforeOffset; // Re-establish visibleColumn by taking character at `i` into account visibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(restoreVisibleColumnFrom, tabSize, charCodeIsTab, charColumnSize); // Reset markers niceBreakOffset = -1; niceBreakVisibleColumn = 0; obtrusiveBreakOffset = -1; obtrusiveBreakVisibleColumn = 0; } // At this point, there is a certainty that the character at `i` fits on the current line if (niceBreakOffset !== -1) { // Advance niceBreakVisibleColumn niceBreakVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(niceBreakVisibleColumn, tabSize, charCodeIsTab, charColumnSize); } if (obtrusiveBreakOffset !== -1) { // Advance obtrusiveBreakVisibleColumn obtrusiveBreakVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(obtrusiveBreakVisibleColumn, tabSize, charCodeIsTab, charColumnSize); } if (charCodeClass === 2 /* BREAK_AFTER */ && (hardWrappingIndent === 0 /* None */ || i >= firstNonWhitespaceIndex)) { // This is a character that indicates that a break should happen after it niceBreakOffset = i + 1; niceBreakVisibleColumn = wrappedTextIndentVisibleColumn; } // CJK breaking : after break if (charCodeClass === 4 /* BREAK_IDEOGRAPHIC */ && i < len - 1) { var nextCode = lineText.charCodeAt(i + 1); var nextClass = classifier.get(nextCode); if (nextClass !== 2 /* BREAK_AFTER */) { // Kinsoku Shori: Don't break before a trailing character, like a period niceBreakOffset = i + 1; niceBreakVisibleColumn = wrappedTextIndentVisibleColumn; } } if (charCodeClass === 3 /* BREAK_OBTRUSIVE */) { // This is an obtrusive character that indicates that a break should happen after it obtrusiveBreakOffset = i + 1; obtrusiveBreakVisibleColumn = wrappedTextIndentVisibleColumn; } } if (breakingLengthsIndex === 0) { return null; } // Add last segment breakingLengths[breakingLengthsIndex++] = len - lastBreakingOffset; return new CharacterHardWrappingLineMapping(new prefixSumComputer_1.PrefixSumComputer(uint_1.toUint32Array(breakingLengths)), wrappedTextIndent); }; return CharacterHardWrappingLineMapperFactory; }()); exports.CharacterHardWrappingLineMapperFactory = CharacterHardWrappingLineMapperFactory; var CharacterHardWrappingLineMapping = /** @class */ (function () { function CharacterHardWrappingLineMapping(prefixSums, wrappedLinesIndent) { this._prefixSums = prefixSums; this._wrappedLinesIndent = wrappedLinesIndent; } CharacterHardWrappingLineMapping.prototype.getOutputLineCount = function () { return this._prefixSums.getCount(); }; CharacterHardWrappingLineMapping.prototype.getWrappedLinesIndent = function () { return this._wrappedLinesIndent; }; CharacterHardWrappingLineMapping.prototype.getInputOffsetOfOutputPosition = function (outputLineIndex, outputOffset) { if (outputLineIndex === 0) { return outputOffset; } else { return this._prefixSums.getAccumulatedValue(outputLineIndex - 1) + outputOffset; } }; CharacterHardWrappingLineMapping.prototype.getOutputPositionOfInputOffset = function (inputOffset) { var r = this._prefixSums.getIndexOf(inputOffset); return new splitLinesCollection_1.OutputPosition(r.index, r.remainder); }; return CharacterHardWrappingLineMapping; }()); exports.CharacterHardWrappingLineMapping = CharacterHardWrappingLineMapping; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[399/*vs/editor/common/viewModel/viewModelImpl*/], __M([0/*require*/,1/*exports*/,28/*vs/base/common/color*/,5/*vs/base/common/strings*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,16/*vs/editor/common/modes*/,186/*vs/editor/common/modes/textToHtmlTokenizer*/,110/*vs/editor/common/view/minimapCharRenderer*/,73/*vs/editor/common/view/viewEvents*/,239/*vs/editor/common/viewLayout/viewLayout*/,398/*vs/editor/common/viewModel/characterHardWrappingLineMapper*/,180/*vs/editor/common/viewModel/splitLinesCollection*/,69/*vs/editor/common/viewModel/viewModel*/,240/*vs/editor/common/viewModel/viewModelDecorations*/,15/*vs/base/common/async*/]), function (require, exports, color_1, strings, position_1, range_1, modes_1, textToHtmlTokenizer_1, minimapCharRenderer_1, viewEvents, viewLayout_1, characterHardWrappingLineMapper_1, splitLinesCollection_1, viewModel_1, viewModelDecorations_1, async_1) { "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, 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 conf = _this.configuration.editor; var hardWrappingLineMapperFactory = new characterHardWrappingLineMapper_1.CharacterHardWrappingLineMapperFactory(conf.wrappingInfo.wordWrapBreakBeforeCharacters, conf.wrappingInfo.wordWrapBreakAfterCharacters, conf.wrappingInfo.wordWrapBreakObtrusiveCharacters); _this.lines = new splitLinesCollection_1.SplitLinesCollection(_this.model, hardWrappingLineMapperFactory, _this.model.getOptions().tabSize, conf.wrappingInfo.wrappingColumn, conf.fontInfo.typicalFullwidthCharacterWidth / conf.fontInfo.typicalHalfwidthCharacterWidth, conf.wrappingInfo.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.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(minimapCharRenderer_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.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 conf = this.configuration.editor; if (this.lines.setWrappingSettings(conf.wrappingInfo.wrappingIndent, conf.wrappingInfo.wrappingColumn, conf.fontInfo.typicalFullwidthCharacterWidth / conf.fontInfo.typicalHalfwidthCharacterWidth)) { 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.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; for (var j = 0, lenJ = changes.length; j < lenJ; j++) { var change = changes[j]; 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 linesInsertedEvent = _this.lines.onModelLinesInserted(versionId, change.fromLineNumber, change.toLineNumber, change.detail); if (linesInsertedEvent !== null) { eventsCollector.emit(linesInsertedEvent); _this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber); } hadOtherModelChange = true; break; } case 2 /* LineChanged */: { var _a = _this.lines.onModelLineChanged(versionId, change.lineNumber, change.detail), lineMappingChanged = _a[0], linesChangedEvent = _a[1], linesInsertedEvent = _a[2], linesDeletedEvent = _a[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.lines.warmUpLookupCache(startLineNumber, endLineNumber); 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); }; 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, this.configuration.editor.readOnly, 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.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 (ranges, emptySelectionClipboard, forceCRLF) { var _this = this; var newLineCharacter = forceCRLF ? '\r\n' : this.model.getEOL(); ranges = ranges.slice(0); ranges.sort(range_1.Range.compareRangesUsingStarts); var nonEmptyRanges = ranges.filter(function (r) { return !r.isEmpty(); }); if (nonEmptyRanges.length === 0) { if (!emptySelectionClipboard) { return ''; } var modelLineNumbers = ranges.map(function (r) { var viewLineStart = new position_1.Position(r.startLineNumber, 1); return _this.coordinatesConverter.convertViewPositionToModelPosition(viewLineStart).lineNumber; }); 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; } var result = []; for (var _i = 0, nonEmptyRanges_1 = nonEmptyRanges; _i < nonEmptyRanges_1.length; _i++) { var nonEmptyRange = nonEmptyRanges_1[_i]; result.push(this.getValueInRange(nonEmptyRange, forceCRLF ? 2 /* CRLF */ : 0 /* TextDefined */)); } return result.length === 1 ? result[0] : result; }; ViewModel.prototype.getHTMLToCopy = function (viewRanges, emptySelectionClipboard) { if (this.model.getLanguageIdentifier().id === 1 /* PlainText */) { return null; } if (viewRanges.length !== 1) { // no multiple selection support at this time return null; } var range = this.coordinatesConverter.convertViewRangeToModelRange(viewRanges[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.editor.fontInfo; var colorMap = this._getColorMap(); return ("
    " + 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); } } 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[400/*vs/editor/contrib/folding/foldingDecorations*/], __M([0/*require*/,1/*exports*/,29/*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; } FoldingDecorationProvider.prototype.getDecorationOption = function (isCollapsed) { if (isCollapsed) { return 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: 'folding collapsed' }); FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, linesDecorationsClassName: 'folding' }); FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, linesDecorationsClassName: 'folding 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[401/*vs/editor/contrib/folding/indentRangeProvider*/], __M([0/*require*/,1/*exports*/,149/*vs/editor/contrib/folding/foldingRanges*/,29/*vs/editor/common/model/textModel*/,39/*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 = []; previousRegions.push({ indent: -1, line: model.getLineCount() + 1, marker: false }); // sentinel, to make sure there's at least one entry for (var line = model.getLineCount(); line > 0; line--) { var lineContent = model.getLineContent(line); var indent = textModel_1.TextModel.computeIndentLevel(lineContent, tabSize); var previous = previousRegions[previousRegions.length - 1]; if (indent === -1) { if (offSide && !previous.marker) { // for offSide languages, empty lines are associated to the next block previous.line = line; } 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].marker) { i--; } if (i > 0) { previousRegions.length = i + 1; previous = previousRegions[i]; // new folding range from pattern, includes the end line result.insertFirst(line, previous.line, indent); previous.marker = false; previous.indent = indent; previous.line = line; continue; } else { // no end marker found, treat line as a regular line } } else { // end pattern match previousRegions.push({ indent: -2, line: line, marker: true }); 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.line - 1; if (endLineNumber - line >= 1) { // needs at east size 1 result.insertFirst(line, endLineNumber, indent); } } if (previous.indent === indent) { previous.line = line; } else { // previous.indent < indent // new region with a bigger indent previousRegions.push({ indent: indent, line: line, marker: false }); } } 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[402/*vs/editor/contrib/linesOperations/moveLinesCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,195/*vs/editor/common/commands/shiftCommand*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,81/*vs/editor/common/modes/languageConfiguration*/,39/*vs/editor/common/modes/languageConfigurationRegistry*/,261/*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._moveEndLineSelectionShrink = false; } MoveLinesCommand.prototype.getEditOperations = function (model, builder) { var modelLineCount = model.getLineCount(); if (this._isMovingDown && this._selection.endLineNumber === modelLineCount) { return; } if (!this._isMovingDown && this._selection.startLineNumber === 1) { 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(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(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(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(model, new range_1.Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn)); if (enter) { var enterPrefix = enter.indentation; var enterAction = enter.enterAction; if (enterAction.indentAction === languageConfiguration_1.IndentAction.None) { enterPrefix = enter.indentation + enterAction.appendText; } else if (enterAction.indentAction === languageConfiguration_1.IndentAction.Indent) { enterPrefix = enter.indentation + enterAction.appendText; } else if (enterAction.indentAction === languageConfiguration_1.IndentAction.IndentOutdent) { enterPrefix = enter.indentation; } else if (enterAction.indentAction === languageConfiguration_1.IndentAction.Outdent) { enterPrefix = indentConverter.unshiftIndent(enter.indentation) + enterAction.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) { 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[403/*vs/editor/contrib/zoneWidget/zoneWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,96/*vs/base/browser/ui/sash/sash*/,28/*vs/base/common/color*/,142/*vs/base/common/idGenerator*/,2/*vs/base/common/lifecycle*/,31/*vs/base/common/objects*/,3/*vs/editor/common/core/range*/,29/*vs/editor/common/model/textModel*/,373/*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.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 = []; // } 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._positionMarkerId = []; this._disposables = []; 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.push(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; lifecycle_1.dispose(this._disposables); 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 = []; }; 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.push(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"; var containerHeight = height - this._decoratingElementsHeight(); this.container.style.height = containerHeight + "px"; var layoutInfo = this.editor.getLayoutInfo(); this._doLayout(containerHeight, this._getWidth(layoutInfo)); 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) ? rangeOrPos : new range_1.Range(rangeOrPos.lineNumber, rangeOrPos.column, rangeOrPos.lineNumber, rangeOrPos.column); 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.getConfiguration().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 = { lineNumber: where.startLineNumber, column: where.startColumn }; 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.getConfiguration().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.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.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(); 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) { // Reveal the line above or below the zone widget, to get the zone widget in the viewport var revealLineNumber = Math.min(model.getLineCount(), Math.max(1, where.endLineNumber + 1)); this.revealLine(revealLineNumber); } }; ZoneWidget.prototype.revealLine = function (lineNumber) { this.editor.revealLine(lineNumber, 0 /* Smooth */); }; ZoneWidget.prototype.setCssClass = function (className, classToReplace) { 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; this._resizeSash = 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.push(this._resizeSash.onDidStart(function (e) { if (_this._viewZone) { data = { startY: e.startY, heightInLines: _this._viewZone.heightInLines, }; } })); this._disposables.push(this._resizeSash.onDidEnd(function () { data = undefined; })); this._disposables.push(this._resizeSash.onDidChange(function (evt) { if (data) { var lineDelta = (evt.currentY - data.startY) / _this.editor.getConfiguration().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[179/*vs/editor/standalone/common/monarch/monarchLexer*/], __M([0/*require*/,1/*exports*/,103/*vs/editor/common/core/token*/,16/*vs/editor/common/modes*/,61/*vs/editor/common/modes/nullMode*/,198/*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 hasOwnProperty = Object.hasOwnProperty; 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 idx in rules) { if (!hasOwnProperty.call(rules, idx)) { continue; } var rule = rules[idx]; 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) { 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 idx in rules) { if (hasOwnProperty.call(rules, idx)) { var rule_1 = rules[idx]; 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; } 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[405/*vs/editor/standalone/browser/colorizer*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,5/*vs/base/common/strings*/,94/*vs/editor/common/core/lineTokens*/,16/*vs/editor/common/modes*/,108/*vs/editor/common/viewLayout/viewLineRenderer*/,69/*vs/editor/common/viewModel/viewModel*/,179/*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, -1, 'none', false, false)); 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, -1, 'none', false, false)); 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, -1, 'none', false, false)); 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[82/*vs/editor/standalone/common/standaloneThemeService*/], __M([0/*require*/,1/*exports*/,13/*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[75/*vs/platform/accessibility/common/accessibility*/], __M([0/*require*/,1/*exports*/,13/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IAccessibilityService = instantiation_1.createDecorator('accessibilityService'); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[176/*vs/platform/clipboard/common/clipboardService*/], __M([0/*require*/,1/*exports*/,13/*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. *--------------------------------------------------------------------------------------------*/ define(__m[27/*vs/platform/commands/common/commands*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,13/*vs/platform/instantiation/common/instantiation*/,4/*vs/base/common/event*/,84/*vs/base/common/linkedList*/]), function (require, exports, lifecycle_1, types_1, instantiation_1, event_1, linkedList_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, [accessor].concat(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 && 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, [newId].concat(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 _this = this; var result = Object.create(null); this._commands.forEach(function (value, key) { result[key] = _this.getCommand(key); }); 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. *--------------------------------------------------------------------------------------------*/ var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; define(__m[410/*vs/editor/browser/services/openerService*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,183/*vs/base/common/marshalling*/,53/*vs/base/common/network*/,54/*vs/base/common/resources*/,32/*vs/editor/browser/services/codeEditorService*/,27/*vs/platform/commands/common/commands*/,5/*vs/base/common/strings*/,84/*vs/base/common/linkedList*/]), function (require, exports, dom, marshalling_1, network_1, resources, codeEditorService_1, commands_1, strings_1, linkedList_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var OpenerService = /** @class */ (function () { function OpenerService(_editorService, _commandService) { this._editorService = _editorService; this._commandService = _commandService; this._opener = new linkedList_1.LinkedList(); // } OpenerService.prototype.open = function (resource, options) { return __awaiter(this, void 0, void 0, function () { var _i, _a, opener_1, handled; return __generator(this, function (_b) { switch (_b.label) { case 0: // no scheme ?!? if (!resource.scheme) { return [2 /*return*/, Promise.resolve(false)]; } _i = 0, _a = this._opener.toArray(); _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/, 4]; opener_1 = _a[_i]; return [4 /*yield*/, opener_1.open(resource, options)]; case 2: handled = _b.sent(); if (handled) { return [2 /*return*/, true]; } _b.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: // use default openers return [2 /*return*/, this._doOpen(resource, options)]; } }); }); }; OpenerService.prototype._doOpen = function (resource, options) { var _a; var scheme = resource.scheme, path = resource.path, query = resource.query, fragment = resource.fragment; if (strings_1.equalsIgnoreCase(scheme, network_1.Schemas.http) || strings_1.equalsIgnoreCase(scheme, network_1.Schemas.https) || strings_1.equalsIgnoreCase(scheme, network_1.Schemas.mailto)) { // open http or default mail application dom.windowOpenNoOpener(encodeURI(resource.toString(true))); return Promise.resolve(true); } else if (strings_1.equalsIgnoreCase(scheme, network_1.Schemas.command)) { // run command or bail out if command isn't known if (!commands_1.CommandsRegistry.getCommand(path)) { return Promise.reject("command '" + path + "' NOT known"); } // execute as command var args = []; try { args = marshalling_1.parse(query); if (!Array.isArray(args)) { args = [args]; } } catch (e) { // } return (_a = this._commandService).executeCommand.apply(_a, [path].concat(args)).then(function () { return true; }); } else { var selection = undefined; var match = /^L?(\d+)(?:,(\d+))?/.exec(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 resource = resource.with({ fragment: '' }); } if (resource.scheme === network_1.Schemas.file) { resource = resources.normalizePath(resource); // workaround for non-normalized paths (https://github.com/Microsoft/vscode/issues/12954) } return this._editorService.openCodeEditor({ resource: resource, options: { selection: selection, } }, this._editorService.getFocusedCodeEditor(), options && options.openToSide).then(function () { return true; }); } }; 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[411/*vs/editor/contrib/links/getLinks*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,16/*vs/editor/common/modes*/,42/*vs/editor/common/services/modelService*/,27/*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"; var _this = this; 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 }; }; 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 }); Link.prototype.resolve = function (token) { var _this = this; if (this._link.url) { try { if (typeof this._link.url === 'string') { return Promise.resolve(uri_1.URI.parse(this._link.url)); } else { return Promise.resolve(this._link.url); } } catch (e) { return Promise.reject(new Error('invalid')); } } if (typeof this._provider.resolveLink === 'function') { 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 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 () { return new LinksList(arrays_1.coalesce(lists)); }); } 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(_this, 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[18/*vs/platform/contextkey/common/contextkey*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,13/*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 new ContextKeyDefinedExpr(key); }; ContextKeyExpr.equals = function (key, value) { return new ContextKeyEqualsExpr(key, value); }; ContextKeyExpr.regex = function (key, value) { return new ContextKeyRegexExpr(key, value); }; ContextKeyExpr.not = function (key) { return new ContextKeyNotExpr(key); }; ContextKeyExpr.and = function () { var expr = []; for (var _i = 0; _i < arguments.length; _i++) { expr[_i] = arguments[_i]; } return new ContextKeyAndExpr(expr); }; ContextKeyExpr.deserialize = function (serialized, strict) { var _this = this; if (strict === void 0) { strict = false; } if (!serialized) { return undefined; } var pieces = serialized.split('&&'); var result = new ContextKeyAndExpr(pieces.map(function (p) { return _this._deserializeOne(p, strict); })); return result.normalize(); }; ContextKeyExpr._deserializeOne = function (serializedOne, strict) { serializedOne = serializedOne.trim(); if (serializedOne.indexOf('!=') >= 0) { var pieces = serializedOne.split('!='); return new ContextKeyNotEqualsExpr(pieces[0].trim(), this._deserializeValue(pieces[1], strict)); } if (serializedOne.indexOf('==') >= 0) { var pieces = serializedOne.split('=='); return new ContextKeyEqualsExpr(pieces[0].trim(), this._deserializeValue(pieces[1], strict)); } if (serializedOne.indexOf('=~') >= 0) { var pieces = serializedOne.split('=~'); return new ContextKeyRegexExpr(pieces[0].trim(), this._deserializeRegexValue(pieces[1], strict)); } if (/^\!\s*/.test(serializedOne)) { return new ContextKeyNotExpr(serializedOne.substr(1).trim()); } return new ContextKeyDefinedExpr(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); default: throw new Error('Unknown ContextKeyExpr!'); } } var ContextKeyDefinedExpr = /** @class */ (function () { function ContextKeyDefinedExpr(key) { this.key = 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.normalize = function () { return this; }; ContextKeyDefinedExpr.prototype.keys = function () { return [this.key]; }; return ContextKeyDefinedExpr; }()); exports.ContextKeyDefinedExpr = ContextKeyDefinedExpr; var ContextKeyEqualsExpr = /** @class */ (function () { function ContextKeyEqualsExpr(key, value) { this.key = key; this.value = 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) { /* tslint:disable:triple-equals */ // Intentional == return (context.getValue(this.key) == this.value); /* tslint:enable:triple-equals */ }; ContextKeyEqualsExpr.prototype.normalize = function () { if (typeof this.value === 'boolean') { if (this.value) { return new ContextKeyDefinedExpr(this.key); } return new ContextKeyNotExpr(this.key); } return this; }; ContextKeyEqualsExpr.prototype.keys = function () { return [this.key]; }; return ContextKeyEqualsExpr; }()); exports.ContextKeyEqualsExpr = ContextKeyEqualsExpr; var ContextKeyNotEqualsExpr = /** @class */ (function () { function ContextKeyNotEqualsExpr(key, value) { this.key = key; this.value = 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) { /* tslint:disable:triple-equals */ // Intentional != return (context.getValue(this.key) != this.value); /* tslint:enable:triple-equals */ }; ContextKeyNotEqualsExpr.prototype.normalize = function () { if (typeof this.value === 'boolean') { if (this.value) { return new ContextKeyNotExpr(this.key); } return new ContextKeyDefinedExpr(this.key); } return this; }; ContextKeyNotEqualsExpr.prototype.keys = function () { return [this.key]; }; return ContextKeyNotEqualsExpr; }()); exports.ContextKeyNotEqualsExpr = ContextKeyNotEqualsExpr; var ContextKeyNotExpr = /** @class */ (function () { function ContextKeyNotExpr(key) { this.key = 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.normalize = function () { return this; }; ContextKeyNotExpr.prototype.keys = function () { return [this.key]; }; return ContextKeyNotExpr; }()); exports.ContextKeyNotExpr = ContextKeyNotExpr; var ContextKeyRegexExpr = /** @class */ (function () { function ContextKeyRegexExpr(key, regexp) { this.key = key; this.regexp = 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.normalize = function () { return this; }; ContextKeyRegexExpr.prototype.keys = function () { return [this.key]; }; return ContextKeyRegexExpr; }()); exports.ContextKeyRegexExpr = ContextKeyRegexExpr; var ContextKeyAndExpr = /** @class */ (function () { function ContextKeyAndExpr(expr) { this.expr = ContextKeyAndExpr._normalizeArr(expr); } ContextKeyAndExpr.prototype.getType = function () { return 5 /* And */; }; 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; } e = e.normalize(); if (!e) { continue; } if (e instanceof ContextKeyAndExpr) { expr = expr.concat(e.expr); continue; } expr.push(e); } expr.sort(cmp); } return expr; }; ContextKeyAndExpr.prototype.normalize = function () { if (this.expr.length === 0) { return undefined; } if (this.expr.length === 1) { return this.expr[0]; } return this; }; 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; }; return ContextKeyAndExpr; }()); exports.ContextKeyAndExpr = ContextKeyAndExpr; 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[21/*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) { /** * 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. *--------------------------------------------------------------------------------------------*/ define(__m[414/*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._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[415/*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 () { function WordContextKey(_editor, contextKeyService) { var _this = this; this._editor = _editor; this._ckAtEnd = WordContextKey.AtEnd.bindTo(contextKeyService); this._confListener = this._editor.onDidChangeConfiguration(function (e) { return e.contribInfo && _this._update(); }); this._update(); } WordContextKey.prototype.dispose = function () { lifecycle_1.dispose(this._confListener, this._selectionListener); this._ckAtEnd.reset(); }; WordContextKey.prototype._update = function () { var _this = this; // only update this when tab completions are enabled var enabled = this._editor.getConfiguration().contribInfo.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; }()); 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[58/*vs/platform/actions/common/actions*/], __M([0/*require*/,1/*exports*/,49/*vs/base/common/actions*/,13/*vs/platform/instantiation/common/instantiation*/,18/*vs/platform/contextkey/common/contextkey*/,27/*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 = Object.create(null); this._menuItems = Object.create(null); this._onDidChangeMenu = new event_1.Emitter(); this.onDidChangeMenu = this._onDidChangeMenu.event; } class_1.prototype.addCommand = function (command) { var _this = this; this._commands[command.id] = command; this._onDidChangeMenu.fire(0 /* CommandPalette */); return { dispose: function () { if (delete _this._commands[command.id]) { _this._onDidChangeMenu.fire(0 /* CommandPalette */); } } }; }; class_1.prototype.getCommand = function (id) { return this._commands[id]; }; class_1.prototype.getCommands = function () { var result = Object.create(null); for (var key in this._commands) { result[key] = this.getCommand(key); } return result; }; class_1.prototype.appendMenuItem = function (id, item) { var _this = this; var array = this._menuItems[id]; if (!array) { this._menuItems[id] = array = [item]; } 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[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); } } for (var id in this._commands) { if (!set.has(id)) { result.push({ command: this._commands[id] }); } } }; 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, [this.id].concat(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.run = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var runArgs = []; if (this._options.arg) { runArgs = runArgs.concat([this._options.arg]); } if (this._options.shouldForwardArgs) { runArgs = runArgs.concat(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; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[417/*vs/platform/actions/common/menuService*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,58/*vs/platform/actions/common/actions*/,27/*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._disposables = []; this._build(); // rebuild this menu whenever the menu registry reports an // event for this MenuId event_1.Event.debounce(event_1.Event.filter(actions_1.MenuRegistry.onDidChangeMenu, function (menuId) { return menuId === _this._id; }), function () { }, 50)(this._build, this, this._disposables); // when context keys change we need to check if the menu also // has changed 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, this._disposables); } Menu.prototype._build = function () { // reset this._menuGroups = []; this._contextKeys = new Set(); 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.dispose = function () { lifecycle_1.dispose(this._disposables); this._onDidChange.dispose(); }; 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 var aTitle = typeof a.command.title === 'string' ? a.command.title : a.command.title.value; var bTitle = typeof b.command.title === 'string' ? b.command.title : b.command.title.value; return aTitle.localeCompare(bTitle); }; 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[59/*vs/platform/contextview/browser/contextView*/], __M([0/*require*/,1/*exports*/,13/*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[419/*vs/platform/dialogs/common/dialogs*/], __M([0/*require*/,1/*exports*/,13/*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[91/*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. *--------------------------------------------------------------------------------------------*/ define(__m[421/*vs/platform/instantiation/common/instantiationService*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,367/*vs/platform/instantiation/common/graph*/,219/*vs/platform/instantiation/common/descriptors*/,13/*vs/platform/instantiation/common/instantiation*/,91/*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 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, [accessor].concat(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, [void 0].concat(args.concat(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(); }); function throwCycleError() { var err = new Error('[createInstance] cyclic dependency between services'); err.message = graph.toString(); throw err; } var count = 0; var stack = [{ id: id, desc: desc, _trace: _trace }]; while (stack.length) { var item = stack.pop(); graph.lookupOrInsertNode(item); // TODO@joh use the graph to find a cycle // a weak heuristic for cycle checks if (count++ > 100) { throwCycleError(); } // check all dependencies for existence and if they need to be created first var dependencies = instantiation_1._util.getServiceDependencies(item.desc.ctor); for (var _i = 0, dependencies_1 = dependencies; _i < dependencies_1.length; _i++) { var dependency = dependencies_1[_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()) { throwCycleError(); } break; } for (var _a = 0, roots_1 = roots; _a < roots_1.length; _a++) { var data = roots_1[_a].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'); } }; 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, prop) { return idle_1.getValue()[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[422/*vs/platform/keybinding/common/abstractKeybindingService*/], __M([0/*require*/,1/*exports*/,358/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/,15/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/]), function (require, exports, nls, async_1, event_1, lifecycle_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var AbstractKeybindingService = /** @class */ (function (_super) { __extends(AbstractKeybindingService, _super); function AbstractKeybindingService(contextKeyService, commandService, telemetryService, notificationService, statusService) { var _this = _super.call(this) || this; _this._contextKeyService = contextKeyService; _this._commandService = commandService; _this._telemetryService = telemetryService; _this._statusService = statusService; _this._notificationService = notificationService; _this._currentChord = null; _this._currentChordChecker = new async_1.IntervalTimer(); _this._currentChordStatusMessage = null; _this._onDidUpdateKeybindings = _this._register(new event_1.Emitter()); return _this; } AbstractKeybindingService.prototype.dispose = function () { _super.prototype.dispose.call(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.lookupKeybinding = function (commandId) { var result = this._getResolver().lookupPrimaryKeybinding(commandId); if (!result) { return undefined; } return types_1.withNullAsUndefined(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 }; if (this._statusService) { this._currentChordStatusMessage = this._statusService.setStatusMessage(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._statusService && this._currentChord) { if (!resolveResult || !resolveResult.commandId) { this._statusService.setStatusMessage(nls.localize(1, null, this._currentChord.label, keypressLabel), 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); }); } /* __GDPR__ "workbenchActionExecuted" : { "id" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "from": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this._telemetryService.publicLog('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[423/*vs/platform/keybinding/common/baseResolvedKeybinding*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,175/*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[37/*vs/platform/keybinding/common/keybinding*/], __M([0/*require*/,1/*exports*/,13/*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[167/*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`. * **Precondition**: Assumes `a` and `b` are normalized! */ KeybindingResolver.whenIsEntirelyIncluded = function (a, b) { if (!b) { return true; } if (!a) { return false; } var aExpressions = ((a instanceof contextkey_1.ContextKeyAndExpr) ? a.expr : [a]); var bExpressions = ((b instanceof contextkey_1.ContextKeyAndExpr) ? b.expr : [b]); var aIndex = 0; for (var _i = 0, bExpressions_1 = bExpressions; _i < bExpressions_1.length; _i++) { var bExpr = bExpressions_1[_i]; var bExprMatched = false; while (!bExprMatched && aIndex < aExpressions.length) { var aExpr = aExpressions[aIndex]; if (aExpr.equals(bExpr)) { bExprMatched = true; } aIndex++; } if (!bExprMatched) { return false; } } return true; }; 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[426/*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[427/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/], __M([0/*require*/,1/*exports*/,36/*vs/base/common/keyCodes*/,423/*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[125/*vs/platform/label/common/label*/], __M([0/*require*/,1/*exports*/,13/*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[163/*vs/platform/layout/browser/layoutService*/], __M([0/*require*/,1/*exports*/,13/*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[430/*vs/platform/contextview/browser/contextViewService*/], __M([0/*require*/,1/*exports*/,489/*vs/base/browser/ui/contextview/contextview*/,2/*vs/base/common/lifecycle*/,163/*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[140/*vs/platform/log/common/log*/], __M([0/*require*/,1/*exports*/,13/*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 NullLogService = /** @class */ (function () { function NullLogService() { } 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[161/*vs/editor/common/services/editorWorkerServiceImpl*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,200/*vs/base/common/worker/simpleWorker*/,504/*vs/base/worker/defaultWorkerFactory*/,16/*vs/editor/common/modes*/,39/*vs/editor/common/modes/languageConfigurationRegistry*/,227/*vs/editor/common/services/editorSimpleWorker*/,42/*vs/editor/common/services/modelService*/,115/*vs/editor/common/services/resourceConfiguration*/,5/*vs/base/common/strings*/,19/*vs/base/common/arrays*/,140/*vs/platform/log/common/log*/,122/*vs/base/common/stopwatch*/]), function (require, exports, async_1, lifecycle_1, simpleWorker_1, defaultWorkerFactory_1, modes, languageConfigurationRegistry_1, editorSimpleWorker_1, modelService_1, resourceConfiguration_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) { return this._workerManager.withWorker().then(function (client) { return client.computeDiff(original, modified, ignoreTrimWhitespace); }); }; 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, resourceConfiguration_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._workerManager = workerManager; this._configurationService = configurationService; this._modelService = modelService; } WordBasedCompletionItemProvider.prototype.provideCompletionItems = function (model, position) { var wordBasedSuggestions = this._configurationService.getValue(model.uri, position, 'editor').wordBasedSuggestions; if (!wordBasedSuggestions) { return undefined; } if (!canSyncModel(this._modelService, model.uri)) { return undefined; // File too large } return this._workerManager.withWorker().then(function (client) { return client.textualSuggest(model.uri, position); }); }; 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; 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, '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.esureSyncedResources = 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 = []; toDispose.push(model.onDidChangeContent(function (e) { _this._proxy.acceptModelChanged(modelUrl.toString(), e); })); toDispose.push(model.onWillDispose(function () { _this._stopModelSync(modelUrl); })); toDispose.push(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 EditorWorkerClient = /** @class */ (function (_super) { __extends(EditorWorkerClient, _super); function EditorWorkerClient(modelService, label) { var _this = _super.call(this) || this; _this._modelService = modelService; _this._workerFactory = new defaultWorkerFactory_1.DefaultWorkerFactory(label); _this._worker = null; _this._modelManager = null; return _this; } EditorWorkerClient.prototype._getOrCreateWorker = function () { if (!this._worker) { try { this._worker = this._register(new simpleWorker_1.SimpleWorkerClient(this._workerFactory, 'vs/editor/common/services/editorSimpleWorker')); } catch (err) { simpleWorker_1.logOnceWebWorkerWarning(err); this._worker = new SynchronousWorkerClient(new editorSimpleWorker_1.EditorSimpleWorkerImpl(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.EditorSimpleWorkerImpl(null)); return _this._getOrCreateWorker().getProxyObject(); }); }; EditorWorkerClient.prototype._getOrCreateModelManager = function (proxy) { if (!this._modelManager) { this._modelManager = this._register(new EditorModelManager(proxy, this._modelService, false)); } return this._modelManager; }; EditorWorkerClient.prototype._withSyncedResources = function (resources) { var _this = this; return this._getProxy().then(function (proxy) { _this._getOrCreateModelManager(proxy).esureSyncedResources(resources); return proxy; }); }; EditorWorkerClient.prototype.computeDiff = function (original, modified, ignoreTrimWhitespace) { return this._withSyncedResources([original, modified]).then(function (proxy) { return proxy.computeDiff(original.toString(), modified.toString(), ignoreTrimWhitespace); }); }; 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[433/*vs/editor/common/services/webWorker*/], __M([0/*require*/,1/*exports*/,161/*vs/editor/common/services/editorWorkerServiceImpl*/]), function (require, exports, editorWorkerServiceImpl_1) { "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.label) || this; _this._foreignModuleId = opts.moduleId; _this._foreignModuleCreateData = opts.createData || null; _this._foreignProxy = null; return _this; } MonacoWebWorkerImpl.prototype._getForeignProxy = function () { var _this = this; if (!this._foreignProxy) { this._foreignProxy = this._getProxy().then(function (proxy) { return proxy.loadForeignModule(_this._foreignModuleId, _this._foreignModuleCreateData).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[66/*vs/platform/markers/common/markers*/], __M([0/*require*/,1/*exports*/,13/*vs/platform/instantiation/common/instantiation*/,360/*vs/nls!vs/platform/markers/common/markers*/,123/*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; })(MarkerSeverity = exports.MarkerSeverity || (exports.MarkerSeverity = {})); var IMarkerData; (function (IMarkerData) { var emptyString = ''; function makeKey(markerData) { var result = [emptyString]; if (markerData.source) { result.push(markerData.source.replace('¦', '\¦')); } else { result.push(emptyString); } if (markerData.code) { result.push(markerData.code.replace('¦', '\¦')); } else { result.push(emptyString); } if (markerData.severity !== undefined && markerData.severity !== null) { result.push(MarkerSeverity.toString(markerData.severity)); } else { result.push(emptyString); } if (markerData.message) { 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.makeKey = makeKey; })(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[435/*vs/platform/markers/common/markerService*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,53/*vs/base/common/network*/,20/*vs/base/common/types*/,4/*vs/base/common/event*/,66/*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*/,123/*vs/base/common/severity*/,13/*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[56/*vs/platform/opener/common/opener*/], __M([0/*require*/,1/*exports*/,13/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IOpenerService = instantiation_1.createDecorator('openerService'); exports.NullOpenerService = Object.freeze({ _serviceBrand: undefined, registerOpener: function () { return { dispose: function () { } }; }, open: function () { return Promise.resolve(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[99/*vs/editor/contrib/markdown/markdownRenderer*/], __M([0/*require*/,1/*exports*/,119/*vs/base/browser/htmlContentRenderer*/,56/*vs/platform/opener/common/opener*/,67/*vs/editor/common/services/modeService*/,25/*vs/base/common/uri*/,10/*vs/base/common/errors*/,186/*vs/editor/common/modes/textToHtmlTokenizer*/,13/*vs/platform/instantiation/common/instantiation*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/editor/common/modes*/]), function (require, exports, htmlContentRenderer_1, opener_1, modeService_1, uri_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 () { function MarkdownRenderer(_editor, _modeService, _openerService) { if (_openerService === void 0) { _openerService = opener_1.NullOpenerService; } this._editor = _editor; this._modeService = _modeService; this._openerService = _openerService; this._onDidRenderCodeBlock = new event_1.Emitter(); this.onDidRenderCodeBlock = this._onDidRenderCodeBlock.event; } 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) { var uri; try { uri = uri_1.URI.parse(content); } catch (_a) { // ignore } if (uri && _this._openerService) { _this._openerService.open(uri).catch(errors_1.onUnexpectedError); } }, disposeables: disposeables } }; }; MarkdownRenderer.prototype.render = function (markdown) { var disposeables = []; var element; if (!markdown) { element = document.createElement('span'); } else { element = htmlContentRenderer_1.renderMarkdown(markdown, this.getOptions(disposeables)); } return { element: element, dispose: function () { return lifecycle_1.dispose(disposeables); } }; }; MarkdownRenderer = __decorate([ __param(1, modeService_1.IModeService), __param(2, instantiation_1.optional(opener_1.IOpenerService)) ], MarkdownRenderer); return MarkdownRenderer; }()); exports.MarkdownRenderer = MarkdownRenderer; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[439/*vs/editor/contrib/hover/modesGlyphHover*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,87/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,203/*vs/editor/contrib/hover/hoverOperation*/,202/*vs/editor/contrib/hover/hoverWidgets*/,99/*vs/editor/contrib/markdown/markdownRenderer*/,56/*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; } 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._lastLineNumber = -1; _this._markdownRenderer = 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._renderDisposeables = lifecycle_1.dispose(this._renderDisposeables); 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) { var _this = this; lifecycle_1.dispose(this._renderDisposeables); this._renderDisposeables = []; var fragment = document.createDocumentFragment(); messages.forEach(function (msg) { var renderedContents = _this._markdownRenderer.render(msg.value); _this._renderDisposeables.push(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[92/*vs/platform/progress/common/progress*/], __M([0/*require*/,1/*exports*/,13/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IProgressService = instantiation_1.createDecorator('progressService'); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[40/*vs/platform/registry/common/platform*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/,157/*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 = {}; } RegistryImpl.prototype.add = function (id, data) { Assert.ok(Types.isString(id)); Assert.ok(Types.isObject(data)); Assert.ok(!this.data.hasOwnProperty(id), 'There is already an extension with this id'); this.data[id] = data; }; RegistryImpl.prototype.as = function (id) { return this.data[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[93/*vs/editor/common/modes/modesRegistry*/], __M([0/*require*/,1/*exports*/,310/*vs/nls!vs/editor/common/modes/modesRegistry*/,4/*vs/base/common/event*/,16/*vs/editor/common/modes*/,39/*vs/editor/common/modes/languageConfigurationRegistry*/,40/*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: [ ['(', ')'], ['[', ']'], ['{', '}'], ] }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[443/*vs/editor/common/services/getIconClasses*/], __M([0/*require*/,1/*exports*/,53/*vs/base/common/network*/,54/*vs/base/common/resources*/,93/*vs/editor/common/modes/modesRegistry*/,221/*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; var path = void 0; if (resource.scheme === network_1.Schemas.data) { var metadata = resources_1.DataUri.parseMetaData(resource); name_1 = metadata.get(resources_1.DataUri.META_DATA_LABEL); path = name_1; } else { name_1 = cssEscape(resources_1.basenameOrAuthority(resource).toLowerCase()); path = resource.path.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 } // Configured Language var configuredLangId = getConfiguredLangId(modelService, modeService, resource); configuredLangId = configuredLangId || (path ? modeService.getModeIdByFilepathOrFirstLine(path) : null); if (configuredLangId) { classes.push(cssEscape(configuredLangId) + "-lang-file-icon"); } } } return classes; } exports.getIconClasses = getIconClasses; function getConfiguredLangId(modelService, modeService, resource) { var configuredLangId = null; if (resource) { 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.getLanguageIdentifier().language; } } if (modeId && modeId !== modesRegistry_1.PLAINTEXT_MODE_ID) { configuredLangId = modeId; // only take if the mode is specific (aka no just plain text) } } return configuredLangId; } exports.getConfiguredLangId = getConfiguredLangId; 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[215/*vs/platform/jsonschemas/common/jsonContributionRegistry*/], __M([0/*require*/,1/*exports*/,40/*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[89/*vs/platform/configuration/common/configurationRegistry*/], __M([0/*require*/,1/*exports*/,357/*vs/nls!vs/platform/configuration/common/configurationRegistry*/,4/*vs/base/common/event*/,40/*vs/platform/registry/common/platform*/,20/*vs/base/common/types*/,5/*vs/base/common/strings*/,215/*vs/platform/jsonschemas/common/jsonContributionRegistry*/]), function (require, exports, nls, event_1, platform_1, types, strings, jsonContributionRegistry_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.windowSettings = { properties: {}, patternProperties: {} }; exports.resourceSettings = { properties: {}, patternProperties: {} }; exports.editorConfigurationSchemaId = 'vscode://schemas/settings/editor'; var contributionRegistry = platform_1.Registry.as(jsonContributionRegistry_1.Extensions.JSONContribution); var ConfigurationRegistry = /** @class */ (function () { function ConfigurationRegistry() { this.overrideIdentifiers = []; 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.editorConfigurationSchema = { properties: {}, patternProperties: {}, additionalProperties: false, errorMessage: 'Unknown editor configuration setting' }; this.configurationProperties = {}; this.excludedConfigurationProperties = {}; this.computeOverridePropertyPattern(); contributionRegistry.registerSchema(exports.editorConfigurationSchemaId, this.editorConfigurationSchema); } 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); _this.updateSchemaForOverrideSettingsConfiguration(configuration); }); this._onDidSchemaChange.fire(); this._onDidUpdateConfiguration.fire(properties); }; ConfigurationRegistry.prototype.registerOverrideIdentifiers = function (overrideIdentifiers) { var _a; (_a = this.overrideIdentifiers).push.apply(_a, overrideIdentifiers); this.updateOverridePropertyPatternKey(); }; ConfigurationRegistry.prototype.validateAndRegisterProperties = function (configuration, validate, scope, overridable) { if (validate === void 0) { validate = true; } if (scope === void 0) { scope = 3 /* WINDOW */; } if (overridable === void 0) { overridable = false; } scope = types.isUndefinedOrNull(configuration.scope) ? scope : configuration.scope; overridable = configuration.overridable || overridable; var propertyKeys = []; var properties = configuration.properties; if (properties) { for (var key in properties) { var message = void 0; if (validate && (message = validateProperty(key))) { console.warn(message); 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); } // Inherit overridable property from parent if (overridable) { property.overridable = true; } 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, overridable)); } } return propertyKeys; }; ConfigurationRegistry.prototype.getConfigurationProperties = function () { return this.configurationProperties; }; ConfigurationRegistry.prototype.registerJSONConfiguration = function (configuration) { function register(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 3 /* WINDOW */: exports.windowSettings.properties[key] = properties[key]; break; case 4 /* RESOURCE */: exports.resourceSettings.properties[key] = properties[key]; break; } } } var subNodes = configuration.allOf; if (subNodes) { subNodes.forEach(register); } } register(configuration); }; ConfigurationRegistry.prototype.updateSchemaForOverrideSettingsConfiguration = function (configuration) { if (configuration.id !== SETTINGS_OVERRRIDE_NODE_ID) { this.update(configuration); contributionRegistry.registerSchema(exports.editorConfigurationSchemaId, this.editorConfigurationSchema); } }; ConfigurationRegistry.prototype.updateOverridePropertyPatternKey = function () { var patternProperties = exports.allSettings.patternProperties[this.overridePropertyPattern]; if (!patternProperties) { patternProperties = { type: 'object', description: nls.localize(1, null), errorMessage: 'Unknown Identifier. Use language identifiers', $ref: exports.editorConfigurationSchemaId }; } delete exports.allSettings.patternProperties[this.overridePropertyPattern]; delete exports.applicationSettings.patternProperties[this.overridePropertyPattern]; delete exports.machineSettings.patternProperties[this.overridePropertyPattern]; delete exports.windowSettings.patternProperties[this.overridePropertyPattern]; delete exports.resourceSettings.patternProperties[this.overridePropertyPattern]; this.computeOverridePropertyPattern(); exports.allSettings.patternProperties[this.overridePropertyPattern] = patternProperties; exports.applicationSettings.patternProperties[this.overridePropertyPattern] = patternProperties; exports.machineSettings.patternProperties[this.overridePropertyPattern] = patternProperties; exports.windowSettings.patternProperties[this.overridePropertyPattern] = patternProperties; exports.resourceSettings.patternProperties[this.overridePropertyPattern] = patternProperties; this._onDidSchemaChange.fire(); }; ConfigurationRegistry.prototype.update = function (configuration) { var _this = this; var properties = configuration.properties; if (properties) { for (var key in properties) { if (properties[key].overridable) { this.editorConfigurationSchema.properties[key] = this.getConfigurationProperties()[key]; } } } var subNodes = configuration.allOf; if (subNodes) { subNodes.forEach(function (subNode) { return _this.update(subNode); }); } }; ConfigurationRegistry.prototype.computeOverridePropertyPattern = function () { this.overridePropertyPattern = this.overrideIdentifiers.length ? OVERRIDE_PATTERN_WITH_SUBSTITUTION.replace('${0}', this.overrideIdentifiers.map(function (identifier) { return strings.createRegExp(identifier, false).source; }).join('|')) : OVERRIDE_PROPERTY; }; return ConfigurationRegistry; }()); var SETTINGS_OVERRRIDE_NODE_ID = 'override'; var OVERRIDE_PROPERTY = '\\[.*\\]$'; var OVERRIDE_PATTERN_WITH_SUBSTITUTION = '\\[(${0})\\]$'; 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(2, null, property); } if (configurationRegistry.getConfigurationProperties()[property] !== undefined) { return nls.localize(3, 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[112/*vs/editor/common/config/commonEditorConfig*/], __M([0/*require*/,1/*exports*/,305/*vs/nls!vs/editor/common/config/commonEditorConfig*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,31/*vs/base/common/objects*/,17/*vs/base/common/platform*/,48/*vs/editor/common/config/editorOptions*/,101/*vs/editor/common/config/editorZoom*/,114/*vs/editor/common/config/fontInfo*/,89/*vs/platform/configuration/common/configurationRegistry*/,40/*vs/platform/registry/common/platform*/]), function (require, exports, nls, event_1, lifecycle_1, objects, platform, editorOptions, editorZoom_1, fontInfo_1, configurationRegistry_1, platform_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EDITOR_DEFAULTS = editorOptions.EDITOR_DEFAULTS; var EDITOR_FONT_DEFAULTS = editorOptions.EDITOR_FONT_DEFAULTS; var EDITOR_MODEL_DEFAULTS = editorOptions.EDITOR_MODEL_DEFAULTS; 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 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; // Do a "deep clone of sorts" on the incoming options _this._rawOptions = objects.mixin({}, options || {}); _this._rawOptions.scrollbar = objects.mixin({}, _this._rawOptions.scrollbar || {}); _this._rawOptions.minimap = objects.mixin({}, _this._rawOptions.minimap || {}); _this._rawOptions.find = objects.mixin({}, _this._rawOptions.find || {}); _this._rawOptions.hover = objects.mixin({}, _this._rawOptions.hover || {}); _this._rawOptions.parameterHints = objects.mixin({}, _this._rawOptions.parameterHints || {}); _this._validatedOptions = editorOptions.EditorOptionsValidator.validate(_this._rawOptions, EDITOR_DEFAULTS); _this._isDominatedByLongLines = false; _this._lineNumbersDigitCount = 1; _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.editor; var newOptions = this._computeInternalOptions(); if (oldOptions && oldOptions.equals(newOptions)) { return; } this.editor = newOptions; if (oldOptions) { this._onDidChange.fire(oldOptions.createChangeEvent(newOptions)); } }; CommonEditorConfiguration.prototype.getRawOptions = function () { return this._rawOptions; }; CommonEditorConfiguration.prototype._computeInternalOptions = function () { var opts = this._validatedOptions; var partialEnv = this._getEnvConfiguration(); var bareFontInfo = fontInfo_1.BareFontInfo.createFromRawSettings(this._rawOptions, 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 editorOptions.InternalEditorOptionsFactory.createInternalEditorOptions(env, opts); }; CommonEditorConfiguration._primitiveArrayEquals = function (a, b) { if (a.length !== b.length) { return false; } for (var i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; }; 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 (!this._primitiveArrayEquals(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; } if (CommonEditorConfiguration._subsetEquals(this._rawOptions, newOptions)) { return; } this._rawOptions = objects.mixin(this._rawOptions, newOptions || {}); this._validatedOptions = editorOptions.EditorOptionsValidator.validate(this._rawOptions, EDITOR_DEFAULTS); 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; var configurationRegistry = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration); var editorConfiguration = { 'id': 'editor', 'order': 5, 'type': 'object', 'title': nls.localize(0, null), 'overridable': true, 'scope': 4 /* RESOURCE */, 'properties': { 'editor.fontFamily': { 'type': 'string', 'default': EDITOR_FONT_DEFAULTS.fontFamily, 'description': nls.localize(1, null) }, 'editor.fontWeight': { 'type': 'string', 'enum': ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'], 'default': EDITOR_FONT_DEFAULTS.fontWeight, 'description': nls.localize(2, null) }, 'editor.fontSize': { 'type': 'number', 'default': EDITOR_FONT_DEFAULTS.fontSize, 'description': nls.localize(3, null) }, 'editor.lineHeight': { 'type': 'number', 'default': EDITOR_FONT_DEFAULTS.lineHeight, 'description': nls.localize(4, null) }, 'editor.letterSpacing': { 'type': 'number', 'default': EDITOR_FONT_DEFAULTS.letterSpacing, 'description': nls.localize(5, null) }, 'editor.lineNumbers': { 'type': 'string', 'enum': ['off', 'on', 'relative', 'interval'], 'enumDescriptions': [ nls.localize(6, null), nls.localize(7, null), nls.localize(8, null), nls.localize(9, null) ], 'default': 'on', 'description': nls.localize(10, null) }, 'editor.renderFinalNewline': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.renderFinalNewline, 'description': nls.localize(11, null) }, 'editor.rulers': { 'type': 'array', 'items': { 'type': 'number' }, 'default': EDITOR_DEFAULTS.viewInfo.rulers, 'description': nls.localize(12, null) }, 'editor.wordSeparators': { 'type': 'string', 'default': EDITOR_DEFAULTS.wordSeparators, 'description': nls.localize(13, null) }, 'editor.tabSize': { 'type': 'number', 'default': EDITOR_MODEL_DEFAULTS.tabSize, 'minimum': 1, 'markdownDescription': nls.localize(14, 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': EDITOR_MODEL_DEFAULTS.insertSpaces, 'markdownDescription': nls.localize(15, null) }, 'editor.detectIndentation': { 'type': 'boolean', 'default': EDITOR_MODEL_DEFAULTS.detectIndentation, 'markdownDescription': nls.localize(16, null) }, 'editor.roundedSelection': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.roundedSelection, 'description': nls.localize(17, null) }, 'editor.scrollBeyondLastLine': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.scrollBeyondLastLine, 'description': nls.localize(18, null) }, 'editor.scrollBeyondLastColumn': { 'type': 'number', 'default': EDITOR_DEFAULTS.viewInfo.scrollBeyondLastColumn, 'description': nls.localize(19, null) }, 'editor.smoothScrolling': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.smoothScrolling, 'description': nls.localize(20, null) }, 'editor.minimap.enabled': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.minimap.enabled, 'description': nls.localize(21, null) }, 'editor.minimap.side': { 'type': 'string', 'enum': ['left', 'right'], 'default': EDITOR_DEFAULTS.viewInfo.minimap.side, 'description': nls.localize(22, null) }, 'editor.minimap.showSlider': { 'type': 'string', 'enum': ['always', 'mouseover'], 'default': EDITOR_DEFAULTS.viewInfo.minimap.showSlider, 'description': nls.localize(23, null) }, 'editor.minimap.renderCharacters': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.minimap.renderCharacters, 'description': nls.localize(24, null) }, 'editor.minimap.maxColumn': { 'type': 'number', 'default': EDITOR_DEFAULTS.viewInfo.minimap.maxColumn, 'description': nls.localize(25, null) }, 'editor.hover.enabled': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.hover.enabled, 'description': nls.localize(26, null) }, 'editor.hover.delay': { 'type': 'number', 'default': EDITOR_DEFAULTS.contribInfo.hover.delay, 'description': nls.localize(27, null) }, 'editor.hover.sticky': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.hover.sticky, 'description': nls.localize(28, null) }, 'editor.find.seedSearchStringFromSelection': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.find.seedSearchStringFromSelection, 'description': nls.localize(29, null) }, 'editor.find.autoFindInSelection': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.find.autoFindInSelection, 'description': nls.localize(30, null) }, 'editor.find.globalFindClipboard': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.find.globalFindClipboard, 'description': nls.localize(31, null), 'included': platform.isMacintosh }, 'editor.find.addExtraSpaceOnTop': { 'type': 'boolean', 'default': true, 'description': nls.localize(32, null) }, 'editor.wordWrap': { 'type': 'string', 'enum': ['off', 'on', 'wordWrapColumn', 'bounded'], 'markdownEnumDescriptions': [ nls.localize(33, null), nls.localize(34, null), nls.localize(35, null), nls.localize(36, null), ], 'default': EDITOR_DEFAULTS.wordWrap, 'description': nls.localize(37, null) }, 'editor.wordWrapColumn': { 'type': 'integer', 'default': EDITOR_DEFAULTS.wordWrapColumn, 'minimum': 1, 'markdownDescription': nls.localize(38, null) }, 'editor.wrappingIndent': { 'type': 'string', 'enum': ['none', 'same', 'indent', 'deepIndent'], enumDescriptions: [ nls.localize(39, null), nls.localize(40, null), nls.localize(41, null), nls.localize(42, null), ], 'default': 'same', 'description': nls.localize(43, null), }, 'editor.mouseWheelScrollSensitivity': { 'type': 'number', 'default': EDITOR_DEFAULTS.viewInfo.scrollbar.mouseWheelScrollSensitivity, 'markdownDescription': nls.localize(44, null) }, 'editor.fastScrollSensitivity': { 'type': 'number', 'default': EDITOR_DEFAULTS.viewInfo.scrollbar.fastScrollSensitivity, 'markdownDescription': nls.localize(45, null) }, 'editor.multiCursorModifier': { 'type': 'string', 'enum': ['ctrlCmd', 'alt'], 'markdownEnumDescriptions': [ nls.localize(46, null), nls.localize(47, null) ], 'default': 'alt', 'markdownDescription': nls.localize(48, null) }, 'editor.multiCursorMergeOverlapping': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.multiCursorMergeOverlapping, 'description': nls.localize(49, null) }, 'editor.quickSuggestions': { 'anyOf': [ { type: 'boolean', }, { type: 'object', properties: { strings: { type: 'boolean', default: false, description: nls.localize(50, null) }, comments: { type: 'boolean', default: false, description: nls.localize(51, null) }, other: { type: 'boolean', default: true, description: nls.localize(52, null) }, } } ], 'default': EDITOR_DEFAULTS.contribInfo.quickSuggestions, 'description': nls.localize(53, null) }, 'editor.quickSuggestionsDelay': { 'type': 'integer', 'default': EDITOR_DEFAULTS.contribInfo.quickSuggestionsDelay, 'minimum': 0, 'description': nls.localize(54, null) }, 'editor.parameterHints.enabled': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.parameterHints.enabled, 'description': nls.localize(55, null) }, 'editor.parameterHints.cycle': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.parameterHints.cycle, 'description': nls.localize(56, null) }, 'editor.autoClosingBrackets': { type: 'string', enum: ['always', 'languageDefined', 'beforeWhitespace', 'never'], enumDescriptions: [ '', nls.localize(57, null), nls.localize(58, null), '', ], 'default': EDITOR_DEFAULTS.autoClosingBrackets, 'description': nls.localize(59, null) }, 'editor.autoClosingQuotes': { type: 'string', enum: ['always', 'languageDefined', 'beforeWhitespace', 'never'], enumDescriptions: [ '', nls.localize(60, null), nls.localize(61, null), '', ], 'default': EDITOR_DEFAULTS.autoClosingQuotes, 'description': nls.localize(62, null) }, 'editor.autoSurround': { type: 'string', enum: ['languageDefined', 'brackets', 'quotes', 'never'], enumDescriptions: [ nls.localize(63, null), nls.localize(64, null), nls.localize(65, null), '' ], 'default': EDITOR_DEFAULTS.autoSurround, 'description': nls.localize(66, null) }, 'editor.formatOnType': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.formatOnType, 'description': nls.localize(67, null) }, 'editor.formatOnPaste': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.formatOnPaste, 'description': nls.localize(68, null) }, 'editor.autoIndent': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.autoIndent, 'description': nls.localize(69, null) }, 'editor.suggestOnTriggerCharacters': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.suggestOnTriggerCharacters, 'description': nls.localize(70, null) }, 'editor.acceptSuggestionOnEnter': { 'type': 'string', 'enum': ['on', 'smart', 'off'], 'default': EDITOR_DEFAULTS.contribInfo.acceptSuggestionOnEnter, 'markdownEnumDescriptions': [ '', nls.localize(71, null), '' ], 'markdownDescription': nls.localize(72, null) }, 'editor.acceptSuggestionOnCommitCharacter': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.acceptSuggestionOnCommitCharacter, 'markdownDescription': nls.localize(73, null) }, 'editor.snippetSuggestions': { 'type': 'string', 'enum': ['top', 'bottom', 'inline', 'none'], 'enumDescriptions': [ nls.localize(74, null), nls.localize(75, null), nls.localize(76, null), nls.localize(77, null), ], 'default': EDITOR_DEFAULTS.contribInfo.suggest.snippets, 'description': nls.localize(78, null) }, 'editor.emptySelectionClipboard': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.emptySelectionClipboard, 'description': nls.localize(79, null) }, 'editor.copyWithSyntaxHighlighting': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.copyWithSyntaxHighlighting, 'description': nls.localize(80, null) }, 'editor.wordBasedSuggestions': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.wordBasedSuggestions, 'description': nls.localize(81, null) }, 'editor.suggestSelection': { 'type': 'string', 'enum': ['first', 'recentlyUsed', 'recentlyUsedByPrefix'], 'markdownEnumDescriptions': [ nls.localize(82, null), nls.localize(83, null), nls.localize(84, null), ], 'default': 'recentlyUsed', 'description': nls.localize(85, null) }, 'editor.suggestFontSize': { 'type': 'integer', 'default': 0, 'minimum': 0, 'markdownDescription': nls.localize(86, null) }, 'editor.suggestLineHeight': { 'type': 'integer', 'default': 0, 'minimum': 0, 'markdownDescription': nls.localize(87, null) }, 'editor.tabCompletion': { type: 'string', default: 'off', enum: ['on', 'off', 'onlySnippets'], enumDescriptions: [ nls.localize(88, null), nls.localize(89, null), nls.localize(90, null), ], description: nls.localize(91, null) }, 'editor.suggest.filterGraceful': { type: 'boolean', default: true, description: nls.localize(92, null) }, 'editor.suggest.localityBonus': { type: 'boolean', default: false, description: nls.localize(93, null) }, 'editor.suggest.shareSuggestSelections': { type: 'boolean', default: false, markdownDescription: nls.localize(94, null) }, 'editor.suggest.snippetsPreventQuickSuggestions': { type: 'boolean', default: true, description: nls.localize(95, null) }, 'editor.suggest.showIcons': { type: 'boolean', default: EDITOR_DEFAULTS.contribInfo.suggest.showIcons, description: nls.localize(96, null) }, 'editor.suggest.maxVisibleSuggestions': { type: 'number', default: EDITOR_DEFAULTS.contribInfo.suggest.maxVisibleSuggestions, minimum: 1, maximum: 15, description: nls.localize(97, null) }, 'editor.suggest.filteredTypes': { type: 'object', default: { keyword: true }, markdownDescription: nls.localize(98, null), properties: { method: { type: 'boolean', default: true, markdownDescription: nls.localize(99, null) }, function: { type: 'boolean', default: true, markdownDescription: nls.localize(100, null) }, constructor: { type: 'boolean', default: true, markdownDescription: nls.localize(101, null) }, field: { type: 'boolean', default: true, markdownDescription: nls.localize(102, null) }, variable: { type: 'boolean', default: true, markdownDescription: nls.localize(103, null) }, class: { type: 'boolean', default: true, markdownDescription: nls.localize(104, null) }, struct: { type: 'boolean', default: true, markdownDescription: nls.localize(105, null) }, interface: { type: 'boolean', default: true, markdownDescription: nls.localize(106, null) }, module: { type: 'boolean', default: true, markdownDescription: nls.localize(107, null) }, property: { type: 'boolean', default: true, markdownDescription: nls.localize(108, null) }, event: { type: 'boolean', default: true, markdownDescription: nls.localize(109, null) }, operator: { type: 'boolean', default: true, markdownDescription: nls.localize(110, null) }, unit: { type: 'boolean', default: true, markdownDescription: nls.localize(111, null) }, value: { type: 'boolean', default: true, markdownDescription: nls.localize(112, null) }, constant: { type: 'boolean', default: true, markdownDescription: nls.localize(113, null) }, enum: { type: 'boolean', default: true, markdownDescription: nls.localize(114, null) }, enumMember: { type: 'boolean', default: true, markdownDescription: nls.localize(115, null) }, keyword: { type: 'boolean', default: true, markdownDescription: nls.localize(116, null) }, text: { type: 'boolean', default: true, markdownDescription: nls.localize(117, null) }, color: { type: 'boolean', default: true, markdownDescription: nls.localize(118, null) }, file: { type: 'boolean', default: true, markdownDescription: nls.localize(119, null) }, reference: { type: 'boolean', default: true, markdownDescription: nls.localize(120, null) }, customcolor: { type: 'boolean', default: true, markdownDescription: nls.localize(121, null) }, folder: { type: 'boolean', default: true, markdownDescription: nls.localize(122, null) }, typeParameter: { type: 'boolean', default: true, markdownDescription: nls.localize(123, null) }, snippet: { type: 'boolean', default: true, markdownDescription: nls.localize(124, null) }, } }, 'editor.gotoLocation.multiple': { description: nls.localize(125, null), type: 'string', enum: ['peek', 'gotoAndPeek', 'goto'], default: EDITOR_DEFAULTS.contribInfo.gotoLocation.multiple, enumDescriptions: [ nls.localize(126, null), nls.localize(127, null), nls.localize(128, null) ] }, 'editor.selectionHighlight': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.selectionHighlight, 'description': nls.localize(129, null) }, 'editor.occurrencesHighlight': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.occurrencesHighlight, 'description': nls.localize(130, null) }, 'editor.overviewRulerLanes': { 'type': 'integer', 'default': 3, 'description': nls.localize(131, null) }, 'editor.overviewRulerBorder': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.overviewRulerBorder, 'description': nls.localize(132, null) }, 'editor.cursorBlinking': { 'type': 'string', 'enum': ['blink', 'smooth', 'phase', 'expand', 'solid'], 'default': editorOptions.blinkingStyleToString(EDITOR_DEFAULTS.viewInfo.cursorBlinking), 'description': nls.localize(133, null) }, 'editor.mouseWheelZoom': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.mouseWheelZoom, 'markdownDescription': nls.localize(134, null) }, 'editor.cursorSmoothCaretAnimation': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.cursorSmoothCaretAnimation, 'description': nls.localize(135, null) }, 'editor.cursorStyle': { 'type': 'string', 'enum': ['block', 'block-outline', 'line', 'line-thin', 'underline', 'underline-thin'], 'default': editorOptions.cursorStyleToString(EDITOR_DEFAULTS.viewInfo.cursorStyle), 'description': nls.localize(136, null) }, 'editor.cursorWidth': { 'type': 'integer', 'default': EDITOR_DEFAULTS.viewInfo.cursorWidth, 'markdownDescription': nls.localize(137, null) }, 'editor.fontLigatures': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.fontLigatures, 'description': nls.localize(138, null) }, 'editor.hideCursorInOverviewRuler': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.hideCursorInOverviewRuler, 'description': nls.localize(139, null) }, 'editor.renderWhitespace': { 'type': 'string', 'enum': ['none', 'boundary', 'all'], 'enumDescriptions': [ '', nls.localize(140, null), '' ], default: EDITOR_DEFAULTS.viewInfo.renderWhitespace, description: nls.localize(141, null) }, 'editor.renderControlCharacters': { 'type': 'boolean', default: EDITOR_DEFAULTS.viewInfo.renderControlCharacters, description: nls.localize(142, null) }, 'editor.renderIndentGuides': { 'type': 'boolean', default: EDITOR_DEFAULTS.viewInfo.renderIndentGuides, description: nls.localize(143, null) }, 'editor.highlightActiveIndentGuide': { 'type': 'boolean', default: EDITOR_DEFAULTS.viewInfo.highlightActiveIndentGuide, description: nls.localize(144, null) }, 'editor.renderLineHighlight': { 'type': 'string', 'enum': ['none', 'gutter', 'line', 'all'], 'enumDescriptions': [ '', '', '', nls.localize(145, null), ], default: EDITOR_DEFAULTS.viewInfo.renderLineHighlight, description: nls.localize(146, null) }, 'editor.codeLens': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.codeLens, 'description': nls.localize(147, null) }, 'editor.folding': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.folding, 'description': nls.localize(148, null) }, 'editor.foldingStrategy': { 'type': 'string', 'enum': ['auto', 'indentation'], 'default': EDITOR_DEFAULTS.contribInfo.foldingStrategy, 'markdownDescription': nls.localize(149, null) }, 'editor.showFoldingControls': { 'type': 'string', 'enum': ['always', 'mouseover'], 'default': EDITOR_DEFAULTS.contribInfo.showFoldingControls, 'description': nls.localize(150, null) }, 'editor.matchBrackets': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.matchBrackets, 'description': nls.localize(151, null) }, 'editor.glyphMargin': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.viewInfo.glyphMargin, 'description': nls.localize(152, null) }, 'editor.useTabStops': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.useTabStops, 'description': nls.localize(153, null) }, 'editor.trimAutoWhitespace': { 'type': 'boolean', 'default': EDITOR_MODEL_DEFAULTS.trimAutoWhitespace, 'description': nls.localize(154, null) }, 'editor.stablePeek': { 'type': 'boolean', 'default': false, 'markdownDescription': nls.localize(155, null) }, 'editor.dragAndDrop': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.dragAndDrop, 'description': nls.localize(156, null) }, 'editor.accessibilitySupport': { 'type': 'string', 'enum': ['auto', 'on', 'off'], 'enumDescriptions': [ nls.localize(157, null), nls.localize(158, null), nls.localize(159, null), ], 'default': EDITOR_DEFAULTS.accessibilitySupport, 'description': nls.localize(160, null) }, 'editor.showUnused': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.showUnused, 'description': nls.localize(161, null) }, 'editor.links': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.links, 'description': nls.localize(162, null) }, 'editor.colorDecorators': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.colorDecorators, 'description': nls.localize(163, null) }, 'editor.lightbulb.enabled': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.lightbulbEnabled, 'description': nls.localize(164, null) }, 'editor.maxTokenizationLineLength': { 'type': 'integer', 'default': 20000, 'description': nls.localize(165, null) }, 'editor.codeActionsOnSave': { 'type': 'object', 'properties': { 'source.organizeImports': { 'type': 'boolean', 'description': nls.localize(166, null) }, 'source.fixAll': { 'type': 'boolean', 'description': nls.localize(167, null) } }, 'additionalProperties': { 'type': 'boolean' }, 'default': EDITOR_DEFAULTS.contribInfo.codeActionsOnSave, 'description': nls.localize(168, null) }, 'editor.codeActionsOnSaveTimeout': { 'type': 'number', 'default': EDITOR_DEFAULTS.contribInfo.codeActionsOnSaveTimeout, 'description': nls.localize(169, null) }, 'editor.selectionClipboard': { 'type': 'boolean', 'default': EDITOR_DEFAULTS.contribInfo.selectionClipboard, 'description': nls.localize(170, null), 'included': platform.isLinux }, 'diffEditor.renderSideBySide': { 'type': 'boolean', 'default': true, 'description': nls.localize(171, null) }, 'diffEditor.ignoreTrimWhitespace': { 'type': 'boolean', 'default': true, 'description': nls.localize(172, null) }, 'editor.largeFileOptimizations': { 'type': 'boolean', 'default': EDITOR_MODEL_DEFAULTS.largeFileOptimizations, 'description': nls.localize(173, null) }, 'diffEditor.renderIndicators': { 'type': 'boolean', 'default': true, 'description': nls.localize(174, null) } } }; 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*/,30/*vs/base/browser/browser*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,345/*vs/editor/browser/config/charWidthReader*/,312/*vs/editor/browser/config/elementSizeObserver*/,112/*vs/editor/common/config/commonEditorConfig*/,114/*vs/editor/common/config/fontInfo*/]), function (require, exports, browser, event_1, lifecycle_1, platform, charWidthReader_1, elementSizeObserver_1, commonEditorConfig_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, 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), 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); 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 = true; var referenceWidth = monospace[0].width; for (var i = 1, len = monospace.length; 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, lineHeight: bareFontInfo.lineHeight, letterSpacing: bareFontInfo.letterSpacing, isMonospace: isMonospace, typicalHalfwidthCharacterWidth: typicalHalfwidthCharacter.width, typicalFullwidthCharacterWidth: typicalFullwidthCharacter.width, canUseHalfwidthRightwardsArrow: canUseHalfwidthRightwardsArrow, spaceWidth: space.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, function () { return _this._onReferenceDomElementSizeChanged(); })); _this._register(CSSBasedConfiguration.INSTANCE.onDidChange(function () { return _this._onCSSBasedConfigurationChanged(); })); if (_this._validatedOptions.automaticLayout) { _this._elementSizeObserver.startObserving(); } _this._register(browser.onDidChangeZoomLevel(function (_) { return _this._recomputeOptions(); })); _this._register(_this.accessibilityService.onDidChangeAccessibilitySupport(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.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.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.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[448/*vs/editor/browser/view/viewOverlays*/], __M([0/*require*/,1/*exports*/,26/*vs/base/browser/fastDomNode*/,60/*vs/editor/browser/config/configuration*/,160/*vs/editor/browser/view/viewLayer*/,33/*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.editor.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) { if (e.lineHeight) { this._lineHeight = this._configuration.editor.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; _this._contentWidth = _this._context.configuration.editor.layoutInfo.contentWidth; _this.domNode.setHeight(0); return _this; } // --- begin event handlers ContentViewOverlays.prototype.onConfigurationChanged = function (e) { if (e.layoutInfo) { this._contentWidth = this._context.configuration.editor.layoutInfo.contentWidth; } return _super.prototype.onConfigurationChanged.call(this, e); }; 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; _this._contentLeft = _this._context.configuration.editor.layoutInfo.contentLeft; _this.domNode.setClassName('margin-view-overlays'); _this.domNode.setWidth(1); configuration_1.Configuration.applyFontInfo(_this.domNode, _this._context.configuration.editor.fontInfo); return _this; } MarginViewOverlays.prototype.onConfigurationChanged = function (e) { var shouldRender = false; if (e.fontInfo) { configuration_1.Configuration.applyFontInfo(this.domNode, this._context.configuration.editor.fontInfo); shouldRender = true; } if (e.layoutInfo) { this._contentLeft = this._context.configuration.editor.layoutInfo.contentLeft; shouldRender = true; } return _super.prototype.onConfigurationChanged.call(this, e) || shouldRender; }; 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[449/*vs/editor/browser/viewParts/viewCursors/viewCursor*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,26/*vs/base/browser/fastDomNode*/,5/*vs/base/common/strings*/,60/*vs/editor/browser/config/configuration*/,48/*vs/editor/common/config/editorOptions*/,12/*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; this._cursorStyle = this._context.configuration.editor.viewInfo.cursorStyle; this._lineHeight = this._context.configuration.editor.lineHeight; this._typicalHalfwidthCharacterWidth = this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth; this._lineCursorWidth = Math.min(this._context.configuration.editor.viewInfo.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, this._context.configuration.editor.fontInfo); this._domNode.setDisplay('none'); this.updatePosition(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) { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; } if (e.fontInfo) { configuration_1.Configuration.applyFontInfo(this._domNode, this._context.configuration.editor.fontInfo); this._typicalHalfwidthCharacterWidth = this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth; } if (e.viewInfo) { this._cursorStyle = this._context.configuration.editor.viewInfo.cursorStyle; this._lineCursorWidth = Math.min(this._context.configuration.editor.viewInfo.cursorWidth, this._typicalHalfwidthCharacterWidth); } return true; }; ViewCursor.prototype.onCursorPositionChanged = function (position) { this.updatePosition(position); return true; }; ViewCursor.prototype._prepareRender = function (ctx) { var textContent = ''; var textContentClassName = ''; if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Line || this._cursorStyle === editorOptions_1.TextEditorCursorStyle.LineThin) { var visibleRange = ctx.visibleRangeForPosition(this._position); if (!visibleRange) { // 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 = this._context.model.getLineContent(this._position.lineNumber); textContent = lineContent.charAt(this._position.column - 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, textContentClassName); } var visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new range_1.Range(this._position.lineNumber, this._position.column, this._position.lineNumber, this._position.column + 1), false); if (!visibleRangeForCharacter || visibleRangeForCharacter.length === 0 || visibleRangeForCharacter[0].ranges.length === 0) { // Outside viewport return null; } var range = visibleRangeForCharacter[0].ranges[0]; var width = range.width < 1 ? this._typicalHalfwidthCharacterWidth : range.width; if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Block) { var lineData = this._context.model.getViewLineData(this._position.lineNumber); textContent = lineData.content.charAt(this._position.column - 1); if (strings.isHighSurrogate(lineData.content.charCodeAt(this._position.column - 1))) { textContent += lineData.content.charAt(this._position.column); } 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 }; }; ViewCursor.prototype.updatePosition = function (newPosition) { this._position = newPosition; }; 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[450/*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*/,533/*vs/base/common/mime*/,5/*vs/base/common/strings*/,16/*vs/editor/common/modes*/,93/*vs/editor/common/modes/modesRegistry*/,61/*vs/editor/common/modes/nullMode*/,89/*vs/platform/configuration/common/configurationRegistry*/,40/*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 (filepath, firstLine) { if (!filepath && !firstLine) { return []; } var mimeTypes = mime.guessMimeTypes(filepath, 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[451/*vs/editor/common/services/modeServiceImpl*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,272/*vs/editor/common/modes/abstractMode*/,61/*vs/editor/common/modes/nullMode*/,450/*vs/editor/common/services/languagesRegistry*/]), function (require, exports, event_1, lifecycle_1, abstractMode_1, nullMode_1, languagesRegistry_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 (filepath, firstLine) { var modeIds = this._registry.getModeIdsFromFilepathOrFirstLine(filepath, firstLine); if (modeIds.length > 0) { return modeIds[0]; } return null; }; ModeServiceImpl.prototype.getModeId = function (commaSeparatedMimetypesOrCommaSeparatedIds) { var modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds); if (modeIds.length > 0) { return modeIds[0]; } return 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 (filepath, firstLine) { var _this = this; return new LanguageSelection(this.onLanguagesMaybeChanged, function () { var modeId = _this.getModeIdByFilepathOrFirstLine(filepath, 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[41/*vs/platform/configuration/common/configuration*/], __M([0/*require*/,1/*exports*/,40/*vs/platform/registry/common/platform*/,13/*vs/platform/instantiation/common/instantiation*/,89/*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.user !== 'undefined' || typeof setting.workspace !== 'undefined' || typeof setting.workspaceFolder !== 'undefined') { return setting.value; } else if (typeof legacySetting.user !== 'undefined' || typeof legacySetting.workspace !== 'undefined' || typeof legacySetting.workspaceFolder !== 'undefined') { return legacySetting.value; } else { return setting.default; } } 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[453/*vs/editor/common/services/modelServiceImpl*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,48/*vs/editor/common/config/editorOptions*/,29/*vs/editor/common/model/textModel*/,93/*vs/editor/common/modes/modesRegistry*/,115/*vs/editor/common/services/resourceConfiguration*/,41/*vs/platform/configuration/common/configuration*/]), function (require, exports, event_1, lifecycle_1, platform, editorOptions_1, textModel_1, modesRegistry_1, resourceConfiguration_1, configuration_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.model = model; this._languageSelection = null; this._languageSelectionListener = null; this._modelEventListeners = []; this._modelEventListeners.push(model.onWillDispose(function () { return onWillDispose(model); })); this._modelEventListeners.push(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 = lifecycle_1.dispose(this._modelEventListeners); 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) { 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(); 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.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, resourceConfiguration_1.ITextResourcePropertiesService) ], ModelServiceImpl); return ModelServiceImpl; }(lifecycle_1.Disposable)); exports.ModelServiceImpl = ModelServiceImpl; }); define(__m[454/*vs/platform/configuration/common/configurationModels*/], __M([0/*require*/,1/*exports*/,46/*vs/base/common/map*/,19/*vs/base/common/arrays*/,20/*vs/base/common/types*/,31/*vs/base/common/objects*/,89/*vs/platform/configuration/common/configurationRegistry*/,41/*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.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(Object.keys(this.contents).concat(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); }; 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 = this.keys.slice(); 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()], 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(); } 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; return { default: overrides.overrideIdentifier ? this._defaultConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._defaultConfiguration.freeze().getValue(key), user: overrides.overrideIdentifier ? this.userConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.userConfiguration.freeze().getValue(key), userLocal: overrides.overrideIdentifier ? this.localUserConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.localUserConfiguration.freeze().getValue(key), userRemote: overrides.overrideIdentifier ? this.remoteUserConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.remoteUserConfiguration.freeze().getValue(key), workspace: workspace ? overrides.overrideIdentifier ? this._workspaceConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._workspaceConfiguration.freeze().getValue(key) : undefined, workspaceFolder: folderConfigurationModel ? overrides.overrideIdentifier ? folderConfigurationModel.freeze().override(overrides.overrideIdentifier).getValue(key) : folderConfigurationModel.freeze().getValue(key) : undefined, memory: overrides.overrideIdentifier ? memoryConfigurationModel.override(overrides.overrideIdentifier).getValue(key) : memoryConfigurationModel.getValue(key), value: consolidateConfigurationModel.getValue(key) }; }; 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 types.withUndefinedAsNull(this._folderConfigurations.get(root.uri)); } } return null; }; 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[455/*vs/platform/contextkey/browser/contextKeyService*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,46/*vs/base/common/map*/,27/*vs/platform/commands/common/commands*/,41/*vs/platform/configuration/common/configuration*/,18/*vs/platform/contextkey/common/contextkey*/,167/*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 = []; _this._lastContextId = 0; var myContext = new ConfigAwareContextValuesContainer(_this._myContextId, configurationService, _this._onDidChangeContext); _this._contexts.set(_this._myContextId, myContext); _this._toDispose.push(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 = lifecycle_1.dispose(this._toDispose); }; 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[95/*vs/platform/keybinding/common/keybindingsRegistry*/], __M([0/*require*/,1/*exports*/,36/*vs/base/common/keyCodes*/,17/*vs/base/common/platform*/,27/*vs/platform/commands/common/commands*/,40/*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, undefined, 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, undefined, 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[457/*vs/platform/browser/contextScopedHistoryWidget*/], __M([0/*require*/,1/*exports*/,18/*vs/platform/contextkey/common/contextkey*/,136/*vs/base/browser/ui/inputbox/inputBox*/,281/*vs/base/browser/ui/findinput/findInput*/,95/*vs/platform/keybinding/common/keybindingsRegistry*/]), function (require, exports, contextkey_1, inputBox_1, findInput_1, keybindingsRegistry_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 ContextScopedHistoryInputBox = /** @class */ (function (_super) { __extends(ContextScopedHistoryInputBox, _super); function ContextScopedHistoryInputBox(container, contextViewProvider, options, contextKeyService) { var _this = _super.call(this, container, contextViewProvider, options) || this; _this._register(createAndBindHistoryNavigationWidgetScopedContextKeyService(contextKeyService, { target: _this.element, historyNavigator: _this }).scopedContextKeyService); return _this; } ContextScopedHistoryInputBox = __decorate([ __param(3, contextkey_1.IContextKeyService) ], ContextScopedHistoryInputBox); return ContextScopedHistoryInputBox; }(inputBox_1.HistoryInputBox)); exports.ContextScopedHistoryInputBox = ContextScopedHistoryInputBox; 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; keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'history.showPrevious', weight: 200 /* WorkbenchContrib */, when: contextkey_1.ContextKeyExpr.and(new contextkey_1.ContextKeyDefinedExpr(exports.HistoryNavigationWidgetContext), new contextkey_1.ContextKeyEqualsExpr(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: new contextkey_1.ContextKeyAndExpr([new contextkey_1.ContextKeyDefinedExpr(exports.HistoryNavigationWidgetContext), new contextkey_1.ContextKeyEqualsExpr(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[68/*vs/platform/storage/common/storage*/], __M([0/*require*/,1/*exports*/,13/*vs/platform/instantiation/common/instantiation*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,20/*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 InMemoryStorageService = /** @class */ (function (_super) { __extends(InMemoryStorageService, _super); function InMemoryStorageService() { var _this = _super !== null && _super.apply(this, arguments) || this; _this._serviceBrand = undefined; _this._onDidChangeStorage = _this._register(new event_1.Emitter()); _this.onWillSaveState = event_1.Event.None; _this.globalCache = new Map(); _this.workspaceCache = new Map(); return _this; } Object.defineProperty(InMemoryStorageService.prototype, "onDidChangeStorage", { get: function () { return this._onDidChangeStorage.event; }, enumerable: true, configurable: true }); 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[188/*vs/editor/contrib/codelens/codeLensCache*/], __M([0/*require*/,1/*exports*/,13/*vs/platform/instantiation/common/instantiation*/,109/*vs/platform/instantiation/common/extensions*/,46/*vs/base/common/map*/,68/*vs/platform/storage/common/storage*/,3/*vs/editor/common/core/range*/]), function (require, exports, instantiation_1, extensions_1, map_1, storage_1, range_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); var key = 'codelens/cache'; // restore lens data on start var raw = storageService.get(key, 1 /* WORKSPACE */, '{}'); this._deserialize(raw); // store lens data on shutdown var listener = storageService.onWillSaveState(function () { storageService.store(key, _this._serialize(), 1 /* WORKSPACE */); listener.dispose(); }); } CodeLensCache.prototype.put = function (model, data) { var _this = this; var item = new CacheItem(model.getLineCount(), data.map(function (item) { return { symbol: item.symbol, provider: _this._fakeProvider }; })); 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; _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 symbols = []; for (var _i = 0, _a = element.lines; _i < _a.length; _i++) { var line = _a[_i]; symbols.push({ provider: this._fakeProvider, symbol: { range: new range_1.Range(line, 1, line, 11) } }); } this._cache.set(key, new CacheItem(element.lineCount, symbols)); } } 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[184/*vs/editor/contrib/suggest/suggestMemory*/], __M([0/*require*/,1/*exports*/,46/*vs/base/common/map*/,68/*vs/platform/storage/common/storage*/,16/*vs/editor/common/modes*/,2/*vs/base/common/lifecycle*/,15/*vs/base/common/async*/,13/*vs/platform/instantiation/common/instantiation*/,41/*vs/platform/configuration/common/configuration*/,109/*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; for (var i = 1; i < items.length; i++) { var _a = items[i], score = _a.score, suggestion = _a.completion; if (score !== 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) { // in order of completions, select the first // that has been used in the past var word = model.getWordUntilPosition(pos).word; if (word.length !== 0) { return _super.prototype.select.call(this, model, pos, items); } 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 res = -1; var seq = -1; for (var i = 0; i < items.length; i++) { var suggestion = items[i].completion; var key = model.getLanguageIdentifier().language + "/" + suggestion.label; var item = this._cache.get(key); if (item && item.touch > seq && item.type === suggestion.kind && item.insertText === suggestion.insertText) { seq = item.touch; res = i; } } if (res === -1) { return _super.prototype.select.call(this, model, pos, items); } else { return res; } }; 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 () { return _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[97/*vs/platform/telemetry/common/telemetry*/], __M([0/*require*/,1/*exports*/,13/*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[11/*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*/,12/*vs/editor/common/core/position*/,42/*vs/editor/common/services/modelService*/,80/*vs/editor/common/services/resolverService*/,58/*vs/platform/actions/common/actions*/,27/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,95/*vs/platform/keybinding/common/keybindingsRegistry*/,40/*vs/platform/registry/common/platform*/,97/*vs/platform/telemetry/common/telemetry*/,20/*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._menubarOpts = opts.menubarOpts; this._description = opts.description; } Command.prototype.register = function () { var _this = this; if (this._menubarOpts) { actions_1.MenuRegistry.appendMenuItem(this._menubarOpts.menuId, { group: this._menubarOpts.group, command: { id: this.id, title: this._menubarOpts.title, }, when: this._menubarOpts.when, order: this._menubarOpts.order }); } 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 }); } }; 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, opts) || this; _this.label = opts.label; _this.alias = opts.alias; _this.menuOpts = opts.menuOpts; return _this; } EditorAction.prototype.register = function () { if (this.menuOpts) { actions_1.MenuRegistry.appendMenuItem(7 /* EditorContext */, { command: { id: this.id, title: this.label }, when: contextkey_1.ContextKeyExpr.and(this.precondition, this.menuOpts.when), group: this.menuOpts.group, order: this.menuOpts.order }); } _super.prototype.register.call(this); }; EditorAction.prototype.runEditorCommand = function (accessor, editor, args) { this.reportTelemetry(accessor, editor); return this.run(accessor, editor, args || {}); }; EditorAction.prototype.reportTelemetry = function (accessor, editor) { /* __GDPR__ "editorActionInvoked" : { "name" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "id": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "${include}": [ "${EditorTelemetryData}" ] } */ accessor.get(telemetry_1.ITelemetryService).publicLog('editorActionInvoked', __assign({ name: this.label, id: this.id }, editor.getTelemetryData())); }; 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 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(ctor) { EditorContributionRegistry.INSTANCE.registerEditorContribution(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; })(EditorExtensionsRegistry = exports.EditorExtensionsRegistry || (exports.EditorExtensionsRegistry = {})); // Editor extension points var Extensions = { EditorCommonContributions: 'editor.contributions' }; var EditorContributionRegistry = /** @class */ (function () { function EditorContributionRegistry() { this.editorContributions = []; this.editorActions = []; this.editorCommands = Object.create(null); } EditorContributionRegistry.prototype.registerEditorContribution = function (ctor) { this.editorContributions.push(ctor); }; EditorContributionRegistry.prototype.registerEditorAction = function (action) { action.register(); this.editorActions.push(action); }; EditorContributionRegistry.prototype.getEditorContributions = function () { return this.editorContributions.slice(0); }; 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[132/*vs/editor/browser/controller/coreCommands*/], __M([0/*require*/,1/*exports*/,301/*vs/nls!vs/editor/browser/controller/coreCommands*/,20/*vs/base/common/types*/,11/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,383/*vs/editor/common/controller/cursorColumnSelection*/,38/*vs/editor/common/controller/cursorCommon*/,193/*vs/editor/common/controller/cursorDeleteOperations*/,187/*vs/editor/common/controller/cursorMoveCommands*/,130/*vs/editor/common/controller/cursorTypeOperations*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,70/*vs/editor/common/editorCommon*/,21/*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(true, 0 /* Primary */, 0 /* Smooth */); }; return BaseMoveToCommand; }(CoreEditorCommand)); CoreNavigationCommands.MoveTo = editorExtensions_1.registerEditorCommand(new BaseMoveToCommand({ id: '_moveTo', inSelectionMode: false, precondition: null })); CoreNavigationCommands.MoveToSelect = editorExtensions_1.registerEditorCommand(new BaseMoveToCommand({ id: '_moveToSelect', inSelectionMode: true, precondition: null })); 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({ toViewLineNumber: result.toLineNumber, toViewVisualColumn: result.toVisualColumn }); cursors.reveal(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: null }) || this; } class_1.prototype._getColumnSelectResult = function (context, primary, prevColumnSelectData, args) { // validate `args` var validatedPosition = context.model.validatePosition(args.position); var validatedViewPosition; if (args.viewPosition) { validatedViewPosition = context.validateViewPosition(new position_1.Position(args.viewPosition.lineNumber, args.viewPosition.column), validatedPosition); } else { validatedViewPosition = context.convertModelPositionToViewPosition(validatedPosition); } return cursorColumnSelection_1.ColumnSelection.columnSelect(context.config, context.viewModel, primary.viewState.selection, 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: null, 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, primary.viewState, prevColumnSelectData.toViewLineNumber, prevColumnSelectData.toViewVisualColumn); }; 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: null, 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, primary.viewState, prevColumnSelectData.toViewLineNumber, prevColumnSelectData.toViewVisualColumn); }; 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, primary.viewState, this._isPaged, prevColumnSelectData.toViewLineNumber, prevColumnSelectData.toViewVisualColumn); }; return ColumnSelectUpCommand; }(ColumnSelectCommand)); CoreNavigationCommands.CursorColumnSelectUp = editorExtensions_1.registerEditorCommand(new ColumnSelectUpCommand({ isPaged: false, id: 'cursorColumnSelectUp', precondition: null, 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: null, 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, primary.viewState, this._isPaged, prevColumnSelectData.toViewLineNumber, prevColumnSelectData.toViewVisualColumn); }; return ColumnSelectDownCommand; }(ColumnSelectCommand)); CoreNavigationCommands.CursorColumnSelectDown = editorExtensions_1.registerEditorCommand(new ColumnSelectDownCommand({ isPaged: false, id: 'cursorColumnSelectDown', precondition: null, 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: null, 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: null, 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(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: null, 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: null, 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: null, 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: null, 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: null, 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: null, 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: null, 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: null, 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: null, 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: null, 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: null, 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: null, 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: null }) || 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: null }) || 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(true, 0 /* Primary */, 0 /* Smooth */); }; return HomeCommand; }(CoreEditorCommand)); CoreNavigationCommands.CursorHome = editorExtensions_1.registerEditorCommand(new HomeCommand({ inSelectionMode: false, id: 'cursorHome', precondition: null, 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: null, 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: null, 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(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(true, 0 /* Primary */, 0 /* Smooth */); }; return EndCommand; }(CoreEditorCommand)); CoreNavigationCommands.CursorEnd = editorExtensions_1.registerEditorCommand(new EndCommand({ inSelectionMode: false, id: 'cursorEnd', precondition: null, 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: null, 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: null, 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(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(true, 0 /* Primary */, 0 /* Smooth */); }; return TopCommand; }(CoreEditorCommand)); CoreNavigationCommands.CursorTop = editorExtensions_1.registerEditorCommand(new TopCommand({ inSelectionMode: false, id: 'cursorTop', precondition: null, 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: null, 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(true, 0 /* Primary */, 0 /* Smooth */); }; return BottomCommand; }(CoreEditorCommand)); CoreNavigationCommands.CursorBottom = editorExtensions_1.registerEditorCommand(new BottomCommand({ inSelectionMode: false, id: 'cursorBottom', precondition: null, 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: null, 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: null, 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: null, 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: null, 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: null, 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: null, 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(true, 0 /* Primary */, 0 /* Smooth */); }; return WordCommand; }(CoreEditorCommand)); CoreNavigationCommands.WordSelect = editorExtensions_1.registerEditorCommand(new WordCommand({ inSelectionMode: false, id: '_wordSelect', precondition: null })); CoreNavigationCommands.WordSelectDrag = editorExtensions_1.registerEditorCommand(new WordCommand({ inSelectionMode: true, id: '_wordSelectDrag', precondition: null })); CoreNavigationCommands.LastCursorWordSelect = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_12, _super); function class_12() { return _super.call(this, { id: 'lastCursorWordSelect', precondition: null }) || 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(false, 0 /* Primary */, 0 /* Smooth */); }; return LineCommand; }(CoreEditorCommand)); CoreNavigationCommands.LineSelect = editorExtensions_1.registerEditorCommand(new LineCommand({ inSelectionMode: false, id: '_lineSelect', precondition: null })); CoreNavigationCommands.LineSelectDrag = editorExtensions_1.registerEditorCommand(new LineCommand({ inSelectionMode: true, id: '_lineSelectDrag', precondition: null })); 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: null })); CoreNavigationCommands.LastCursorLineSelectDrag = editorExtensions_1.registerEditorCommand(new LastCursorLineCommand({ inSelectionMode: true, id: 'lastCursorLineSelectDrag', precondition: null })); CoreNavigationCommands.ExpandLineSelection = editorExtensions_1.registerEditorCommand(new /** @class */ (function (_super) { __extends(class_13, _super); function class_13() { return _super.call(this, { id: 'expandLineSelection', precondition: null, 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(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(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(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: null, 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(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: null }) || 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: null }) || 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: null, 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 */ }, menubarOpts: { menuId: 22 /* 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 */ }, menubarOpts: { menuId: 14 /* 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 */ } }, menubarOpts: { menuId: 14 /* 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[464/*vs/editor/browser/view/viewController*/], __M([0/*require*/,1/*exports*/,132/*vs/editor/browser/controller/coreCommands*/,12/*vs/editor/common/core/position*/]), function (require, exports, coreCommands_1, position_1) { "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) { this.commandDelegate.paste(source, text, pasteOnNewLine, multicursorText); }; 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.editor.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.editor.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) { if (data.middleButton) { if (data.inSelectionMode) { this._columnSelect(data.position, data.mouseColumn); } else { this.moveTo(data.position); } } 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); } 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); } 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) { viewPosition = this._validateViewColumn(viewPosition); this._execMouseCommand(coreCommands_1.CoreNavigationCommands.ColumnSelect, { position: this._convertViewToModelPosition(viewPosition), viewPosition: viewPosition, mouseColumn: mouseColumn }); }; 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[465/*vs/editor/contrib/caretOperations/caretOperations*/], __M([0/*require*/,1/*exports*/,315/*vs/nls!vs/editor/contrib/caretOperations/caretOperations*/,11/*vs/editor/browser/editorExtensions*/,21/*vs/editor/common/editorContextKeys*/,241/*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[466/*vs/editor/contrib/caretOperations/transpose*/], __M([0/*require*/,1/*exports*/,316/*vs/nls!vs/editor/contrib/caretOperations/transpose*/,5/*vs/base/common/strings*/,11/*vs/editor/browser/editorExtensions*/,77/*vs/editor/common/commands/replaceCommand*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/editorContextKeys*/]), function (require, exports, nls, strings_1, editorExtensions_1, replaceCommand_1, position_1, range_1, editorContextKeys_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.positionLeftOf = function (start, model) { var column = start.column; var lineNumber = start.lineNumber; if (column > model.getLineMinColumn(lineNumber)) { if (strings_1.isLowSurrogate(model.getLineContent(lineNumber).charCodeAt(column - 2))) { // character before column is a low surrogate column = column - 2; } else { column = column - 1; } } else if (lineNumber > 1) { lineNumber = lineNumber - 1; column = model.getLineMaxColumn(lineNumber); } return new position_1.Position(lineNumber, column); }; TransposeLettersAction.prototype.positionRightOf = function (start, model) { var column = start.column; var lineNumber = start.lineNumber; if (column < model.getLineMaxColumn(lineNumber)) { if (strings_1.isHighSurrogate(model.getLineContent(lineNumber).charCodeAt(column - 1))) { // character after column is a high surrogate column = column + 2; } else { column = column + 1; } } else if (lineNumber < model.getLineCount()) { lineNumber = lineNumber + 1; column = 0; } return new position_1.Position(lineNumber, column); }; 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() : this.positionRightOf(selection.getPosition(), model); var middlePosition = this.positionLeftOf(endPosition, model); var beginPosition = this.positionLeftOf(middlePosition, model); 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[467/*vs/editor/contrib/clipboard/clipboard*/], __M([0/*require*/,1/*exports*/,317/*vs/nls!vs/editor/contrib/clipboard/clipboard*/,30/*vs/base/browser/browser*/,17/*vs/base/common/platform*/,171/*vs/editor/browser/controller/textAreaInput*/,11/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,21/*vs/editor/common/editorContextKeys*/,397/*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 = null; } _this = _super.call(this, 'cut', { id: 'editor.action.clipboardCutAction', label: nls.localize(0, null), alias: 'Cut', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: kbOpts, menuOpts: { group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 1 }, menubarOpts: { menuId: 14 /* 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.getConfiguration().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 = null; } _this = _super.call(this, 'copy', { id: 'editor.action.clipboardCopyAction', label: nls.localize(2, null), alias: 'Copy', precondition: null, kbOpts: kbOpts, menuOpts: { group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 2 }, menubarOpts: { menuId: 14 /* 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.getConfiguration().emptySelectionClipboard; if (!emptySelectionClipboard && editor.getSelection().isEmpty()) { return; } // Prevent copying an empty line by accident if (editor.getSelections().length === 1 && editor.getSelection().isEmpty()) { if (editor.getModel().getLineFirstNonWhitespaceColumn(editor.getSelection().positionLineNumber) === 0) { 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 = null; } _this = _super.call(this, 'paste', { id: 'editor.action.clipboardPasteAction', label: nls.localize(4, null), alias: 'Paste', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: kbOpts, menuOpts: { group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 3 }, menubarOpts: { menuId: 14 /* 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: null, 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.getConfiguration().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. *--------------------------------------------------------------------------------------------*/ define(__m[177/*vs/editor/contrib/codeAction/codeAction*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,24/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,11/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,16/*vs/editor/common/modes*/,42/*vs/editor/common/services/modelService*/,151/*vs/editor/contrib/codeAction/codeActionTrigger*/,64/*vs/editor/browser/core/editorState*/]), function (require, exports, arrays_1, cancellation_1, errors_1, uri_1, editorExtensions_1, range_1, modes_1, modelService_1, codeActionTrigger_1, editorState_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CodeActionSet = /** @class */ (function () { function CodeActionSet(actions) { this.actions = arrays_1.mergeSort(actions, CodeActionSet.codeActionsComparator); } CodeActionSet.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(CodeActionSet.prototype, "hasAutoFix", { get: function () { return this.actions.some(function (fix) { return !!fix.kind && codeActionTrigger_1.CodeActionKind.QuickFix.contains(new codeActionTrigger_1.CodeActionKind(fix.kind)) && !!fix.isPreferred; }); }, enumerable: true, configurable: true }); return CodeActionSet; }()); exports.CodeActionSet = CodeActionSet; function getCodeActions(model, rangeOrSelection, trigger, token) { var filter = trigger.filter || {}; var codeActionContext = { only: filter.kind ? filter.kind.value : undefined, trigger: trigger.type === 'manual' ? 2 /* Manual */ : 1 /* Automatic */ }; var cts = new editorState_1.TextModelCancellationTokenSource(model, token); var providers = getCodeActionProviders(model, filter); var promises = providers.map(function (provider) { return Promise.resolve(provider.provideCodeActions(model, rangeOrSelection, codeActionContext, cts.token)).then(function (providedCodeActions) { if (cts.token.isCancellationRequested || !Array.isArray(providedCodeActions)) { return []; } return providedCodeActions.filter(function (action) { return action && codeActionTrigger_1.filtersAction(filter, action); }); }, function (err) { if (errors_1.isPromiseCanceledError(err)) { throw err; } errors_1.onUnexpectedExternalError(err); return []; }); }); var listener = modes_1.CodeActionProviderRegistry.onDidChange(function () { var newProviders = modes_1.CodeActionProviderRegistry.all(model); if (!arrays_1.equals(newProviders, providers)) { cts.cancel(); } }); return Promise.all(promises) .then(arrays_1.flatten) .then(function (actions) { return new CodeActionSet(actions); }) .finally(function () { listener.dispose(); cts.dispose(); }); } exports.getCodeActions = getCodeActions; function getCodeActionProviders(model, filter) { return modes_1.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 codeActionTrigger_1.mayIncludeActionsOfKind(filter, new codeActionTrigger_1.CodeActionKind(kind)); }); }); } editorExtensions_1.registerLanguageCommand('_executeCodeActionProvider', function (accessor, args) { var resource = args.resource, range = args.range, kind = args.kind; if (!(resource instanceof uri_1.URI) || !range_1.Range.isIRange(range)) { throw errors_1.illegalArgument(); } var model = accessor.get(modelService_1.IModelService).getModel(resource); if (!model) { throw errors_1.illegalArgument(); } return getCodeActions(model, model.validateRange(range), { type: 'manual', filter: { includeSourceActions: true, kind: kind && kind.value ? new codeActionTrigger_1.CodeActionKind(kind.value) : undefined } }, cancellation_1.CancellationToken.None).then(function (actions) { return actions.actions; }); }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[174/*vs/editor/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*/,16/*vs/editor/common/modes*/,18/*vs/platform/contextkey/common/contextkey*/,177/*vs/editor/contrib/codeAction/codeAction*/]), function (require, exports, async_1, event_1, lifecycle_1, range_1, modes_1, contextkey_1, codeAction_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SUPPORTED_CODE_ACTIONS = new contextkey_1.RawContextKey('supportedCodeAction', ''); var CodeActionOracle = /** @class */ (function () { function CodeActionOracle(_editor, _markerService, _signalChange, _delay, _progressService) { var _this = this; if (_delay === void 0) { _delay = 250; } this._editor = _editor; this._markerService = _markerService; this._signalChange = _signalChange; this._delay = _delay; this._progressService = _progressService; this._disposables = []; this._autoTriggerTimer = new async_1.TimeoutTimer(); this._disposables.push(this._markerService.onMarkerChanged(function (e) { return _this._onMarkerChanges(e); }), this._editor.onDidChangeCursorPosition(function () { return _this._onCursorChange(); })); } CodeActionOracle.prototype.dispose = function () { this._disposables = lifecycle_1.dispose(this._disposables); this._autoTriggerTimer.cancel(); }; 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 resource.toString() === model.uri.toString(); })) { this._autoTriggerTimer.cancelAndSet(function () { _this.trigger({ type: 'auto' }); }, this._delay); } }; CodeActionOracle.prototype._onCursorChange = function () { var _this = this; this._autoTriggerTimer.cancelAndSet(function () { _this.trigger({ type: '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]; if (range_1.Range.intersectRanges(marker, selection)) { return range_1.Range.lift(marker); } } 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 === '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 ? selection : undefined; }; CodeActionOracle.prototype._createEventAndSignalChange = function (trigger, selection) { if (!selection) { // cancel this._signalChange(CodeActionsState.Empty); return Promise.resolve(undefined); } else { var model_1 = this._editor.getModel(); if (!model_1) { // cancel this._signalChange(CodeActionsState.Empty); return Promise.resolve(undefined); } var markerRange = this._getRangeOfMarker(selection); var position = markerRange ? markerRange.getStartPosition() : selection.getStartPosition(); var actions = async_1.createCancelablePromise(function (token) { return codeAction_1.getCodeActions(model_1, selection, trigger, token); }); if (this._progressService && trigger.type === 'manual') { this._progressService.showWhile(actions, 250); } this._signalChange(new CodeActionsState.Triggered(trigger, selection, position, actions)); return actions; } }; return CodeActionOracle; }()); exports.CodeActionOracle = CodeActionOracle; var CodeActionsState; (function (CodeActionsState) { CodeActionsState.Empty = new /** @class */ (function () { function class_1() { this.type = 0 /* Empty */; } return class_1; }()); 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 () { function CodeActionModel(_editor, _markerService, contextKeyService, _progressService) { var _this = this; this._editor = _editor; this._markerService = _markerService; this._progressService = _progressService; this._state = CodeActionsState.Empty; this._onDidChangeState = new event_1.Emitter(); this._disposables = []; this._supportedCodeActions = exports.SUPPORTED_CODE_ACTIONS.bindTo(contextKeyService); this._disposables.push(this._editor.onDidChangeModel(function () { return _this._update(); })); this._disposables.push(this._editor.onDidChangeModelLanguage(function () { return _this._update(); })); this._disposables.push(modes_1.CodeActionProviderRegistry.onDidChange(function () { return _this._update(); })); this._update(); } CodeActionModel.prototype.dispose = function () { this._disposables = lifecycle_1.dispose(this._disposables); lifecycle_1.dispose(this._codeActionOracle); }; Object.defineProperty(CodeActionModel.prototype, "onDidChangeState", { get: function () { return this._onDidChangeState.event; }, enumerable: true, configurable: true }); CodeActionModel.prototype._update = function () { var _this = this; if (this._codeActionOracle) { this._codeActionOracle.dispose(); this._codeActionOracle = undefined; } if (this._state.type === 1 /* Triggered */) { this._state.actions.cancel(); } this.setState(CodeActionsState.Empty); var model = this._editor.getModel(); if (model && modes_1.CodeActionProviderRegistry.has(model) && !this._editor.getConfiguration().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 = new CodeActionOracle(this._editor, this._markerService, function (newState) { return _this.setState(newState); }, undefined, this._progressService); this._codeActionOracle.trigger({ type: 'auto' }); } else { this._supportedCodeActions.reset(); } }; CodeActionModel.prototype.trigger = function (trigger) { if (this._codeActionOracle) { return this._codeActionOracle.trigger(trigger); } return Promise.resolve(undefined); }; CodeActionModel.prototype.setState = function (newState) { if (newState === this._state) { return; } this._state = newState; this._onDidChangeState.fire(newState); }; return CodeActionModel; }()); 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[470/*vs/editor/contrib/codeAction/lightBulbWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,72/*vs/base/browser/globalMouseMoveMonitor*/,24/*vs/base/common/cancellation*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,29/*vs/editor/common/model/textModel*/,174/*vs/editor/contrib/codeAction/codeActionModel*/,395/*vs/css!vs/editor/contrib/codeAction/lightBulbWidget*/]), function (require, exports, dom, globalMouseMoveMonitor_1, cancellation_1, event_1, lifecycle_1, textModel_1, codeActionModel_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LightBulbWidget = /** @class */ (function (_super) { __extends(LightBulbWidget, _super); function LightBulbWidget(editor) { var _this = _super.call(this) || this; _this._onClick = _this._register(new event_1.Emitter()); _this.onClick = _this._onClick.event; _this._state = codeActionModel_1.CodeActionsState.Empty; _this._futureFixes = new cancellation_1.CancellationTokenSource(); _this._domNode = document.createElement('div'); _this._domNode.className = 'lightbulb-glyph'; _this._editor = editor; _this._editor.addContentWidget(_this); _this._register(_this._editor.onDidChangeModel(function (_) { return _this._futureFixes.cancel(); })); _this._register(_this._editor.onDidChangeModelLanguage(function (_) { return _this._futureFixes.cancel(); })); _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 /* Triggered */ || !editorModel || _this._state.position.lineNumber >= editorModel.getLineCount()) { _this._futureFixes.cancel(); } })); _this._register(dom.addStandardDisposableListener(_this._domNode, 'click', function (e) { if (_this._state.type !== 1 /* Triggered */) { return; } // Make sure that focus / cursor location is not lost when clicking widget icon _this._editor.focus(); // a bit of extra work to make sure the menu // doesn't cover the line-text var _a = dom.getDomNodePagePosition(_this._domNode), top = _a.top, height = _a.height; var lineHeight = _this._editor.getConfiguration().lineHeight; var pad = Math.floor(lineHeight / 3); if (_this._position && _this._position.position !== null && _this._position.position.lineNumber < _this._state.position.lineNumber) { pad += lineHeight; } _this._onClick.fire({ x: e.posx, y: top + height + pad, state: _this._state }); })); _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(globalMouseMoveMonitor_1.standardMouseMoveMerger, function () { }, function () { monitor.dispose(); }); })); _this._register(_this._editor.onDidChangeConfiguration(function (e) { // hide when told to do so if (e.contribInfo && !_this._editor.getConfiguration().contribInfo.lightbulbEnabled) { _this.hide(); } })); 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._position; }; LightBulbWidget.prototype.tryShow = function (newState) { var _this = this; if (newState.type !== 1 /* Triggered */ || this._position && (!newState.position || this._position.position && this._position.position.lineNumber !== newState.position.lineNumber)) { // hide when getting a 'hide'-request or when currently // showing on another line this.hide(); } else if (this._futureFixes) { // cancel pending show request in any case this._futureFixes.cancel(); } this._futureFixes = new cancellation_1.CancellationTokenSource(); var token = this._futureFixes.token; this._state = newState; if (this._state.type === codeActionModel_1.CodeActionsState.Empty.type) { return; } var selection = this._state.rangeOrSelection; this._state.actions.then(function (fixes) { if (!token.isCancellationRequested && fixes.actions.length > 0 && selection) { _this._show(fixes); } else { _this.hide(); } }).catch(function () { _this.hide(); }); }; Object.defineProperty(LightBulbWidget.prototype, "title", { get: function () { return this._domNode.title; }, set: function (value) { this._domNode.title = value; }, enumerable: true, configurable: true }); LightBulbWidget.prototype._show = function (codeActions) { var _this = this; var config = this._editor.getConfiguration(); if (!config.contribInfo.lightbulbEnabled) { return; } if (this._state.type !== 1 /* Triggered */) { return; } var _a = this._state.position, lineNumber = _a.lineNumber, column = _a.column; var model = this._editor.getModel(); if (!model) { return; } var tabSize = model.getOptions().tabSize; var lineContent = model.getLineContent(lineNumber); var indent = textModel_1.TextModel.computeIndentLevel(lineContent, tabSize); var lineHasSpace = config.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 * config.fontInfo.spaceWidth < 22) { // cannot show lightbulb above/below and showing // it inline would overlay the cursor... this.hide(); return; } } this._position = { position: { lineNumber: effectiveLineNumber, column: 1 }, preference: LightBulbWidget._posPref }; dom.toggleClass(this._domNode, 'autofixable', codeActions.hasAutoFix); this._editor.layoutContentWidget(this); }; LightBulbWidget.prototype.hide = function () { this._position = null; this._state = codeActionModel_1.CodeActionsState.Empty; this._futureFixes.cancel(); this._editor.layoutContentWidget(this); }; LightBulbWidget._posPref = [0 /* EXACT */]; return LightBulbWidget; }(lifecycle_1.Disposable)); exports.LightBulbWidget = LightBulbWidget; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[471/*vs/editor/contrib/codelens/codelens*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,24/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,11/*vs/editor/browser/editorExtensions*/,16/*vs/editor/common/modes*/,42/*vs/editor/common/services/modelService*/]), function (require, exports, arrays_1, cancellation_1, errors_1, uri_1, editorExtensions_1, modes_1, modelService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getCodeLensData(model, token) { var symbols = []; var provider = modes_1.CodeLensProviderRegistry.ordered(model); var promises = provider.map(function (provider) { return Promise.resolve(provider.provideCodeLenses(model, token)).then(function (result) { if (Array.isArray(result)) { for (var _i = 0, result_1 = result; _i < result_1.length; _i++) { var symbol = result_1[_i]; symbols.push({ symbol: symbol, provider: provider }); } } }).catch(errors_1.onUnexpectedExternalError); }); return Promise.all(promises).then(function () { return arrays_1.mergeSort(symbols, 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 (provider.indexOf(a.provider) < provider.indexOf(b.provider)) { return -1; } else if (provider.indexOf(a.provider) > provider.indexOf(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; } }); }); } 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 = []; return getCodeLensData(model, cancellation_1.CancellationToken.None).then(function (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, value_1 = value; _i < value_1.length; _i++) { var item = value_1[_i]; _loop_1(item); } return Promise.all(resolve); }).then(function () { 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[173/*vs/editor/contrib/colorPicker/color*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,11/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,16/*vs/editor/common/modes*/,42/*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[172/*vs/editor/contrib/colorPicker/colorDetector*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,28/*vs/base/common/color*/,10/*vs/base/common/errors*/,566/*vs/base/common/hash*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,3/*vs/editor/common/core/range*/,29/*vs/editor/common/model/textModel*/,16/*vs/editor/common/modes*/,173/*vs/editor/contrib/colorPicker/color*/,41/*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 () { function ColorDetector(_editor, _codeEditorService, _configurationService) { var _this = this; this._editor = _editor; this._codeEditorService = _codeEditorService; this._configurationService = _configurationService; this._globalToDispose = []; this._localToDispose = []; this._decorationsIds = []; this._colorDatas = new Map(); this._colorDecoratorIds = []; this._decorationsTypes = {}; this._globalToDispose.push(_editor.onDidChangeModel(function (e) { _this._isEnabled = _this.isEnabled(); _this.onModelChanged(); })); this._globalToDispose.push(_editor.onDidChangeModelLanguage(function (e) { return _this.onModelChanged(); })); this._globalToDispose.push(modes_1.ColorProviderRegistry.onDidChange(function (e) { return _this.onModelChanged(); })); this._globalToDispose.push(_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(); } 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.getConfiguration().contribInfo.colorDecorators; }; ColorDetector.prototype.getId = function () { return ColorDetector.ID; }; ColorDetector.get = function (editor) { return editor.getContribution(this.ID); }; ColorDetector.prototype.dispose = function () { this.stop(); this.removeAllDecorations(); this._globalToDispose = lifecycle_1.dispose(this._globalToDispose); }; 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.push(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 = lifecycle_1.dispose(this._localToDispose); }; 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 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[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' } } }); } 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) }); } for (var subType in this._decorationsTypes) { if (!newDecorationsTypes[subType]) { this._codeEditorService.removeDecorationType(subType); } } this._colorDecoratorIds = this._editor.deltaDecorations(this._colorDecoratorIds, decorations); }; ColorDetector.prototype.removeAllDecorations = function () { this._decorationsIds = this._editor.deltaDecorations(this._decorationsIds, []); this._colorDecoratorIds = this._editor.deltaDecorations(this._colorDecoratorIds, []); for (var subType in this._decorationsTypes) { 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; }()); exports.ColorDetector = ColorDetector; editorExtensions_1.registerEditorContribution(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[474/*vs/editor/contrib/comment/comment*/], __M([0/*require*/,1/*exports*/,319/*vs/nls!vs/editor/contrib/comment/comment*/,36/*vs/base/common/keyCodes*/,11/*vs/editor/browser/editorExtensions*/,21/*vs/editor/common/editorContextKeys*/,214/*vs/editor/contrib/comment/blockCommentCommand*/,246/*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 opts = model.getOptions(); for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) { var selection = selections_1[_i]; commands.push(new lineCommentCommand_1.LineCommentCommand(selection, opts.tabSize, this._type)); } 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 */ }, menubarOpts: { menuId: 14 /* 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 */ }, menubarOpts: { menuId: 14 /* MenubarEditMenu */, group: '5_insert', title: nls.localize(5, null), order: 2 } }) || this; } BlockCommentAction.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } 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)); } 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[475/*vs/editor/contrib/contextmenu/contextmenu*/], __M([0/*require*/,1/*exports*/,320/*vs/nls!vs/editor/contrib/contextmenu/contextmenu*/,7/*vs/base/browser/dom*/,79/*vs/base/browser/ui/actionbar/actionbar*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/browser/editorExtensions*/,21/*vs/editor/common/editorContextKeys*/,58/*vs/platform/actions/common/actions*/,18/*vs/platform/contextkey/common/contextkey*/,59/*vs/platform/contextview/browser/contextView*/,37/*vs/platform/keybinding/common/keybinding*/]), function (require, exports, nls, dom, actionbar_1, lifecycle_1, editorExtensions_1, editorContextKeys_1, actions_1, contextkey_1, contextView_1, keybinding_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 = []; this._contextMenuIsBeingShownCount = 0; this._editor = editor; this._toDispose.push(this._editor.onContextMenu(function (e) { return _this._onContextMenu(e); })); this._toDispose.push(this._editor.onMouseWheel(function (e) { if (_this._contextMenuIsBeingShownCount > 0) { _this._contextViewService.hideContextView(); } })); this._toDispose.push(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.getConfiguration().contribInfo.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 && !this._editor.getSelection().containsPosition(e.target.position)) { 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.getConfiguration().contribInfo.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()); // Show menu if we have actions to show if (menuActions.length > 0) { this._doShowContextMenu(menuActions, anchor); } }; ContextMenuController.prototype._getMenuActions = function (model) { var result = []; var contextMenu = this._menuService.createMenu(7 /* EditorContext */, this._contextKeyService); var groups = contextMenu.getActions({ arg: model.uri }); contextMenu.dispose(); for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) { var group = groups_1[_i]; var actions = group[1]; result.push.apply(result, actions); result.push(new actionbar_1.Separator()); } 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.getConfiguration().contribInfo.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; }, getActionItem: function (action) { var keybinding = _this._keybindingFor(action); if (keybinding) { return new actionbar_1.ActionItem(action, action, { label: true, keybinding: keybinding.getLabel(), isMenu: true }); } var customActionItem = action; if (typeof customActionItem.getActionItem === 'function') { return customActionItem.getActionItem(); } return new actionbar_1.ActionItem(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.getId = function () { return ContextMenuController.ID; }; ContextMenuController.prototype.dispose = function () { if (this._contextMenuIsBeingShownCount > 0) { this._contextViewService.hideContextView(); } this._toDispose = lifecycle_1.dispose(this._toDispose); }; 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: null, 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); 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[476/*vs/editor/contrib/cursorUndo/cursorUndo*/], __M([0/*require*/,1/*exports*/,321/*vs/nls!vs/editor/contrib/cursorUndo/cursorUndo*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/browser/editorExtensions*/,21/*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 CursorUndoController = /** @class */ (function (_super) { __extends(CursorUndoController, _super); function CursorUndoController(editor) { var _this = _super.call(this) || this; _this._editor = editor; _this._isCursorUndo = false; _this._undoStack = []; _this._prevState = _this._readState(); _this._register(editor.onDidChangeModel(function (e) { _this._undoStack = []; _this._prevState = null; })); _this._register(editor.onDidChangeModelContent(function (e) { _this._undoStack = []; _this._prevState = null; })); _this._register(editor.onDidChangeCursorSelection(function (e) { if (!_this._isCursorUndo && _this._prevState) { _this._undoStack.push(_this._prevState); if (_this._undoStack.length > 50) { // keep the cursor undo stack bounded _this._undoStack.shift(); } } _this._prevState = _this._readState(); })); return _this; } CursorUndoController.get = function (editor) { return editor.getContribution(CursorUndoController.ID); }; CursorUndoController.prototype._readState = function () { if (!this._editor.hasModel()) { // no model => no state return null; } return new CursorState(this._editor.getSelections()); }; CursorUndoController.prototype.getId = function () { return CursorUndoController.ID; }; CursorUndoController.prototype.cursorUndo = function () { if (!this._editor.hasModel()) { return; } var currState = new CursorState(this._editor.getSelections()); while (this._undoStack.length > 0) { var prevState = this._undoStack.pop(); if (!prevState.equals(currState)) { this._isCursorUndo = true; this._editor.setSelections(prevState.selections); this._editor.revealRangeInCenterIfOutsideViewport(prevState.selections[0], 0 /* Smooth */); this._isCursorUndo = false; return; } } }; CursorUndoController.ID = 'editor.contrib.cursorUndoController'; return CursorUndoController; }(lifecycle_1.Disposable)); exports.CursorUndoController = CursorUndoController; var CursorUndo = /** @class */ (function (_super) { __extends(CursorUndo, _super); function CursorUndo() { return _super.call(this, { id: 'cursorUndo', label: nls.localize(0, null), alias: 'Soft Undo', precondition: null, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2048 /* CtrlCmd */ | 51 /* KEY_U */, weight: 100 /* EditorContrib */ } }) || this; } CursorUndo.prototype.run = function (accessor, editor, args) { CursorUndoController.get(editor).cursorUndo(); }; return CursorUndo; }(editorExtensions_1.EditorAction)); exports.CursorUndo = CursorUndo; editorExtensions_1.registerEditorContribution(CursorUndoController); editorExtensions_1.registerEditorAction(CursorUndo); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[477/*vs/editor/contrib/dnd/dnd*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,11/*vs/editor/browser/editorExtensions*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,247/*vs/editor/contrib/dnd/dragAndDropCommand*/,29/*vs/editor/common/model/textModel*/,392/*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 () { function DragAndDropController(editor) { var _this = this; this._editor = editor; this._toUnhook = []; this._toUnhook.push(this._editor.onMouseDown(function (e) { return _this._onEditorMouseDown(e); })); this._toUnhook.push(this._editor.onMouseUp(function (e) { return _this._onEditorMouseUp(e); })); this._toUnhook.push(this._editor.onMouseDrag(function (e) { return _this._onEditorMouseDrag(e); })); this._toUnhook.push(this._editor.onMouseDrop(function (e) { return _this._onEditorMouseDrop(e); })); this._toUnhook.push(this._editor.onKeyDown(function (e) { return _this.onEditorKeyDown(e); })); this._toUnhook.push(this._editor.onKeyUp(function (e) { return _this.onEditorKeyUp(e); })); this._toUnhook.push(this._editor.onDidBlurEditorWidget(function () { return _this.onEditorBlur(); })); this._dndDecorationIds = []; this._mouseDown = false; this._modifierPressed = false; this._dragSelection = null; } DragAndDropController.prototype.onEditorBlur = function () { this._removeDecoration(); this._dragSelection = null; this._mouseDown = false; this._modifierPressed = false; }; DragAndDropController.prototype.onEditorKeyDown = function (e) { if (!this._editor.getConfiguration().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.getConfiguration().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.getId = function () { return DragAndDropController.ID; }; DragAndDropController.prototype.dispose = function () { this._removeDecoration(); this._dragSelection = null; this._mouseDown = false; this._modifierPressed = false; this._toUnhook = lifecycle_1.dispose(this._toUnhook); }; 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; }()); exports.DragAndDropController = DragAndDropController; editorExtensions_1.registerEditorContribution(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[478/*vs/editor/contrib/folding/folding*/], __M([0/*require*/,1/*exports*/,324/*vs/nls!vs/editor/contrib/folding/folding*/,20/*vs/base/common/types*/,5/*vs/base/common/strings*/,15/*vs/base/common/async*/,36/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/browser/editorExtensions*/,252/*vs/editor/contrib/folding/foldingModel*/,400/*vs/editor/contrib/folding/foldingDecorations*/,21/*vs/editor/common/editorContextKeys*/,253/*vs/editor/contrib/folding/hiddenRangeModel*/,39/*vs/editor/common/modes/languageConfigurationRegistry*/,401/*vs/editor/contrib/folding/indentRangeProvider*/,16/*vs/editor/common/modes*/,208/*vs/editor/contrib/folding/syntaxRangeProvider*/,255/*vs/editor/contrib/folding/intializingRangeProvider*/,10/*vs/base/common/errors*/,387/*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) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ID = 'editor.contrib.folding'; var FoldingController = /** @class */ (function () { function FoldingController(editor) { var _this = this; this.editor = editor; this._isEnabled = this.editor.getConfiguration().contribInfo.folding; this._autoHideFoldingControls = this.editor.getConfiguration().contribInfo.showFoldingControls === 'mouseover'; this._useFoldingProviders = this.editor.getConfiguration().contribInfo.foldingStrategy !== 'indentation'; this.globalToDispose = []; this.localToDispose = []; this.foldingDecorationProvider = new foldingDecorations_1.FoldingDecorationProvider(editor); this.foldingDecorationProvider.autoHideFoldingControls = this._autoHideFoldingControls; this.globalToDispose.push(this.editor.onDidChangeModel(function () { return _this.onModelChanged(); })); this.globalToDispose.push(this.editor.onDidChangeConfiguration(function (e) { if (e.contribInfo) { var oldIsEnabled = _this._isEnabled; _this._isEnabled = _this.editor.getConfiguration().contribInfo.folding; if (oldIsEnabled !== _this._isEnabled) { _this.onModelChanged(); } var oldShowFoldingControls = _this._autoHideFoldingControls; _this._autoHideFoldingControls = _this.editor.getConfiguration().contribInfo.showFoldingControls === 'mouseover'; if (oldShowFoldingControls !== _this._autoHideFoldingControls) { _this.foldingDecorationProvider.autoHideFoldingControls = _this._autoHideFoldingControls; _this.onModelContentChanged(); } var oldUseFoldingProviders = _this._useFoldingProviders; _this._useFoldingProviders = _this.editor.getConfiguration().contribInfo.foldingStrategy !== 'indentation'; if (oldUseFoldingProviders !== _this._useFoldingProviders) { _this.onFoldingStrategyChanged(); } } })); this.globalToDispose.push({ dispose: function () { return lifecycle_1.dispose(_this.localToDispose); } }); this.onModelChanged(); } FoldingController.get = function (editor) { return editor.getContribution(exports.ID); }; FoldingController.prototype.getId = function () { return exports.ID; }; FoldingController.prototype.dispose = function () { this.globalToDispose = lifecycle_1.dispose(this.globalToDispose); }; /** * 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 = lifecycle_1.dispose(this.localToDispose); 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.push(this.foldingModel); this.hiddenRangeModel = new hiddenRangeModel_1.HiddenRangeModel(this.foldingModel); this.localToDispose.push(this.hiddenRangeModel); this.localToDispose.push(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.push(this.cursorChangedScheduler); this.localToDispose.push(modes_1.FoldingRangeProviderRegistry.onDidChange(function () { return _this.onFoldingStrategyChanged(); })); this.localToDispose.push(this.editor.onDidChangeModelLanguageConfiguration(function () { return _this.onFoldingStrategyChanged(); })); // covers model language changes as well this.localToDispose.push(this.editor.onDidChangeModelContent(function () { return _this.onModelContentChanged(); })); this.localToDispose.push(this.editor.onDidChangeCursorPosition(function () { return _this.onCursorPositionChanged(); })); this.localToDispose.push(this.editor.onMouseDown(function (e) { return _this.onEditorMouseDown(e); })); this.localToDispose.push(this.editor.onMouseUp(function (e) { return _this.onEditorMouseUp(e); })); this.localToDispose.push({ 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 7 /* CONTENT_EMPTY */: { if (this.hiddenRangeModel.hasRanges()) { var data_1 = e.target.detail; if (!data_1.isAfterLines) { break; } } return; } 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_1 = region.isCollapsed; if (iconClicked || isCollapsed_1) { var toToggle = [region]; if (e.event.middleButton || e.event.shiftKey) { toToggle.push.apply(toToggle, foldingModel.getRegionsInside(region, function (r) { return r.isCollapsed === isCollapsed_1; })); } 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 */); }; return FoldingController; }()); 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: null, 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: null, 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: null, 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. Defaults to 1.\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", 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; } FoldAction.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, true, levels, lineNumbers); } else { foldingModel_1.setCollapseStateLevelsDown(foldingModel, true, levels, lineNumbers); } }; return FoldAction; }(FoldingAction)); var FoldRecursivelyAction = /** @class */ (function (_super) { __extends(FoldRecursivelyAction, _super); function FoldRecursivelyAction() { return _super.call(this, { id: 'editor.foldRecursively', label: nls.localize(3, null), alias: 'Fold Recursively', precondition: null, 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(4, null), alias: 'Fold All Block Comments', precondition: null, 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(5, null), alias: 'Fold All Regions', precondition: null, 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(6, null), alias: 'Unfold All Regions', precondition: null, 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(7, null), alias: 'Fold All', precondition: null, 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(8, null), alias: 'Unfold All', precondition: null, 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); 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); for (var i = 1; i <= 7; i++) { editorExtensions_1.registerInstantiatedEditorAction(new FoldLevelAction({ id: FoldLevelAction.ID(i), label: nls.localize(9, null, i), alias: "Fold Level " + i, precondition: null, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | (21 /* KEY_0 */ + i)), weight: 100 /* EditorContrib */ } })); } }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[479/*vs/editor/contrib/fontZoom/fontZoom*/], __M([0/*require*/,1/*exports*/,325/*vs/nls!vs/editor/contrib/fontZoom/fontZoom*/,11/*vs/editor/browser/editorExtensions*/,101/*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: null }) || 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: null }) || 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: null }) || 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[480/*vs/editor/contrib/format/format*/], __M([0/*require*/,1/*exports*/,47/*vs/base/browser/ui/aria/aria*/,19/*vs/base/common/arrays*/,24/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,64/*vs/editor/browser/core/editorState*/,106/*vs/editor/browser/editorBrowser*/,11/*vs/editor/browser/editorExtensions*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,16/*vs/editor/common/modes*/,63/*vs/editor/common/services/editorWorkerService*/,42/*vs/editor/common/services/modelService*/,207/*vs/editor/contrib/format/formattingEdit*/,326/*vs/nls!vs/editor/contrib/format/format*/,363/*vs/platform/extensions/common/extensions*/,13/*vs/platform/instantiation/common/instantiation*/,84/*vs/base/common/linkedList*/]), function (require, exports, aria_1, arrays_1, cancellation_1, errors_1, uri_1, editorState_1, editorBrowser_1, editorExtensions_1, position_1, range_1, selection_1, modes_1, editorWorkerService_1, modelService_1, formattingEdit_1, nls, extensions_1, instantiation_1, linkedList_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, validate, state_1, versionNow_1, rawEdits, edits, 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(); state_1 = new editorState_1.EditorState(editorOrModel, 1 /* Value */ | 4 /* Position */); validate = function () { return state_1.validate(editorOrModel); }; } else { model = editorOrModel; versionNow_1 = editorOrModel.getVersionId(); validate = function () { return versionNow_1 === editorOrModel.getVersionId(); }; } return [4 /*yield*/, provider.provideDocumentRangeFormattingEdits(model, range, model.getFormattingOptions(), token)]; case 1: rawEdits = _a.sent(); return [4 /*yield*/, workerService.computeMoreMinimalEdits(model.uri, rawEdits)]; case 2: edits = _a.sent(); if (!validate()) { return [2 /*return*/, true]; } 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.focus(); 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, rawEdits, edits, 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); } return [4 /*yield*/, provider.provideDocumentFormattingEdits(model, model.getFormattingOptions(), cts.token)]; case 1: rawEdits = _a.sent(); return [4 /*yield*/, workerService.computeMoreMinimalEdits(model.uri, rawEdits)]; case 2: edits = _a.sent(); if (cts.token.isCancellationRequested) { return [2 /*return*/, true]; } 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.focus(); 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; editorExtensions_1.registerLanguageCommand('_executeFormatRangeProvider', function (accessor, args) { var resource = args.resource, range = args.range, options = args.options; if (!(resource instanceof uri_1.URI) || !range_1.Range.isIRange(range)) { throw errors_1.illegalArgument(); } 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); }); editorExtensions_1.registerLanguageCommand('_executeFormatDocumentProvider', function (accessor, args) { var resource = args.resource, options = args.options; if (!(resource instanceof uri_1.URI)) { throw errors_1.illegalArgument('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); }); editorExtensions_1.registerLanguageCommand('_executeFormatOnTypeProvider', function (accessor, args) { var resource = args.resource, position = args.position, ch = args.ch, options = args.options; if (!(resource instanceof uri_1.URI) || !position_1.Position.isIPosition(position) || typeof ch !== 'string') { throw errors_1.illegalArgument(); } 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[481/*vs/editor/contrib/format/formatActions*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,24/*vs/base/common/cancellation*/,36/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,76/*vs/editor/common/core/characterClassifier*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/editorContextKeys*/,16/*vs/editor/common/modes*/,63/*vs/editor/common/services/editorWorkerService*/,480/*vs/editor/contrib/format/format*/,207/*vs/editor/contrib/format/formattingEdit*/,327/*vs/nls!vs/editor/contrib/format/formatActions*/,27/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,13/*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"; var _this = this; Object.defineProperty(exports, "__esModule", { value: true }); var FormatOnType = /** @class */ (function () { function FormatOnType(editor, _workerService) { var _this = this; this._workerService = _workerService; this._callOnDispose = []; this._callOnModel = []; this._editor = editor; this._callOnDispose.push(editor.onDidChangeConfiguration(function () { return _this._update(); })); this._callOnDispose.push(editor.onDidChangeModel(function () { return _this._update(); })); this._callOnDispose.push(editor.onDidChangeModelLanguage(function () { return _this._update(); })); this._callOnDispose.push(modes_1.OnTypeFormattingEditProviderRegistry.onDidChange(this._update, this)); } FormatOnType.prototype.getId = function () { return FormatOnType.ID; }; FormatOnType.prototype.dispose = function () { this._callOnDispose = lifecycle_1.dispose(this._callOnDispose); this._callOnModel = lifecycle_1.dispose(this._callOnModel); }; FormatOnType.prototype._update = function () { var _this = this; // clean up this._callOnModel = lifecycle_1.dispose(this._callOnModel); // we are disabled if (!this._editor.getConfiguration().contribInfo.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.push(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 = []; this._callOnModel = []; this._callOnDispose.push(editor.onDidChangeConfiguration(function () { return _this._update(); })); this._callOnDispose.push(editor.onDidChangeModel(function () { return _this._update(); })); this._callOnDispose.push(editor.onDidChangeModelLanguage(function () { return _this._update(); })); this._callOnDispose.push(modes_1.DocumentRangeFormattingEditProviderRegistry.onDidChange(this._update, this)); } FormatOnPaste.prototype.getId = function () { return FormatOnPaste.ID; }; FormatOnPaste.prototype.dispose = function () { this._callOnDispose = lifecycle_1.dispose(this._callOnDispose); this._callOnModel = lifecycle_1.dispose(this._callOnModel); }; FormatOnPaste.prototype._update = function () { var _this = this; // clean up this._callOnModel = lifecycle_1.dispose(this._callOnModel); // we are disabled if (!this.editor.getConfiguration().contribInfo.formatOnPaste) { return; } // no model if (!this.editor.hasModel()) { return; } // no formatter if (!modes_1.DocumentRangeFormattingEditProviderRegistry.has(this.editor.getModel())) { return; } this._callOnModel.push(this.editor.onDidPaste(function (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 */ }, menuOpts: { 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 Code', 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 */ }, menuOpts: { 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); editorExtensions_1.registerEditorContribution(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(_this, 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[170/*vs/editor/contrib/goToDefinition/goToDefinition*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,24/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,11/*vs/editor/browser/editorExtensions*/,16/*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 getDefinitions(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 getDefinitions(model, position, modes_1.DefinitionProviderRegistry, function (provider, model, position) { return provider.provideDefinition(model, position, token); }); } exports.getDefinitionsAtPosition = getDefinitionsAtPosition; function getDeclarationsAtPosition(model, position, token) { return getDefinitions(model, position, modes_1.DeclarationProviderRegistry, function (provider, model, position) { return provider.provideDeclaration(model, position, token); }); } exports.getDeclarationsAtPosition = getDeclarationsAtPosition; function getImplementationsAtPosition(model, position, token) { return getDefinitions(model, position, modes_1.ImplementationProviderRegistry, function (provider, model, position) { return provider.provideImplementation(model, position, token); }); } exports.getImplementationsAtPosition = getImplementationsAtPosition; function getTypeDefinitionsAtPosition(model, position, token) { return getDefinitions(model, position, modes_1.TypeDefinitionProviderRegistry, function (provider, model, position) { return provider.provideTypeDefinition(model, position, token); }); } exports.getTypeDefinitionsAtPosition = getTypeDefinitionsAtPosition; editorExtensions_1.registerDefaultLanguageCommand('_executeDefinitionProvider', function (model, position) { return getDefinitionsAtPosition(model, position, cancellation_1.CancellationToken.None); }); editorExtensions_1.registerDefaultLanguageCommand('_executeDeclarationProvider', function (model, position) { return getDeclarationsAtPosition(model, position, cancellation_1.CancellationToken.None); }); editorExtensions_1.registerDefaultLanguageCommand('_executeImplementationProvider', function (model, position) { return getImplementationsAtPosition(model, position, cancellation_1.CancellationToken.None); }); editorExtensions_1.registerDefaultLanguageCommand('_executeTypeDefinitionProvider', function (model, position) { return getTypeDefinitionsAtPosition(model, position, 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[483/*vs/editor/contrib/hover/getHover*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,24/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,11/*vs/editor/browser/editorExtensions*/,16/*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.registerDefaultLanguageCommand('_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[484/*vs/editor/contrib/linesOperations/linesOperations*/], __M([0/*require*/,1/*exports*/,335/*vs/nls!vs/editor/contrib/linesOperations/linesOperations*/,36/*vs/base/common/keyCodes*/,132/*vs/editor/browser/controller/coreCommands*/,11/*vs/editor/browser/editorExtensions*/,77/*vs/editor/common/commands/replaceCommand*/,307/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/,130/*vs/editor/common/controller/cursorTypeOperations*/,55/*vs/editor/common/core/editOperation*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,21/*vs/editor/common/editorContextKeys*/,262/*vs/editor/contrib/linesOperations/copyLinesCommand*/,402/*vs/editor/contrib/linesOperations/moveLinesCommand*/,263/*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 */ }, menubarOpts: { menuId: 22 /* 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 */ }, menubarOpts: { menuId: 22 /* MenubarSelectionMenu */, group: '2_line', title: nls.localize(3, null), order: 2 } }) || this; } return CopyLinesDownAction; }(AbstractCopyLinesAction)); // 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.getConfiguration().autoIndent; for (var _i = 0, selections_2 = selections; _i < selections_2.length; _i++) { var selection = selections_2[_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(4, 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 */ }, menubarOpts: { menuId: 22 /* MenubarSelectionMenu */, group: '2_line', title: nls.localize(5, 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(6, 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 */ }, menubarOpts: { menuId: 22 /* MenubarSelectionMenu */, group: '2_line', title: nls.localize(7, 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_3 = selections; _i < selections_3.length; _i++) { var selection = selections_3[_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(8, 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(9, 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(10, 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(11, 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(12, 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(13, 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(14, 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(15, 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(16, 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 selection; } }); 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(17, 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(18, 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(19, 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.getConfiguration().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(20, 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(21, 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(22, 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(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[111/*vs/editor/contrib/parameterHints/provideSignatureHelp*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,11/*vs/editor/browser/editorExtensions*/,16/*vs/editor/common/modes*/,18/*vs/platform/contextkey/common/contextkey*/,24/*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(errors_1.onUnexpectedExternalError); }; })); } exports.provideSignatureHelp = provideSignatureHelp; editorExtensions_1.registerDefaultLanguageCommand('_executeSignatureHelpProvider', function (model, position, args) { return provideSignatureHelp(model, position, { triggerKind: modes.SignatureHelpTriggerKind.Invoke, isRetrigger: false, triggerCharacter: args['triggerCharacter'] }, 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[486/*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*/,76/*vs/editor/common/core/characterClassifier*/,16/*vs/editor/common/modes*/,111/*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 = new /** @class */ (function () { function class_1() { this.type = 0 /* Default */; } return class_1; }()); 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._state = ParameterHintState.Default; _this.triggerChars = new characterClassifier_1.CharacterSet(); _this.retriggerChars = new characterClassifier_1.CharacterSet(); _this.triggerId = 0; _this.editor = editor; _this.enabled = false; _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.throttledDelayer.trigger(function () { return _this.doTrigger({ triggerKind: context.triggerKind, triggerCharacter: context.triggerCharacter, isRetrigger: _this.state.type === 1 /* Active */ || _this.state.type === 2 /* Pending */, activeSignatureHelp: _this.state.type === 1 /* Active */ ? _this.state.hints : undefined }, triggerId); }, delay).then(undefined, 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.getConfiguration().contribInfo.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.getConfiguration().contribInfo.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({}, this.state.hints, { activeSignature: activeSignature })); this._onChangedHints.fire(this.state.hints); }; ParameterHintsModel.prototype.doTrigger = function (triggerContext, triggerId) { var _this = this; this.cancel(true); if (!this.editor.hasModel()) { return Promise.resolve(false); } var model = this.editor.getModel(); var position = this.editor.getPosition(); this.state = new ParameterHintState.Pending(async_1.createCancelablePromise(function (token) { return provideSignatureHelp_1.provideSignatureHelp(model, position, triggerContext, token); })); return this.state.request.then(function (result) { // Check that we are still resolving the correct signature help if (triggerId !== _this.triggerId) { return false; } if (!result || !result.signatures || result.signatures.length === 0) { _this.cancel(); return false; } else { _this.state = new ParameterHintState.Active(result); _this._onChangedHints.fire(_this.state.hints); return true; } }).catch(function (error) { if (triggerId === _this.triggerId) { _this.state = ParameterHintState.Default; } errors_1.onUnexpectedError(error); return false; }); }; 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.enabled) { 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.enabled = this.editor.getConfiguration().contribInfo.parameterHints.enabled; if (!this.enabled) { 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; }); /*--------------------------------------------------------------------------------------------- * 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/contrib/quickOpen/quickOpen*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,11/*vs/editor/browser/editorExtensions*/,16/*vs/editor/common/modes*/,42/*vs/editor/common/services/modelService*/,24/*vs/base/common/cancellation*/,80/*vs/editor/common/services/resolverService*/]), function (require, exports, errors_1, uri_1, range_1, editorExtensions_1, modes_1, modelService_1, cancellation_1, resolverService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getDocumentSymbols(model, flat, token) { var roots = []; var promises = modes_1.DocumentSymbolProviderRegistry.all(model).map(function (support) { return Promise.resolve(support.provideDocumentSymbols(model, token)).then(function (result) { if (Array.isArray(result)) { roots.push.apply(roots, result); } }, function (err) { errors_1.onUnexpectedExternalError(err); }); }); return Promise.all(promises).then(function () { var flatEntries = []; if (token.isCancellationRequested) { return flatEntries; } if (flat) { flatten(flatEntries, roots, ''); } else { flatEntries = roots; } flatEntries.sort(compareEntriesUsingStart); return flatEntries; }); } 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, 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); } } } editorExtensions_1.registerLanguageCommand('_executeDocumentSymbolProvider', function (accessor, args) { var resource = args.resource; if (!(resource instanceof uri_1.URI)) { throw errors_1.illegalArgument('resource'); } var model = accessor.get(modelService_1.IModelService).getModel(resource); if (model) { return getDocumentSymbols(model, false, cancellation_1.CancellationToken.None); } return accessor.get(resolverService_1.ITextModelService).createModelReference(resource).then(function (reference) { return new Promise(function (resolve, reject) { try { var result = getDocumentSymbols(reference.object.textEditorModel, false, cancellation_1.CancellationToken.None); resolve(result); } catch (err) { reject(err); } }).finally(function () { reference.dispose(); }); }); }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[488/*vs/editor/contrib/smartSelect/smartSelect*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,24/*vs/base/common/cancellation*/,11/*vs/editor/browser/editorExtensions*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,21/*vs/editor/common/editorContextKeys*/,16/*vs/editor/common/modes*/,350/*vs/nls!vs/editor/contrib/smartSelect/smartSelect*/,2/*vs/base/common/lifecycle*/,265/*vs/editor/contrib/smartSelect/wordSelections*/,201/*vs/editor/contrib/smartSelect/bracketSelections*/,27/*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.getId = function () { return SmartSelectController._id; }; 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: null, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 512 /* Alt */ | 17 /* RightArrow */, mac: { primary: 2048 /* CtrlCmd */ | 256 /* WinCtrl */ | 1024 /* Shift */ | 17 /* RightArrow */ }, weight: 100 /* EditorContrib */ }, menubarOpts: { menuId: 22 /* 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: null, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 512 /* Alt */ | 15 /* LeftArrow */, mac: { primary: 2048 /* CtrlCmd */ | 256 /* WinCtrl */ | 1024 /* Shift */ | 15 /* LeftArrow */ }, weight: 100 /* EditorContrib */ }, menubarOpts: { menuId: 22 /* MenubarSelectionMenu */, group: '1_basic', title: nls.localize(3, null), order: 3 } }) || this; } return ShrinkSelectionAction; }(AbstractSmartSelect)); editorExtensions_1.registerEditorContribution(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)) { 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)) { oneRangesWithTrivia.push(rangeFull); } } oneRangesWithTrivia.push(cur); } return oneRangesWithTrivia; }); }); } exports.provideSelectionRanges = provideSelectionRanges; editorExtensions_1.registerDefaultLanguageCommand('_executeSelectionRangeProvider', function (model, _position, args) { return provideSelectionRanges(model, args.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[100/*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*/,11/*vs/editor/browser/editorExtensions*/,16/*vs/editor/common/modes*/,18/*vs/platform/contextkey/common/contextkey*/,24/*vs/base/common/cancellation*/,3/*vs/editor/common/core/range*/,65/*vs/base/common/filters*/]), function (require, exports, async_1, objects_1, errors_1, editorExtensions_1, modes, contextkey_1, cancellation_1, range_1, filters_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) { this.position = position; this.completion = completion; this.container = container; this.provider = provider; // sorting, filtering this.score = filters_1.FuzzyScore.Default; this.distance = 0; // ensure lower-variants (perf) this.labelLow = completion.label.toLowerCase(); this.sortTextLow = completion.sortText && completion.sortText.toLowerCase(); this.filterTextLow = completion.filterText && completion.filterText.toLowerCase(); // create the suggestion resolver var resolveCompletionItem = provider.resolveCompletionItem; if (typeof resolveCompletionItem !== 'function') { this.resolve = function () { return Promise.resolve(); }; } else { var cached_1; this.resolve = function (token) { if (!cached_1) { var isDone_1 = false; cached_1 = Promise.resolve(resolveCompletionItem.call(provider, model, position, completion, token)).then(function (value) { objects_1.assign(completion, value); isDone_1 = 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 (!isDone_1) { // 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 allSuggestions = []; var wordUntil = model.getWordUntilPosition(position); var defaultRange = new range_1.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]); } // add suggestions from contributed providers - providers are ordered in groups of // equal score and once a group produces a result the process stops var hasResult = false; 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 = defaultRange; } allSuggestions.push(new CompletionItem(position, suggestion, container, provider, model)); } } } 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) { 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) { var result = { incomplete: false, suggestions: [] }; var resolving = []; var maxItemsToResolve = args['maxItemsToResolve'] || 0; return provideSuggestionItems(model, position).then(function (items) { for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { var 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); } }).then(function () { return Promise.all(resolving); }).then(function () { return result; }); }); 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[164/*vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/], __M([0/*require*/,1/*exports*/,354/*vs/nls!vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/,47/*vs/base/browser/ui/aria/aria*/,11/*vs/editor/browser/editorExtensions*/,112/*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: null, 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[491/*vs/editor/contrib/tokenization/tokenization*/], __M([0/*require*/,1/*exports*/,355/*vs/nls!vs/editor/contrib/tokenization/tokenization*/,11/*vs/editor/browser/editorExtensions*/,122/*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: null }) || this; } ForceRetokenizeAction.prototype.run = function (accessor, editor) { if (!editor.hasModel()) { return; } var model = editor.getModel(); model.flushTokens(); 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[162/*vs/editor/contrib/wordOperations/wordOperations*/], __M([0/*require*/,1/*exports*/,11/*vs/editor/browser/editorExtensions*/,77/*vs/editor/common/commands/replaceCommand*/,38/*vs/editor/common/controller/cursorCommon*/,127/*vs/editor/common/controller/cursorWordOperations*/,83/*vs/editor/common/controller/wordCharacterClassifier*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,21/*vs/editor/common/editorContextKeys*/]), function (require, exports, editorExtensions_1, replaceCommand_1, cursorCommon_1, cursorWordOperations_1, wordCharacterClassifier_1, position_1, range_1, selection_1, editorContextKeys_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 config = editor.getConfiguration(); var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(config.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: null, 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: null }) || 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: null }) || 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: null, 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: null }) || this; } return CursorWordEndLeftSelect; }(WordLeftCommand)); exports.CursorWordEndLeftSelect = CursorWordEndLeftSelect; var CursorWordLeftSelect = /** @class */ (function (_super) { __extends(CursorWordLeftSelect, _super); function CursorWordLeftSelect() { return _super.call(this, { inSelectionMode: true, wordNavigationType: 0 /* WordStart */, id: 'cursorWordLeftSelect', precondition: null }) || this; } return CursorWordLeftSelect; }(WordLeftCommand)); exports.CursorWordLeftSelect = CursorWordLeftSelect; var CursorWordStartRight = /** @class */ (function (_super) { __extends(CursorWordStartRight, _super); function CursorWordStartRight() { return _super.call(this, { inSelectionMode: false, wordNavigationType: 0 /* WordStart */, id: 'cursorWordStartRight', precondition: null }) || 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: null, 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: null }) || 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: null }) || 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: null, 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: null }) || this; } return CursorWordRightSelect; }(WordRightCommand)); exports.CursorWordRightSelect = CursorWordRightSelect; 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 config = editor.getConfiguration(); var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(config.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 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[493/*vs/editor/contrib/wordPartOperations/wordPartOperations*/], __M([0/*require*/,1/*exports*/,11/*vs/editor/browser/editorExtensions*/,127/*vs/editor/common/controller/cursorWordOperations*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/editorContextKeys*/,162/*vs/editor/contrib/wordOperations/wordOperations*/,27/*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: null, 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: null, 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: null, 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: null, 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[494/*vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/browser/editorExtensions*/,371/*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 () { function IPadShowKeyboard(editor) { var _this = this; this.editor = editor; this.toDispose = []; if (browser.isIPad) { this.toDispose.push(editor.onDidChangeConfiguration(function () { return _this.update(); })); this.update(); } } IPadShowKeyboard.prototype.update = function () { var shouldHaveWidget = (!this.editor.getConfiguration().readOnly); if (!this.widget && shouldHaveWidget) { this.widget = new ShowKeyboardWidget(this.editor); } else if (this.widget && !shouldHaveWidget) { this.widget.dispose(); this.widget = null; } }; IPadShowKeyboard.prototype.getId = function () { return IPadShowKeyboard.ID; }; IPadShowKeyboard.prototype.dispose = function () { this.toDispose = lifecycle_1.dispose(this.toDispose); if (this.widget) { this.widget.dispose(); this.widget = null; } }; IPadShowKeyboard.ID = 'editor.contrib.iPadShowKeyboard'; return IPadShowKeyboard; }()); exports.IPadShowKeyboard = IPadShowKeyboard; var ShowKeyboardWidget = /** @class */ (function () { function ShowKeyboardWidget(editor) { var _this = this; this.editor = editor; this._domNode = document.createElement('textarea'); this._domNode.className = 'iPadShowKeyboard'; this._toDispose = []; this._toDispose.push(dom.addDisposableListener(this._domNode, 'touchstart', function (e) { _this.editor.focus(); })); this._toDispose.push(dom.addDisposableListener(this._domNode, 'focus', function (e) { _this.editor.focus(); })); this.editor.addOverlayWidget(this); } ShowKeyboardWidget.prototype.dispose = function () { this.editor.removeOverlayWidget(this); this._toDispose = lifecycle_1.dispose(this._toDispose); }; // ----- 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; }()); editorExtensions_1.registerEditorContribution(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[495/*vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast*/], __M([0/*require*/,1/*exports*/,11/*vs/editor/browser/editorExtensions*/,82/*vs/editor/standalone/common/standaloneThemeService*/,50/*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: null }) || 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[23/*vs/platform/theme/common/colorRegistry*/], __M([0/*require*/,1/*exports*/,40/*vs/platform/registry/common/platform*/,28/*vs/base/common/color*/,4/*vs/base/common/event*/,361/*vs/nls!vs/platform/theme/common/colorRegistry*/,215/*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', default: '#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: '#007ACC', light: '#007ACC', hc: exports.activeContrastBorder }, nls.localize(11, null)); exports.inputValidationInfoBackground = registerColor('inputValidation.infoBackground', { dark: '#063B49', light: '#D6ECF2', hc: color_1.Color.black }, nls.localize(12, null)); exports.inputValidationInfoForeground = registerColor('inputValidation.infoForeground', { dark: null, light: null, hc: null }, nls.localize(13, null)); exports.inputValidationInfoBorder = registerColor('inputValidation.infoBorder', { dark: '#007acc', light: '#007acc', hc: exports.contrastBorder }, nls.localize(14, null)); exports.inputValidationWarningBackground = registerColor('inputValidation.warningBackground', { dark: '#352A05', light: '#F6F5D2', hc: color_1.Color.black }, nls.localize(15, null)); exports.inputValidationWarningForeground = registerColor('inputValidation.warningForeground', { dark: null, light: null, hc: null }, nls.localize(16, null)); exports.inputValidationWarningBorder = registerColor('inputValidation.warningBorder', { dark: '#B89500', light: '#B89500', hc: exports.contrastBorder }, nls.localize(17, null)); exports.inputValidationErrorBackground = registerColor('inputValidation.errorBackground', { dark: '#5A1D1D', light: '#F2DEDE', hc: color_1.Color.black }, nls.localize(18, null)); exports.inputValidationErrorForeground = registerColor('inputValidation.errorForeground', { dark: null, light: null, hc: null }, nls.localize(19, null)); exports.inputValidationErrorBorder = registerColor('inputValidation.errorBorder', { dark: '#BE1100', light: '#BE1100', hc: exports.contrastBorder }, nls.localize(20, null)); exports.selectBackground = registerColor('dropdown.background', { dark: '#3C3C3C', light: color_1.Color.white, hc: color_1.Color.black }, nls.localize(21, null)); exports.selectForeground = registerColor('dropdown.foreground', { dark: '#F0F0F0', light: null, hc: color_1.Color.white }, nls.localize(22, null)); exports.listFocusBackground = registerColor('list.focusBackground', { dark: '#062F4A', light: '#D6EBFF', hc: null }, nls.localize(23, null)); exports.listFocusForeground = registerColor('list.focusForeground', { dark: null, light: null, hc: null }, nls.localize(24, null)); exports.listActiveSelectionBackground = registerColor('list.activeSelectionBackground', { dark: '#094771', light: '#0074E8', hc: null }, nls.localize(25, null)); exports.listActiveSelectionForeground = registerColor('list.activeSelectionForeground', { dark: color_1.Color.white, light: color_1.Color.white, hc: null }, nls.localize(26, null)); exports.listInactiveSelectionBackground = registerColor('list.inactiveSelectionBackground', { dark: '#37373D', light: '#E4E6F1', hc: null }, nls.localize(27, null)); exports.listInactiveSelectionForeground = registerColor('list.inactiveSelectionForeground', { dark: null, light: null, hc: null }, nls.localize(28, null)); exports.listInactiveFocusBackground = registerColor('list.inactiveFocusBackground', { dark: null, light: null, hc: null }, nls.localize(29, null)); exports.listHoverBackground = registerColor('list.hoverBackground', { dark: '#2A2D2E', light: '#F0F0F0', hc: null }, nls.localize(30, null)); exports.listHoverForeground = registerColor('list.hoverForeground', { dark: null, light: null, hc: null }, nls.localize(31, null)); exports.listDropBackground = registerColor('list.dropBackground', { dark: exports.listFocusBackground, light: exports.listFocusBackground, hc: null }, nls.localize(32, null)); exports.listHighlightForeground = registerColor('list.highlightForeground', { dark: '#0097fb', light: '#0066BF', hc: exports.focusBorder }, nls.localize(33, null)); exports.listFilterWidgetBackground = registerColor('listFilterWidget.background', { light: '#efc1ad', dark: '#653723', hc: color_1.Color.black }, nls.localize(34, null)); exports.listFilterWidgetOutline = registerColor('listFilterWidget.outline', { dark: color_1.Color.transparent, light: color_1.Color.transparent, hc: '#f38518' }, nls.localize(35, null)); exports.listFilterWidgetNoMatchesOutline = registerColor('listFilterWidget.noMatchesOutline', { dark: '#BE1100', light: '#BE1100', hc: exports.contrastBorder }, nls.localize(36, null)); exports.pickerGroupForeground = registerColor('pickerGroup.foreground', { dark: '#3794FF', light: '#0066BF', hc: color_1.Color.white }, nls.localize(37, null)); exports.pickerGroupBorder = registerColor('pickerGroup.border', { dark: '#3F3F46', light: '#CCCEDB', hc: color_1.Color.white }, nls.localize(38, null)); exports.badgeBackground = registerColor('badge.background', { dark: '#4D4D4D', light: '#C4C4C4', hc: color_1.Color.black }, nls.localize(39, null)); exports.badgeForeground = registerColor('badge.foreground', { dark: color_1.Color.white, light: '#333', hc: color_1.Color.white }, nls.localize(40, null)); exports.scrollbarShadow = registerColor('scrollbar.shadow', { dark: '#000000', light: '#DDDDDD', hc: null }, nls.localize(41, 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(42, 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(43, 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(44, null)); exports.progressBarBackground = registerColor('progressBar.background', { dark: color_1.Color.fromHex('#0E70C0'), light: color_1.Color.fromHex('#0E70C0'), hc: exports.contrastBorder }, nls.localize(45, null)); exports.menuBorder = registerColor('menu.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(46, null)); exports.menuForeground = registerColor('menu.foreground', { dark: exports.selectForeground, light: exports.foreground, hc: exports.selectForeground }, nls.localize(47, null)); exports.menuBackground = registerColor('menu.background', { dark: exports.selectBackground, light: exports.selectBackground, hc: exports.selectBackground }, nls.localize(48, null)); exports.menuSelectionForeground = registerColor('menu.selectionForeground', { dark: exports.listActiveSelectionForeground, light: exports.listActiveSelectionForeground, hc: exports.listActiveSelectionForeground }, nls.localize(49, null)); exports.menuSelectionBackground = registerColor('menu.selectionBackground', { dark: exports.listActiveSelectionBackground, light: exports.listActiveSelectionBackground, hc: exports.listActiveSelectionBackground }, nls.localize(50, null)); exports.menuSelectionBorder = registerColor('menu.selectionBorder', { dark: null, light: null, hc: exports.activeContrastBorder }, nls.localize(51, null)); exports.menuSeparatorBackground = registerColor('menu.separatorBackground', { dark: '#BBBBBB', light: '#888888', hc: exports.contrastBorder }, nls.localize(52, 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(53, null)); /** * Editor foreground color. */ exports.editorForeground = registerColor('editor.foreground', { light: '#333333', dark: '#BBBBBB', hc: color_1.Color.white }, nls.localize(54, null)); /** * Editor widgets */ exports.editorWidgetBackground = registerColor('editorWidget.background', { dark: '#252526', light: '#F3F3F3', hc: '#0C141F' }, nls.localize(55, null)); exports.editorWidgetBorder = registerColor('editorWidget.border', { dark: '#454545', light: '#C8C8C8', hc: exports.contrastBorder }, nls.localize(56, null)); exports.editorWidgetResizeBorder = registerColor('editorWidget.resizeBorder', { light: null, dark: null, hc: null }, nls.localize(57, null)); /** * Editor selection colors. */ exports.editorSelectionBackground = registerColor('editor.selectionBackground', { light: '#ADD6FF', dark: '#264F78', hc: '#f3f518' }, nls.localize(58, null)); exports.editorSelectionForeground = registerColor('editor.selectionForeground', { light: null, dark: null, hc: '#000000' }, nls.localize(59, 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(60, 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(61, null), true); exports.editorSelectionHighlightBorder = registerColor('editor.selectionHighlightBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(62, null)); /** * Editor find match colors. */ exports.editorFindMatch = registerColor('editor.findMatchBackground', { light: '#A8AC94', dark: '#515C6A', hc: null }, nls.localize(63, null)); exports.editorFindMatchHighlight = registerColor('editor.findMatchHighlightBackground', { light: '#EA5C0055', dark: '#EA5C0055', hc: null }, nls.localize(64, null), true); exports.editorFindRangeHighlight = registerColor('editor.findRangeHighlightBackground', { dark: '#3a3d4166', light: '#b4b4b44d', hc: null }, nls.localize(65, null), true); exports.editorFindMatchBorder = registerColor('editor.findMatchBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(66, null)); exports.editorFindMatchHighlightBorder = registerColor('editor.findMatchHighlightBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(67, null)); exports.editorFindRangeHighlightBorder = registerColor('editor.findRangeHighlightBorder', { dark: null, light: null, hc: transparent(exports.activeContrastBorder, 0.4) }, nls.localize(68, null), true); /** * Editor hover */ exports.editorHoverHighlight = registerColor('editor.hoverHighlightBackground', { light: '#ADD6FF26', dark: '#264f7840', hc: '#ADD6FF26' }, nls.localize(69, null), true); exports.editorHoverBackground = registerColor('editorHoverWidget.background', { light: exports.editorWidgetBackground, dark: exports.editorWidgetBackground, hc: exports.editorWidgetBackground }, nls.localize(70, null)); exports.editorHoverBorder = registerColor('editorHoverWidget.border', { light: exports.editorWidgetBorder, dark: exports.editorWidgetBorder, hc: exports.editorWidgetBorder }, nls.localize(71, null)); exports.editorHoverStatusBarBackground = registerColor('editorHoverWidget.statusBarBackground', { dark: lighten(exports.editorHoverBackground, 0.2), light: darken(exports.editorHoverBackground, 0.05), hc: exports.editorWidgetBackground }, nls.localize(72, null)); /** * Editor link colors */ exports.editorActiveLinkForeground = registerColor('editorLink.activeForeground', { dark: '#4E94CE', light: color_1.Color.blue, hc: color_1.Color.cyan }, nls.localize(73, 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(74, null), true); exports.diffRemoved = registerColor('diffEditor.removedTextBackground', { dark: exports.defaultRemoveColor, light: exports.defaultRemoveColor, hc: null }, nls.localize(75, null), true); exports.diffInsertedOutline = registerColor('diffEditor.insertedTextBorder', { dark: null, light: null, hc: '#33ff2eff' }, nls.localize(76, null)); exports.diffRemovedOutline = registerColor('diffEditor.removedTextBorder', { dark: null, light: null, hc: '#FF008F' }, nls.localize(77, null)); exports.diffBorder = registerColor('diffEditor.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(78, 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(79, null)); exports.snippetTabstopHighlightBorder = registerColor('editor.snippetTabstopHighlightBorder', { dark: null, light: null, hc: null }, nls.localize(80, null)); exports.snippetFinalTabstopHighlightBackground = registerColor('editor.snippetFinalTabstopHighlightBackground', { dark: null, light: null, hc: null }, nls.localize(81, 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(82, null)); var findMatchColorDefault = new color_1.Color(new color_1.RGBA(246, 185, 77, 0.7)); exports.overviewRulerFindMatchForeground = registerColor('editorOverviewRuler.findMatchForeground', { dark: findMatchColorDefault, light: findMatchColorDefault, hc: findMatchColorDefault }, nls.localize(83, null), true); exports.overviewRulerSelectionHighlightForeground = registerColor('editorOverviewRuler.selectionHighlightForeground', { dark: '#A0A0A0CC', light: '#A0A0A0CC', hc: '#A0A0A0CC' }, nls.localize(84, null), true); // ----- 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.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[497/*vs/editor/contrib/rename/renameInputField*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,349/*vs/nls!vs/editor/contrib/rename/renameInputField*/,18/*vs/platform/contextkey/common/contextkey*/,23/*vs/platform/theme/common/colorRegistry*/,377/*vs/css!vs/editor/contrib/rename/renameInputField*/]), function (require, exports, lifecycle_1, position_1, range_1, nls_1, contextkey_1, colorRegistry_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, themeService, contextKeyService) { var _this = this; this.themeService = themeService; this._disposables = []; // Editor.IContentWidget.allowEditorOverflow this.allowEditorOverflow = true; this._currentAcceptInput = null; this._currentCancelInput = null; this._visibleContextKey = exports.CONTEXT_RENAME_INPUT_VISIBLE.bindTo(contextKeyService); this._editor = editor; this._editor.addContentWidget(this); this._disposables.push(editor.onDidChangeConfiguration(function (e) { if (e.fontInfo) { _this.updateFont(); } })); this._disposables.push(themeService.onThemeChange(function (theme) { return _this.onThemeChange(theme); })); } RenameInputField.prototype.onThemeChange = function (theme) { this.updateStyles(theme); }; RenameInputField.prototype.dispose = function () { this._disposables = lifecycle_1.dispose(this._disposables); this._editor.removeContentWidget(this); }; RenameInputField.prototype.getId = function () { return '__renameInputWidget'; }; RenameInputField.prototype.getDomNode = function () { if (!this._domNode) { this._inputField = document.createElement('input'); this._inputField.className = 'rename-input'; this._inputField.type = 'text'; this._inputField.setAttribute('aria-label', nls_1.localize(0, null)); this._domNode = document.createElement('div'); this._domNode.style.height = this._editor.getConfiguration().lineHeight + "px"; this._domNode.className = 'monaco-editor rename-box'; this._domNode.appendChild(this._inputField); this.updateFont(); this.updateStyles(this.themeService.getTheme()); } return this._domNode; }; RenameInputField.prototype.updateStyles = function (theme) { if (!this._inputField) { return; } var background = theme.getColor(colorRegistry_1.inputBackground); var foreground = theme.getColor(colorRegistry_1.inputForeground); var widgetShadowColor = theme.getColor(colorRegistry_1.widgetShadow); var border = theme.getColor(colorRegistry_1.inputBorder); this._inputField.style.backgroundColor = background ? background.toString() : null; this._inputField.style.color = foreground ? foreground.toString() : null; this._inputField.style.borderWidth = border ? '1px' : '0px'; this._inputField.style.borderStyle = border ? 'solid' : 'none'; this._inputField.style.borderColor = border ? border.toString() : 'none'; this._domNode.style.boxShadow = widgetShadowColor ? " 0 2px 8px " + widgetShadowColor : null; }; RenameInputField.prototype.updateFont = function () { if (!this._inputField) { return; } var fontInfo = this._editor.getConfiguration().fontInfo; this._inputField.style.fontFamily = fontInfo.fontFamily; this._inputField.style.fontWeight = fontInfo.fontWeight; this._inputField.style.fontSize = fontInfo.fontSize + "px"; }; RenameInputField.prototype.getPosition = function () { return this._visible ? { position: this._position, preference: [2 /* BELOW */, 1 /* ABOVE */] } : null; }; RenameInputField.prototype.acceptInput = function () { if (this._currentAcceptInput) { this._currentAcceptInput(); } }; RenameInputField.prototype.cancelInput = function (focusEditor) { if (this._currentCancelInput) { this._currentCancelInput(focusEditor); } }; RenameInputField.prototype.getInput = function (where, value, selectionStart, selectionEnd) { var _this = this; this._position = new position_1.Position(where.startLineNumber, where.startColumn); this._inputField.value = value; this._inputField.setAttribute('selectionStart', selectionStart.toString()); this._inputField.setAttribute('selectionEnd', selectionEnd.toString()); this._inputField.size = Math.max((where.endColumn - where.startColumn) * 1.1, 20); var disposeOnDone = []; var always = function () { lifecycle_1.dispose(disposeOnDone); _this._hide(); }; return new Promise(function (resolve) { _this._currentCancelInput = function (focusEditor) { _this._currentAcceptInput = null; _this._currentCancelInput = null; resolve(focusEditor); return true; }; _this._currentAcceptInput = function () { if (_this._inputField.value.trim().length === 0 || _this._inputField.value === value) { // empty or whitespace only or not changed _this.cancelInput(true); return; } _this._currentAcceptInput = null; _this._currentCancelInput = null; resolve(_this._inputField.value); }; var onCursorChanged = function () { var editorPosition = _this._editor.getPosition(); if (!editorPosition || !range_1.Range.containsPosition(where, editorPosition)) { _this.cancelInput(true); } }; disposeOnDone.push(_this._editor.onDidChangeCursorSelection(onCursorChanged)); disposeOnDone.push(_this._editor.onDidBlurEditorWidget(function () { return _this.cancelInput(false); })); _this._show(); }).then(function (newValue) { always(); return newValue; }, function (err) { always(); return Promise.reject(err); }); }; 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._inputField.focus(); _this._inputField.setSelectionRange(parseInt(_this._inputField.getAttribute('selectionStart')), parseInt(_this._inputField.getAttribute('selectionEnd'))); }, 100); }; RenameInputField.prototype._hide = function () { this._visible = false; this._visibleContextKey.reset(); this._editor.layoutContentWidget(this); }; 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[85/*vs/platform/theme/common/styler*/], __M([0/*require*/,1/*exports*/,23/*vs/platform/theme/common/colorRegistry*/,31/*vs/base/common/objects*/]), function (require, exports, colorRegistry_1, objects_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 (typeof value === 'string') { styles[key] = theme.getColor(value); } else if (typeof value === 'function') { styles[key] = 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, objects_1.mixin(overrides || Object.create(null), exports.defaultListStyles, false), 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 }; 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({}, 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[499/*vs/editor/standalone/browser/quickOpen/quickOpenEditorWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,300/*vs/base/parts/quickopen/browser/quickOpenWidget*/,23/*vs/platform/theme/common/colorRegistry*/,85/*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.create(onOk, onCancel, onType, configuration); } QuickOpenEditorWidget.prototype.create = function (onOk, onCancel, onType, configuration) { 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[500/*vs/platform/contextview/browser/contextMenuHandler*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,49/*vs/base/common/actions*/,286/*vs/base/browser/ui/menu/menu*/,7/*vs/base/browser/dom*/,85/*vs/platform/theme/common/styler*/,62/*vs/base/browser/event*/,43/*vs/base/browser/mouseEvent*/,364/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/]), function (require, exports, lifecycle_1, actions_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.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 = []; 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, { actionItemProvider: delegate.getActionItem, context: delegate.getActionsContext ? delegate.getActionsContext() : null, actionRunner: actionRunner, getKeyBinding: delegate.getKeyBinding ? delegate.getKeyBinding : function (action) { return _this.keybindingService.lookupKeybinding(action.id); } }); menuDisposables.push(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) { 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.concat([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) { /* __GDPR__ "workbenchActionExecuted" : { "id" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "from": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('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*/,13/*vs/platform/instantiation/common/instantiation*/,2/*vs/base/common/lifecycle*/,40/*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[502/*vs/editor/browser/services/codeEditorServiceImpl*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,25/*vs/base/common/uri*/,308/*vs/editor/browser/services/abstractCodeEditorService*/,70/*vs/editor/common/editorCommon*/,45/*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 CodeEditorServiceImpl = /** @class */ (function (_super) { __extends(CodeEditorServiceImpl, _super); function CodeEditorServiceImpl(themeService, styleSheet) { if (styleSheet === void 0) { styleSheet = dom.createStyleSheet(); } var _this = _super.call(this) || this; _this._styleSheet = styleSheet; _this._decorationOptionProviders = Object.create(null); _this._themeService = themeService; return _this; } CodeEditorServiceImpl.prototype.registerDecorationType = function (key, options, parentTypeKey) { var provider = this._decorationOptionProviders[key]; if (!provider) { var providerArgs = { styleSheet: this._styleSheet, key: key, parentTypeKey: parentTypeKey, options: options || Object.create(null) }; if (!parentTypeKey) { provider = new DecorationTypeOptionsProvider(this._themeService, providerArgs); } else { provider = new DecorationSubTypeOptionsProvider(this._themeService, providerArgs); } this._decorationOptionProviders[key] = provider; } provider.refCount++; }; CodeEditorServiceImpl.prototype.removeDecorationType = function (key) { var provider = this._decorationOptionProviders[key]; if (provider) { provider.refCount--; if (provider.refCount <= 0) { delete this._decorationOptionProviders[key]; provider.dispose(); this.listCodeEditors().forEach(function (ed) { return ed.removeDecorations(key); }); } } }; CodeEditorServiceImpl.prototype.resolveDecorationOptions = function (decorationTypeKey, writable) { var provider = this._decorationOptionProviders[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, providerArgs) { 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; } }; return DecorationSubTypeOptionsProvider; }()); var DecorationTypeOptionsProvider = /** @class */ (function () { function DecorationTypeOptionsProvider(themeService, providerArgs) { var _this = this; this.refCount = 0; this._disposables = []; var createCSSRules = function (type) { var rules = new DecorationCSSRules(type, providerArgs, themeService); _this._disposables.push(rules); if (rules.hasContent) { return rules.className; } return undefined; }; var createInlineCSSRules = function (type) { var rules = new DecorationCSSRules(type, providerArgs, themeService); _this._disposables.push(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 = lifecycle_1.dispose(this._disposables); }; 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:url(\'{0}\') center center no-repeat;', gutterIconSize: 'background-size:{0};', contentText: 'content:\'{0}\';', contentIconPath: 'content:url(\'{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, uri_1.URI.revive(opts.contentIconPath).toString(true).replace(/'/g, '%27'))); } 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, uri_1.URI.revive(opts.gutterIconPath).toString(true).replace(/'/g, '%27'))); 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[503/*vs/editor/browser/viewParts/editorScrollbar/editorScrollbar*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,26/*vs/base/browser/fastDomNode*/,51/*vs/base/browser/ui/scrollbar/scrollableElement*/,33/*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 editor = _this._context.configuration.editor; var configScrollbarOpts = editor.viewInfo.scrollbar; var scrollbarOptions = { listenOnDomNode: viewDomNode.domNode, className: 'editor-scrollable' + ' ' + themeService_1.getThemeTypeSelector(context.theme.type), useShadows: false, lazyRender: true, vertical: configScrollbarOpts.vertical, horizontal: configScrollbarOpts.horizontal, verticalHasArrows: configScrollbarOpts.verticalHasArrows, horizontalHasArrows: configScrollbarOpts.horizontalHasArrows, verticalScrollbarSize: configScrollbarOpts.verticalScrollbarSize, verticalSliderSize: configScrollbarOpts.verticalSliderSize, horizontalScrollbarSize: configScrollbarOpts.horizontalScrollbarSize, horizontalSliderSize: configScrollbarOpts.horizontalSliderSize, handleMouseWheel: configScrollbarOpts.handleMouseWheel, arrowSize: configScrollbarOpts.arrowSize, mouseWheelScrollSensitivity: configScrollbarOpts.mouseWheelScrollSensitivity, fastScrollSensitivity: configScrollbarOpts.fastScrollSensitivity, }; _this.scrollbar = _this._register(new scrollableElement_1.SmoothScrollableElement(linesContent.domNode, scrollbarOptions, _this._context.viewLayout.scrollable)); 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 layoutInfo = this._context.configuration.editor.layoutInfo; this.scrollbarDomNode.setLeft(layoutInfo.contentLeft); var side = this._context.configuration.editor.viewInfo.minimap.side; if (side === 'right') { this.scrollbarDomNode.setWidth(layoutInfo.contentWidth + layoutInfo.minimapWidth); } else { this.scrollbarDomNode.setWidth(layoutInfo.contentWidth); } this.scrollbarDomNode.setHeight(layoutInfo.contentHeight); }; 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.viewInfo) { var editor = this._context.configuration.editor; var newOpts = { handleMouseWheel: editor.viewInfo.scrollbar.handleMouseWheel, mouseWheelScrollSensitivity: editor.viewInfo.scrollbar.mouseWheelScrollSensitivity, fastScrollSensitivity: editor.viewInfo.scrollbar.fastScrollSensitivity }; this.scrollbar.updateOptions(newOpts); } if (e.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[218/*vs/editor/browser/viewParts/lines/viewLine*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,26/*vs/base/browser/fastDomNode*/,17/*vs/base/common/platform*/,245/*vs/editor/browser/viewParts/lines/rangeUtil*/,88/*vs/editor/common/view/renderingContext*/,154/*vs/editor/common/viewLayout/lineDecorations*/,108/*vs/editor/common/viewLayout/viewLineRenderer*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, browser, fastDomNode_1, platform, rangeUtil_1, renderingContext_1, lineDecorations_1, viewLineRenderer_1, themeService_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; this.renderWhitespace = config.editor.viewInfo.renderWhitespace; this.renderControlCharacters = config.editor.viewInfo.renderControlCharacters; this.spaceWidth = config.editor.fontInfo.spaceWidth; this.useMonospaceOptimizations = (config.editor.fontInfo.isMonospace && !config.editor.viewInfo.disableMonospaceOptimizations); this.canUseHalfwidthRightwardsArrow = config.editor.fontInfo.canUseHalfwidthRightwardsArrow; this.lineHeight = config.editor.lineHeight; this.stopRenderingLineAfter = config.editor.viewInfo.stopRenderingLineAfter; this.fontLigatures = config.editor.viewInfo.fontLigatures; } ViewLineOptions.prototype.equals = function (other) { return (this.themeType === other.themeType && this.renderWhitespace === other.renderWhitespace && this.renderControlCharacters === other.renderControlCharacters && this.spaceWidth === other.spaceWidth && 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._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); if (alwaysRenderInlineSelection || options.themeType === themeService_1.HIGH_CONTRAST) { 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) { actualInlineDecorations.push(new lineDecorations_1.LineDecoration(startColumn, endColumn, 'inline-selected-text', 0 /* Regular */)); } } } 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, options.spaceWidth, options.stopRenderingLineAfter, options.renderWhitespace, options.renderControlCharacters, options.fontLigatures); 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 if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter && endColumn > stopRenderingLineAfter) { // This range is obviously not visible return null; } if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter) { startColumn = stopRenderingLineAfter; } if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter) { endColumn = stopRenderingLineAfter; } return this._renderedViewLine.getVisibleRangesForRange(startColumn, endColumn, context); }; 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 () { return this.domNode.domNode.firstChild; }; /** * Width of the line in pixels */ RenderedViewLine.prototype.getWidth = function () { if (this._cachedWidth === -1) { this._cachedWidth = this._getReadingTarget().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._pixelOffsetCache !== null) { // the text is LTR var startOffset = this._readPixelOffset(startColumn, context); if (startOffset === -1) { return null; } var endOffset = this._readPixelOffset(endColumn, context); if (endOffset === -1) { return null; } return [new renderingContext_1.HorizontalRange(startOffset, endOffset - startOffset)]; } return this._readVisibleRangesForRange(startColumn, endColumn, context); }; RenderedViewLine.prototype._readVisibleRangesForRange = function (startColumn, endColumn, context) { if (startColumn === endColumn) { var pixelOffset = this._readPixelOffset(startColumn, context); if (pixelOffset === -1) { return null; } else { return [new renderingContext_1.HorizontalRange(pixelOffset, 0)]; } } else { return this._readRawVisibleRangesForRange(startColumn, endColumn, context); } }; RenderedViewLine.prototype._readPixelOffset = function (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 element before the (empty) line return this.getWidth(); } } if (this._pixelOffsetCache !== null) { // the text is LTR var cachedPixelOffset = this._pixelOffsetCache[column]; if (cachedPixelOffset !== -1) { return cachedPixelOffset; } var result = this._actualReadPixelOffset(column, context); this._pixelOffsetCache[column] = result; return result; } return this._actualReadPixelOffset(column, context); }; RenderedViewLine.prototype._actualReadPixelOffset = function (column, context) { if (this._characterMapping.length === 0) { // This line has no content var r_1 = rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(), 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(), partIndex, charOffsetInPart, partIndex, charOffsetInPart, context.clientRectDeltaLeft, context.endNode); if (!r || r.length === 0) { return -1; } return r[0].left; }; RenderedViewLine.prototype._readRawVisibleRangesForRange = function (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(), 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 (startColumn, endColumn, context) { var output = _super.prototype._readVisibleRangesForRange.call(this, 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(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[217/*vs/editor/browser/controller/mouseTarget*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,113/*vs/editor/browser/editorDom*/,33/*vs/editor/browser/view/viewPart*/,218/*vs/editor/browser/viewParts/lines/viewLine*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, browser, editorDom_1, viewPart_1, viewLine_1, position_1, range_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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, lastViewCursorsRenderData) { this.model = context.model; this.layoutInfo = context.configuration.editor.layoutInfo; this.viewDomNode = viewHelper.viewDomNode; this.lineHeight = context.configuration.editor.lineHeight; this.typicalHalfwidthCharacterWidth = context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth; this.lastViewCursorsRenderData = lastViewCursorsRenderData; 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.visibleRangeForPosition2 = function (lineNumber, column) { return this._viewHelper.visibleRangeForPosition2(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; } return new MouseTarget(this.target, type, this.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 (lastViewCursorsRenderData, editorPos, pos, target) { var ctx = new HitTestContext(this._context, this._viewHelper, lastViewCursorsRenderData); 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.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.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)) { return request.fulfill(1 /* TEXTAREA */); } 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 = ctx.getLineWidth(lineNumber); var detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); return request.fulfill(7 /* CONTENT_EMPTY */, new position_1.Position(lineNumber, 1), 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 layoutInfo = this._context.configuration.editor.layoutInfo; var mouseContentHorizontalOffset = this._context.viewLayout.getCurrentScrollLeft() + pos.x - editorPos.x - layoutInfo.contentLeft; return MouseTargetFactory._getMouseColumn(mouseContentHorizontalOffset, this._context.configuration.editor.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.visibleRangeForPosition2(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.visibleRangeForPosition2(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.visibleRangeForPosition2(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 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 (document.caretRangeFromPoint) { 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; }); /*--------------------------------------------------------------------------------------------- * 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/editor/browser/controller/mouseHandler*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,43/*vs/base/browser/mouseEvent*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,217/*vs/editor/browser/controller/mouseTarget*/,113/*vs/editor/browser/editorDom*/,101/*vs/editor/common/config/editorZoom*/,12/*vs/editor/common/core/position*/,22/*vs/editor/common/core/selection*/,86/*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; }; } 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.editor.viewInfo.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, 'mousewheel', onMouseWheel, true)); _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; } var lastViewCursorsRenderData = this.viewHelper.getLastViewCursorsRenderData(); return this.mouseTargetFactory.createMouseTarget(lastViewCursorsRenderData, editorPos, pos, null); }; MouseHandler.prototype._createMouseTarget = function (e, testEventTarget) { var lastViewCursorsRenderData = this.viewHelper.getLastViewCursorsRenderData(); return this.mouseTargetFactory.createMouseTarget(lastViewCursorsRenderData, 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.editor.viewInfo.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; if (!this._context.configuration.editor.readOnly && this._context.configuration.editor.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(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(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[507/*vs/editor/browser/controller/pointerHandler*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,78/*vs/base/browser/touch*/,506/*vs/editor/browser/controller/mouseHandler*/,113/*vs/editor/browser/editorDom*/]), function (require, exports, dom, touch_1, mouseHandler_1, editorDom_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)); var TouchHandler = /** @class */ (function (_super) { __extends(TouchHandler, _super); function TouchHandler(context, viewController, viewHelper) { var _this = _super.call(this, context, viewController, viewHelper) || this; 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.dispose = function () { _super.prototype.dispose.call(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 () { function PointerHandler(context, viewController, viewHelper) { if (window.navigator.msPointerEnabled) { this.handler = new MsPointerHandler(context, viewController, viewHelper); } else if (window.TouchEvent) { this.handler = new TouchHandler(context, viewController, viewHelper); } else if (window.navigator.pointerEnabled || window.PointerEvent) { this.handler = new StandardPointerHandler(context, viewController, viewHelper); } else { this.handler = new mouseHandler_1.MouseHandler(context, viewController, viewHelper); } } PointerHandler.prototype.getTargetAtClientPoint = function (clientX, clientY) { return this.handler.getTargetAtClientPoint(clientX, clientY); }; PointerHandler.prototype.dispose = function () { this.handler.dispose(); }; return PointerHandler; }()); 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[508/*vs/editor/browser/view/viewOutgoingEvents*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,217/*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.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.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 new ExternalMouseTarget(target.element, target.type, target.mouseColumn, target.position ? this._convertViewToModelPosition(target.position) : null, target.range ? this._convertViewToModelRange(target.range) : null, target.detail); }; ViewOutgoingEvents.prototype._convertViewToModelPosition = function (viewPosition) { return this._viewModel.coordinatesConverter.convertViewPositionToModelPosition(viewPosition); }; ViewOutgoingEvents.prototype._convertViewToModelRange = function (viewRange) { return this._viewModel.coordinatesConverter.convertViewRangeToModelRange(viewRange); }; 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[509/*vs/editor/browser/viewParts/lines/viewLines*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,60/*vs/editor/browser/config/configuration*/,160/*vs/editor/browser/view/viewLayer*/,33/*vs/editor/browser/view/viewPart*/,218/*vs/editor/browser/viewParts/lines/viewLine*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,88/*vs/editor/common/view/renderingContext*/,429/*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; _this._lineHeight = conf.editor.lineHeight; _this._typicalHalfwidthCharacterWidth = conf.editor.fontInfo.typicalHalfwidthCharacterWidth; _this._isViewportWrapping = conf.editor.wrappingInfo.isViewportWrapping; _this._revealHorizontalRightPadding = conf.editor.viewInfo.revealHorizontalRightPadding; _this._canUseLayerHinting = conf.editor.canUseLayerHinting; _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, conf.editor.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.wrappingInfo) { this._maxLineWidth = 0; } var conf = this._context.configuration; if (e.lineHeight) { this._lineHeight = conf.editor.lineHeight; } if (e.fontInfo) { this._typicalHalfwidthCharacterWidth = conf.editor.fontInfo.typicalHalfwidthCharacterWidth; } if (e.wrappingInfo) { this._isViewportWrapping = conf.editor.wrappingInfo.isViewportWrapping; } if (e.viewInfo) { this._revealHorizontalRightPadding = conf.editor.viewInfo.revealHorizontalRightPadding; } if (e.canUseLayerHinting) { this._canUseLayerHinting = conf.editor.canUseLayerHinting; } if (e.fontInfo) { configuration_1.Configuration.applyFontInfo(this.domNode, conf.editor.fontInfo); } this._onOptionsMaybeChanged(); if (e.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.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 || visibleRangesForLine.length === 0) { 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[visibleRangesForLine.length - 1].width += this._typicalHalfwidthCharacterWidth; } } visibleRanges[visibleRangesLen++] = new renderingContext_1.LineVisibleRanges(lineNumber, visibleRangesForLine); } if (visibleRangesLen === 0) { return null; } return visibleRanges; }; ViewLines.prototype.visibleRangesForRange2 = function (_range) { 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 range = range_1.Range.intersectRanges(_range, this._lastRenderedData.getCurrentVisibleRange()); if (!range) { return null; } var result = []; var domReadingContext = new viewLine_1.DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot); 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 || visibleRangesForLine.length === 0) { continue; } result = result.concat(visibleRangesForLine); } if (result.length === 0) { return null; } return result; }; ViewLines.prototype.visibleRangeForPosition = function (position) { var visibleRanges = this.visibleRangesForRange2(new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column)); if (!visibleRanges) { return null; } return visibleRanges[0]; }; // --- 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); 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, 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; 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 (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.visibleRangesForRange2(new range_1.Range(lineNumber, startColumn, lineNumber, endColumn)); var boxStartX = Number.MAX_VALUE; var boxEndX = 0; if (!visibleRanges) { // Unknown return { scrollLeft: viewportStartX, maxHorizontalOffset: maxHorizontalOffset }; } for (var _i = 0, visibleRanges_1 = visibleRanges; _i < visibleRanges_1.length; _i++) { var visibleRange = visibleRanges_1[_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[510/*vs/editor/browser/viewParts/minimap/minimap*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,26/*vs/base/browser/fastDomNode*/,72/*vs/base/browser/globalMouseMoveMonitor*/,17/*vs/base/common/platform*/,5/*vs/base/common/strings*/,160/*vs/editor/browser/view/viewLayer*/,33/*vs/editor/browser/view/viewPart*/,3/*vs/editor/common/core/range*/,110/*vs/editor/common/view/minimapCharRenderer*/,396/*vs/editor/common/view/runtimeMinimapCharRenderer*/,73/*vs/editor/common/view/viewEvents*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,424/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/]), function (require, exports, dom, fastDomNode_1, globalMouseMoveMonitor_1, platform, strings, viewLayer_1, viewPart_1, range_1, minimapCharRenderer_1, runtimeMinimapCharRenderer_1, viewEvents, colorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getMinimapLineHeight(renderMinimap) { if (renderMinimap === 2 /* Large */) { return 4 /* x2_CHAR_HEIGHT */; } if (renderMinimap === 4 /* LargeBlocks */) { return 4 /* x2_CHAR_HEIGHT */ + 2; } if (renderMinimap === 1 /* Small */) { return 2 /* x1_CHAR_HEIGHT */; } // RenderMinimap.SmallBlocks return 2 /* x1_CHAR_HEIGHT */ + 1; } function getMinimapCharWidth(renderMinimap) { if (renderMinimap === 2 /* Large */) { return 2 /* x2_CHAR_WIDTH */; } if (renderMinimap === 4 /* LargeBlocks */) { return 2 /* x2_CHAR_WIDTH */; } if (renderMinimap === 1 /* Small */) { return 1 /* x1_CHAR_WIDTH */; } // RenderMinimap.SmallBlocks return 1 /* x1_CHAR_WIDTH */; } /** * The orthogonal distance to the slider at which dragging "resets". This implements "snapping" */ var MOUSE_DRAG_RESET_DISTANCE = 140; var MinimapOptions = /** @class */ (function () { function MinimapOptions(configuration) { var pixelRatio = configuration.editor.pixelRatio; var layoutInfo = configuration.editor.layoutInfo; var viewInfo = configuration.editor.viewInfo; var fontInfo = configuration.editor.fontInfo; this.renderMinimap = layoutInfo.renderMinimap | 0; this.scrollBeyondLastLine = viewInfo.scrollBeyondLastLine; this.showSlider = viewInfo.minimap.showSlider; this.pixelRatio = pixelRatio; this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; this.lineHeight = configuration.editor.lineHeight; this.minimapLeft = layoutInfo.minimapLeft; this.minimapWidth = layoutInfo.minimapWidth; this.minimapHeight = layoutInfo.height; this.canvasInnerWidth = Math.max(1, Math.floor(pixelRatio * this.minimapWidth)); this.canvasInnerHeight = Math.max(1, 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.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.create = function (options, viewportStartLineNumber, viewportEndLineNumber, viewportHeight, viewportContainsWhitespaceGaps, lineCount, scrollTop, scrollHeight, previousLayout) { var pixelRatio = options.pixelRatio; var minimapLineHeight = getMinimapLineHeight(options.renderMinimap); 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); if (minimapLinesFitting >= lineCount) { // 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.renderedLayout.startLineNumber !== layout.startLineNumber) { return false; } if (this.renderedLayout.endLineNumber !== layout.endLineNumber) { 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; }; 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._options = new MinimapOptions(_this._context.configuration); _this._lastRenderData = null; _this._buffers = null; _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._slider = fastDomNode_1.createFastDomNode(document.createElement('div')); _this._slider.setPosition('absolute'); _this._slider.setClassName('minimap-slider'); _this._slider.setLayerHinting(true); _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 = minimapCharRenderer_1.MinimapTokensColorTracker.getInstance(); _this._applyLayout(); _this._mouseDownListener = dom.addStandardDisposableListener(_this._canvas.domNode, 'mousedown', function (e) { e.preventDefault(); var renderMinimap = _this._options.renderMinimap; if (renderMinimap === 0 /* None */) { return; } if (!_this._lastRenderData) { return; } var minimapLineHeight = getMinimapLineHeight(renderMinimap); 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(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(); 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(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); }); } }); return _this; } Minimap.prototype.dispose = function () { this._mouseDownListener.dispose(); this._sliderMouseMoveMonitor.dispose(); this._sliderMouseDownListener.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._slider.setWidth(this._options.minimapWidth); }; Minimap.prototype._getBuffer = function () { if (!this._buffers) { this._buffers = new MinimapBuffers(this._canvas.domNode.getContext('2d'), this._options.canvasInnerWidth, this._options.canvasInnerHeight, this._tokensColorTracker.getColor(2 /* DefaultBackground */)); } return this._buffers.getBuffer(); }; 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.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) { 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; }; // --- 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.pixelRatio)); this._sliderHorizontal.setLeft(horizontalSliderLeft); this._sliderHorizontal.setWidth(this._options.minimapWidth - horizontalSliderLeft); this._sliderHorizontal.setTop(0); this._sliderHorizontal.setHeight(layout.sliderHeight); this._lastRenderData = this.renderLines(layout); }; Minimap.prototype.renderLines = function (layout) { var renderMinimap = this._options.renderMinimap; var startLineNumber = layout.startLineNumber; var endLineNumber = layout.endLineNumber; var minimapLineHeight = getMinimapLineHeight(renderMinimap); // 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(); // 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, runtimeMinimapCharRenderer_1.getOrCreateMinimapCharRenderer(), dy, tabSize, lineInfo.data[lineIndex]); } 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) { var content = lineData.content; var tokens = lineData.tokens; var charWidth = getMinimapCharWidth(renderMinimap); var maxDx = target.width - charWidth; var dx = 0; 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 /* Large */) { minimapCharRenderer.x2RenderChar(target, dx, dy, charCode, tokenColor, backgroundColor, useLighterFont); } else if (renderMinimap === 1 /* Small */) { minimapCharRenderer.x1RenderChar(target, dx, dy, charCode, tokenColor, backgroundColor, useLighterFont); } else if (renderMinimap === 4 /* LargeBlocks */) { minimapCharRenderer.x2BlockRenderChar(target, dx, dy, tokenColor, backgroundColor, useLighterFont); } else { // RenderMinimap.SmallBlocks minimapCharRenderer.x1BlockRenderChar(target, dx, dy, tokenColor, backgroundColor, 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[511/*vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([0/*require*/,1/*exports*/,26/*vs/base/browser/fastDomNode*/,33/*vs/editor/browser/view/viewPart*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,416/*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; _this._useShadows = _this._context.configuration.editor.viewInfo.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 layoutInfo = this._context.configuration.editor.layoutInfo; var newWidth = 0; if (layoutInfo.renderMinimap === 0 || (layoutInfo.minimapWidth > 0 && layoutInfo.minimapLeft === 0)) { newWidth = layoutInfo.width; } else { newWidth = layoutInfo.width - layoutInfo.minimapWidth - layoutInfo.verticalScrollbarWidth; } if (this._width !== newWidth) { this._width = newWidth; return true; } return false; }; // --- begin event handlers ScrollDecorationViewPart.prototype.onConfigurationChanged = function (e) { var shouldRender = false; if (e.viewInfo) { this._useShadows = this._context.configuration.editor.viewInfo.scrollbar.useShadows; } if (e.layoutInfo) { shouldRender = this._updateWidth(); } return this._updateShouldShow() || shouldRender; }; 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[512/*vs/editor/browser/viewParts/selections/selections*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,71/*vs/editor/browser/view/dynamicViewOverlay*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,413/*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; _this._lineHeight = _this._context.configuration.editor.lineHeight; _this._roundedSelection = _this._context.configuration.editor.viewInfo.roundedSelection; _this._typicalHalfwidthCharacterWidth = _this._context.configuration.editor.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) { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; } if (e.viewInfo) { this._roundedSelection = this._context.configuration.editor.viewInfo.roundedSelection; } if (e.fontInfo) { this._typicalHalfwidthCharacterWidth = this._context.configuration.editor.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) { var visibleRangesHaveStyle = (visibleRanges.length > 0 && visibleRanges[0].ranges[0].startStyle); var fullLineHeight = (this._lineHeight).toString(); var reducedLineHeight = (this._lineHeight - 1).toString(); var firstLineNumber = (visibleRanges.length > 0 ? visibleRanges[0].lineNumber : 0); var lastLineNumber = (visibleRanges.length > 0 ? visibleRanges[visibleRanges.length - 1].lineNumber : 0); 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 lineOutput = ''; 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) lineOutput += 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; } lineOutput += 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) lineOutput += 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; } lineOutput += 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; } } lineOutput += this._createSelectionPiece(top_1, lineHeight, className, visibleRange.left, visibleRange.width); } output2[lineIndex] += lineOutput; } }; SelectionsOverlay.prototype.prepareRender = function (ctx) { 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; }; 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[34/*vs/editor/common/view/editorColorRegistry*/], __M([0/*require*/,1/*exports*/,313/*vs/nls!vs/editor/common/view/editorColorRegistry*/,28/*vs/base/common/color*/,23/*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.editorCursorForeground = colorRegistry_1.registerColor('editorCursor.foreground', { dark: '#AEAFAD', light: color_1.Color.black, hc: color_1.Color.white }, nls.localize(4, null)); exports.editorCursorBackground = colorRegistry_1.registerColor('editorCursor.background', null, nls.localize(5, null)); exports.editorWhitespaces = colorRegistry_1.registerColor('editorWhitespace.foreground', { dark: '#e3e4e229', light: '#33333333', hc: '#e3e4e229' }, nls.localize(6, null)); exports.editorIndentGuides = colorRegistry_1.registerColor('editorIndentGuide.background', { dark: exports.editorWhitespaces, light: exports.editorWhitespaces, hc: exports.editorWhitespaces }, nls.localize(7, null)); exports.editorActiveIndentGuides = colorRegistry_1.registerColor('editorIndentGuide.activeBackground', { dark: exports.editorWhitespaces, light: exports.editorWhitespaces, hc: exports.editorWhitespaces }, nls.localize(8, null)); exports.editorLineNumbers = colorRegistry_1.registerColor('editorLineNumber.foreground', { dark: '#858585', light: '#237893', hc: color_1.Color.white }, nls.localize(9, null)); var deprecatedEditorActiveLineNumber = colorRegistry_1.registerColor('editorActiveLineNumber.foreground', { dark: '#c6c6c6', light: '#0B216F', hc: colorRegistry_1.activeContrastBorder }, nls.localize(10, null), false, nls.localize(11, null)); exports.editorActiveLineNumber = colorRegistry_1.registerColor('editorLineNumber.activeForeground', { dark: deprecatedEditorActiveLineNumber, light: deprecatedEditorActiveLineNumber, hc: deprecatedEditorActiveLineNumber }, nls.localize(12, null)); exports.editorRuler = colorRegistry_1.registerColor('editorRuler.foreground', { dark: '#5A5A5A', light: color_1.Color.lightgrey, hc: color_1.Color.white }, nls.localize(13, null)); exports.editorCodeLensForeground = colorRegistry_1.registerColor('editorCodeLens.foreground', { dark: '#999999', light: '#999999', hc: '#999999' }, nls.localize(14, null)); exports.editorBracketMatchBackground = colorRegistry_1.registerColor('editorBracketMatch.background', { dark: '#0064001a', light: '#0064001a', hc: '#0064001a' }, nls.localize(15, null)); exports.editorBracketMatchBorder = colorRegistry_1.registerColor('editorBracketMatch.border', { dark: '#888', light: '#B9B9B9', hc: '#fff' }, nls.localize(16, null)); exports.editorOverviewRulerBorder = colorRegistry_1.registerColor('editorOverviewRuler.border', { dark: '#7f7f7f4d', light: '#7f7f7f4d', hc: '#7f7f7f4d' }, nls.localize(17, null)); exports.editorGutter = colorRegistry_1.registerColor('editorGutter.background', { dark: colorRegistry_1.editorBackground, light: colorRegistry_1.editorBackground, hc: colorRegistry_1.editorBackground }, nls.localize(18, null)); exports.editorErrorForeground = colorRegistry_1.registerColor('editorError.foreground', { dark: '#ea4646', light: '#d60a0a', hc: null }, nls.localize(19, null)); exports.editorErrorBorder = colorRegistry_1.registerColor('editorError.border', { dark: null, light: null, hc: color_1.Color.fromHex('#E47777').transparent(0.8) }, nls.localize(20, null)); exports.editorWarningForeground = colorRegistry_1.registerColor('editorWarning.foreground', { dark: '#4d9e4d', light: '#117711', hc: null }, nls.localize(21, null)); exports.editorWarningBorder = colorRegistry_1.registerColor('editorWarning.border', { dark: null, light: null, hc: color_1.Color.fromHex('#71B771').transparent(0.8) }, nls.localize(22, null)); exports.editorInfoForeground = colorRegistry_1.registerColor('editorInfo.foreground', { dark: '#008000', light: '#008000', hc: null }, nls.localize(23, null)); exports.editorInfoBorder = colorRegistry_1.registerColor('editorInfo.border', { dark: null, light: null, hc: color_1.Color.fromHex('#71B771').transparent(0.8) }, nls.localize(24, null)); exports.editorHintForeground = colorRegistry_1.registerColor('editorHint.foreground', { dark: color_1.Color.fromHex('#eeeeee').transparent(0.7), light: '#6c6c6c', hc: null }, nls.localize(25, null)); exports.editorHintBorder = colorRegistry_1.registerColor('editorHint.border', { dark: null, light: null, hc: color_1.Color.fromHex('#eeeeee').transparent(0.8) }, nls.localize(26, null)); exports.editorUnnecessaryCodeBorder = colorRegistry_1.registerColor('editorUnnecessaryCode.border', { dark: null, light: null, hc: color_1.Color.fromHex('#fff').transparent(0.8) }, nls.localize(27, null)); exports.editorUnnecessaryCodeOpacity = colorRegistry_1.registerColor('editorUnnecessaryCode.opacity', { dark: color_1.Color.fromHex('#000a'), light: color_1.Color.fromHex('#0007'), hc: null }, nls.localize(28, 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(29, null)); exports.overviewRulerWarning = colorRegistry_1.registerColor('editorOverviewRuler.warningForeground', { dark: new color_1.Color(new color_1.RGBA(18, 136, 18, 0.7)), light: new color_1.Color(new color_1.RGBA(18, 136, 18, 0.7)), hc: new color_1.Color(new color_1.RGBA(50, 255, 50, 1)) }, nls.localize(30, null)); exports.overviewRulerInfo = colorRegistry_1.registerColor('editorOverviewRuler.infoForeground', { dark: new color_1.Color(new color_1.RGBA(18, 18, 136, 0.7)), light: new color_1.Color(new color_1.RGBA(18, 18, 136, 0.7)), hc: new color_1.Color(new color_1.RGBA(50, 50, 255, 1)) }, nls.localize(31, 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 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[514/*vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([0/*require*/,1/*exports*/,71/*vs/editor/browser/view/dynamicViewOverlay*/,34/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,438/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/]), function (require, exports, dynamicViewOverlay_1, editorColorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CurrentLineHighlightOverlay = /** @class */ (function (_super) { __extends(CurrentLineHighlightOverlay, _super); function CurrentLineHighlightOverlay(context) { var _this = _super.call(this) || this; _this._context = context; _this._lineHeight = _this._context.configuration.editor.lineHeight; _this._renderLineHighlight = _this._context.configuration.editor.viewInfo.renderLineHighlight; _this._selectionIsEmpty = true; _this._primaryCursorLineNumber = 1; _this._scrollWidth = 0; _this._contentWidth = _this._context.configuration.editor.layoutInfo.contentWidth; _this._context.addEventHandler(_this); return _this; } CurrentLineHighlightOverlay.prototype.dispose = function () { this._context.removeEventHandler(this); _super.prototype.dispose.call(this); }; // --- begin event handlers CurrentLineHighlightOverlay.prototype.onConfigurationChanged = function (e) { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; } if (e.viewInfo) { this._renderLineHighlight = this._context.configuration.editor.viewInfo.renderLineHighlight; } if (e.layoutInfo) { this._contentWidth = this._context.configuration.editor.layoutInfo.contentWidth; } return true; }; CurrentLineHighlightOverlay.prototype.onCursorStateChanged = function (e) { var hasChanged = false; var primaryCursorLineNumber = e.selections[0].positionLineNumber; if (this._primaryCursorLineNumber !== primaryCursorLineNumber) { this._primaryCursorLineNumber = primaryCursorLineNumber; hasChanged = true; } var selectionIsEmpty = e.selections[0].isEmpty(); if (this._selectionIsEmpty !== selectionIsEmpty) { this._selectionIsEmpty = selectionIsEmpty; return true; } return hasChanged; }; CurrentLineHighlightOverlay.prototype.onFlushed = function (e) { return true; }; CurrentLineHighlightOverlay.prototype.onLinesDeleted = function (e) { return true; }; CurrentLineHighlightOverlay.prototype.onLinesInserted = function (e) { return true; }; CurrentLineHighlightOverlay.prototype.onScrollChanged = function (e) { return e.scrollWidthChanged; }; CurrentLineHighlightOverlay.prototype.onZonesChanged = function (e) { return true; }; // --- end event handlers CurrentLineHighlightOverlay.prototype.prepareRender = function (ctx) { this._scrollWidth = ctx.scrollWidth; }; CurrentLineHighlightOverlay.prototype.render = function (startLineNumber, lineNumber) { if (lineNumber === this._primaryCursorLineNumber) { if (this._shouldShowCurrentLine()) { var paintedInMargin = this._willRenderMarginCurrentLine(); var className = 'current-line' + (paintedInMargin ? ' current-line-both' : ''); return ('
    '); } else { return ''; } } return ''; }; CurrentLineHighlightOverlay.prototype._shouldShowCurrentLine = function () { return ((this._renderLineHighlight === 'line' || this._renderLineHighlight === 'all') && this._selectionIsEmpty); }; CurrentLineHighlightOverlay.prototype._willRenderMarginCurrentLine = function () { return ((this._renderLineHighlight === 'gutter' || this._renderLineHighlight === 'all')); }; return CurrentLineHighlightOverlay; }(dynamicViewOverlay_1.DynamicViewOverlay)); exports.CurrentLineHighlightOverlay = CurrentLineHighlightOverlay; themeService_1.registerThemingParticipant(function (theme, collector) { var lineHighlight = theme.getColor(editorColorRegistry_1.editorLineHighlight); if (lineHighlight) { collector.addRule(".monaco-editor .view-overlays .current-line { background-color: " + lineHighlight + "; }"); } if (!lineHighlight || lineHighlight.isTransparent() || theme.defines(editorColorRegistry_1.editorLineHighlightBorder)) { var lineHighlightBorder = theme.getColor(editorColorRegistry_1.editorLineHighlightBorder); if (lineHighlightBorder) { collector.addRule(".monaco-editor .view-overlays .current-line { border: 2px solid " + lineHighlightBorder + "; }"); if (theme.type === 'hc') { collector.addRule(".monaco-editor .view-overlays .current-line { 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[515/*vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight*/], __M([0/*require*/,1/*exports*/,71/*vs/editor/browser/view/dynamicViewOverlay*/,34/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,437/*vs/css!vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight*/]), function (require, exports, dynamicViewOverlay_1, editorColorRegistry_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var CurrentLineMarginHighlightOverlay = /** @class */ (function (_super) { __extends(CurrentLineMarginHighlightOverlay, _super); function CurrentLineMarginHighlightOverlay(context) { var _this = _super.call(this) || this; _this._context = context; _this._lineHeight = _this._context.configuration.editor.lineHeight; _this._renderLineHighlight = _this._context.configuration.editor.viewInfo.renderLineHighlight; _this._selectionIsEmpty = true; _this._primaryCursorLineNumber = 1; _this._contentLeft = _this._context.configuration.editor.layoutInfo.contentLeft; _this._context.addEventHandler(_this); return _this; } CurrentLineMarginHighlightOverlay.prototype.dispose = function () { this._context.removeEventHandler(this); _super.prototype.dispose.call(this); }; // --- begin event handlers CurrentLineMarginHighlightOverlay.prototype.onConfigurationChanged = function (e) { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; } if (e.viewInfo) { this._renderLineHighlight = this._context.configuration.editor.viewInfo.renderLineHighlight; } if (e.layoutInfo) { this._contentLeft = this._context.configuration.editor.layoutInfo.contentLeft; } return true; }; CurrentLineMarginHighlightOverlay.prototype.onCursorStateChanged = function (e) { var hasChanged = false; var primaryCursorLineNumber = e.selections[0].positionLineNumber; if (this._primaryCursorLineNumber !== primaryCursorLineNumber) { this._primaryCursorLineNumber = primaryCursorLineNumber; hasChanged = true; } var selectionIsEmpty = e.selections[0].isEmpty(); if (this._selectionIsEmpty !== selectionIsEmpty) { this._selectionIsEmpty = selectionIsEmpty; return true; } return hasChanged; }; CurrentLineMarginHighlightOverlay.prototype.onFlushed = function (e) { return true; }; CurrentLineMarginHighlightOverlay.prototype.onLinesDeleted = function (e) { return true; }; CurrentLineMarginHighlightOverlay.prototype.onLinesInserted = function (e) { return true; }; CurrentLineMarginHighlightOverlay.prototype.onZonesChanged = function (e) { return true; }; // --- end event handlers CurrentLineMarginHighlightOverlay.prototype.prepareRender = function (ctx) { }; CurrentLineMarginHighlightOverlay.prototype.render = function (startLineNumber, lineNumber) { if (lineNumber === this._primaryCursorLineNumber) { var className = 'current-line'; if (this._shouldShowCurrentLine()) { var paintedInContent = this._willRenderContentCurrentLine(); className = 'current-line current-line-margin' + (paintedInContent ? ' current-line-margin-both' : ''); } return ('
    '); } return ''; }; CurrentLineMarginHighlightOverlay.prototype._shouldShowCurrentLine = function () { return ((this._renderLineHighlight === 'gutter' || this._renderLineHighlight === 'all')); }; CurrentLineMarginHighlightOverlay.prototype._willRenderContentCurrentLine = function () { return ((this._renderLineHighlight === 'line' || this._renderLineHighlight === 'all') && this._selectionIsEmpty); }; return CurrentLineMarginHighlightOverlay; }(dynamicViewOverlay_1.DynamicViewOverlay)); exports.CurrentLineMarginHighlightOverlay = CurrentLineMarginHighlightOverlay; themeService_1.registerThemingParticipant(function (theme, collector) { var lineHighlight = theme.getColor(editorColorRegistry_1.editorLineHighlight); if (lineHighlight) { collector.addRule(".monaco-editor .margin-view-overlays .current-line-margin { background-color: " + lineHighlight + "; border: none; }"); } else { var lineHighlightBorder = theme.getColor(editorColorRegistry_1.editorLineHighlightBorder); if (lineHighlightBorder) { collector.addRule(".monaco-editor .margin-view-overlays .current-line-margin { border: 2px solid " + lineHighlightBorder + "; }"); } if (theme.type === 'hc') { 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[516/*vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([0/*require*/,1/*exports*/,71/*vs/editor/browser/view/dynamicViewOverlay*/,12/*vs/editor/common/core/position*/,34/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,432/*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; _this._lineHeight = _this._context.configuration.editor.lineHeight; _this._spaceWidth = _this._context.configuration.editor.fontInfo.spaceWidth; _this._enabled = _this._context.configuration.editor.viewInfo.renderIndentGuides; _this._activeIndentEnabled = _this._context.configuration.editor.viewInfo.highlightActiveIndentGuide; _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) { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; } if (e.fontInfo) { this._spaceWidth = this._context.configuration.editor.fontInfo.spaceWidth; } if (e.viewInfo) { this._enabled = this._context.configuration.editor.viewInfo.renderIndentGuides; this._activeIndentEnabled = this._context.configuration.editor.viewInfo.highlightActiveIndentGuide; } 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 = ''; 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) { 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[213/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,71/*vs/editor/browser/view/dynamicViewOverlay*/,12/*vs/editor/common/core/position*/,34/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,431/*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 config = this._context.configuration.editor; this._lineHeight = config.lineHeight; this._renderLineNumbers = config.viewInfo.renderLineNumbers; this._renderCustomLineNumbers = config.viewInfo.renderCustomLineNumbers; this._renderFinalNewline = config.viewInfo.renderFinalNewline; this._lineNumbersLeft = config.layoutInfo.lineNumbersLeft; this._lineNumbersWidth = config.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._renderFinalNewline) { var lineCount = this._context.model.getLineCount(); var lineContent = this._context.model.getLineContent(modelLineNumber); if (modelLineNumber === lineCount && lineContent === '') { return ''; } } 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 output = []; for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { var lineIndex = lineNumber - visibleStartLineNumber; 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[518/*vs/editor/browser/controller/textAreaHandler*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,26/*vs/base/browser/fastDomNode*/,17/*vs/base/common/platform*/,5/*vs/base/common/strings*/,60/*vs/editor/browser/config/configuration*/,171/*vs/editor/browser/controller/textAreaInput*/,165/*vs/editor/browser/controller/textAreaState*/,33/*vs/editor/browser/view/viewPart*/,213/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/,220/*vs/editor/browser/viewParts/margin/margin*/,83/*vs/editor/common/controller/wordCharacterClassifier*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,73/*vs/editor/common/view/viewEvents*/,440/*vs/css!vs/editor/browser/controller/textAreaHandler*/]), function (require, exports, browser, fastDomNode_1, platform, strings, configuration_1, textAreaInput_1, textAreaState_1, viewPart_1, lineNumbers_1, margin_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); /** * 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 LocalClipboardMetadataManager = /** @class */ (function () { function LocalClipboardMetadataManager() { this._lastState = null; } LocalClipboardMetadataManager.prototype.set = function (state) { this._lastState = state; }; LocalClipboardMetadataManager.prototype.get = function (pastedText) { if (this._lastState && this._lastState.lastCopiedValue === pastedText) { // match! return this._lastState; } this._lastState = null; return null; }; LocalClipboardMetadataManager.INSTANCE = new LocalClipboardMetadataManager(); return LocalClipboardMetadataManager; }()); var TextAreaHandler = /** @class */ (function (_super) { __extends(TextAreaHandler, _super); function TextAreaHandler(context, viewController, viewHelper) { var _this = _super.call(this, context) || this; // --- end view API _this._primaryCursorVisibleRange = null; _this._viewController = viewController; _this._viewHelper = viewHelper; var conf = _this._context.configuration.editor; _this._accessibilitySupport = conf.accessibilitySupport; _this._contentLeft = conf.layoutInfo.contentLeft; _this._contentWidth = conf.layoutInfo.contentWidth; _this._contentHeight = conf.layoutInfo.contentHeight; _this._scrollLeft = 0; _this._scrollTop = 0; _this._fontInfo = conf.fontInfo; _this._lineHeight = conf.lineHeight; _this._emptySelectionClipboard = conf.emptySelectionClipboard; _this._copyWithSyntaxHighlighting = conf.copyWithSyntaxHighlighting; _this._visibleTextArea = null; _this._selections = [new selection_1.Selection(1, 1, 1, 1)]; // 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', conf.viewInfo.ariaLabel); _this.textArea.setAttribute('role', 'textbox'); _this.textArea.setAttribute('aria-multiline', 'true'); _this.textArea.setAttribute('aria-haspopup', 'false'); _this.textArea.setAttribute('aria-autocomplete', 'both'); _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 = { getPlainTextToCopy: function () { var rawWhatToCopy = _this._context.model.getPlainTextToCopy(_this._selections, _this._emptySelectionClipboard, platform.isWindows); var newLineCharacter = _this._context.model.getEOL(); var isFromEmptySelection = (_this._emptySelectionClipboard && _this._selections.length === 1 && _this._selections[0].isEmpty()); var multicursorText = (Array.isArray(rawWhatToCopy) ? rawWhatToCopy : null); var whatToCopy = (Array.isArray(rawWhatToCopy) ? rawWhatToCopy.join(newLineCharacter) : rawWhatToCopy); var metadata = null; if (isFromEmptySelection || multicursorText) { // Only store the non-default metadata // When writing "LINE\r\n" to the clipboard and then pasting, // Firefox pastes "LINE\n", so let's work around this quirk var lastCopiedValue = (browser.isFirefox ? whatToCopy.replace(/\r\n/g, '\n') : whatToCopy); metadata = { lastCopiedValue: lastCopiedValue, isFromEmptySelection: (_this._emptySelectionClipboard && _this._selections.length === 1 && _this._selections[0].isEmpty()), multicursorText: multicursorText }; } LocalClipboardMetadataManager.INSTANCE.set(metadata); return whatToCopy; }, getHTMLToCopy: function () { if (!_this._copyWithSyntaxHighlighting && !textAreaInput_1.CopyOptions.forceCopyWithSyntaxHighlighting) { return null; } return _this._context.model.getHTMLToCopy(_this._selections, _this._emptySelectionClipboard); }, 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._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 metadata = LocalClipboardMetadataManager.INSTANCE.get(e.text); var pasteOnNewLine = false; var multicursorText = null; if (metadata) { pasteOnNewLine = (_this._emptySelectionClipboard && metadata.isFromEmptySelection); multicursorText = metadata.multicursorText; } _this._viewController.paste('keyboard', e.text, pasteOnNewLine, multicursorText); })); _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(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.editor.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 ''; }; // --- begin event handlers TextAreaHandler.prototype.onConfigurationChanged = function (e) { var conf = this._context.configuration.editor; if (e.fontInfo) { this._fontInfo = conf.fontInfo; } if (e.viewInfo) { this.textArea.setAttribute('aria-label', conf.viewInfo.ariaLabel); } if (e.layoutInfo) { this._contentLeft = conf.layoutInfo.contentLeft; this._contentWidth = conf.layoutInfo.contentWidth; this._contentHeight = conf.layoutInfo.contentHeight; } if (e.lineHeight) { this._lineHeight = conf.lineHeight; } if (e.accessibilitySupport) { this._accessibilitySupport = conf.accessibilitySupport; this._textAreaInput.writeScreenReaderContent('strategy changed'); } if (e.emptySelectionClipboard) { this._emptySelectionClipboard = conf.emptySelectionClipboard; } if (e.copyWithSyntaxHighlighting) { this._copyWithSyntaxHighlighting = conf.copyWithSyntaxHighlighting; } return true; }; TextAreaHandler.prototype.onCursorStateChanged = function (e) { this._selections = e.selections.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.prepareRender = function (ctx) { if (this._accessibilitySupport === 2 /* Enabled */) { // Do not move the textarea with the cursor, as this generates accessibility events that might confuse screen readers // See https://github.com/Microsoft/vscode/issues/26730 this._primaryCursorVisibleRange = null; } else { var primaryCursorPosition = new position_1.Position(this._selections[0].positionLineNumber, this._selections[0].positionColumn); this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(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(this._visibleTextArea.top - this._scrollTop, this._contentLeft + this._visibleTextArea.left - this._scrollLeft, this._visibleTextArea.width, this._lineHeight, true); 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 this._renderInsideEditor(top, left, canUseZeroSizeTextarea ? 0 : 1, canUseZeroSizeTextarea ? 0 : 1, false); }; TextAreaHandler.prototype._renderInsideEditor = function (top, left, width, height, useEditorFont) { var ta = this.textArea; var tac = this.textAreaCover; if (useEditorFont) { configuration_1.Configuration.applyFontInfo(ta, this._fontInfo); } else { ta.setFontSize(1); ta.setLineHeight(this._fontInfo.lineHeight); } 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 () { 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); if (this._context.configuration.editor.viewInfo.glyphMargin) { tac.setClassName('monaco-editor-background textAreaCover ' + margin_1.Margin.OUTER_CLASS_NAME); } else { if (this._context.configuration.editor.viewInfo.renderLineNumbers !== 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[519/*vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler*/], __M([0/*require*/,1/*exports*/,26/*vs/base/browser/fastDomNode*/,28/*vs/base/common/color*/,33/*vs/editor/browser/view/viewPart*/,12/*vs/editor/common/core/position*/,16/*vs/editor/common/modes*/,34/*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) { this.lineHeight = config.editor.lineHeight; this.pixelRatio = config.editor.pixelRatio; this.overviewRulerLanes = config.editor.viewInfo.overviewRulerLanes; this.renderBorder = config.editor.viewInfo.overviewRulerBorder; var borderColor = theme.getColor(editorColorRegistry_1.editorOverviewRulerBorder); this.borderColor = borderColor ? borderColor.toString() : null; this.hideCursor = config.editor.viewInfo.hideCursorInOverviewRuler; var cursorColor = theme.getColor(editorColorRegistry_1.editorCursorForeground); this.cursorColor = cursorColor ? cursorColor.transparent(0.7).toString() : null; this.themeType = theme.type; var minimapEnabled = config.editor.viewInfo.minimap.enabled; var minimapSide = config.editor.viewInfo.minimap.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 position = config.editor.layoutInfo.overviewRuler; this.top = position.top; this.right = position.right; this.domWidth = position.width; this.domHeight = position.height; 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.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 () { 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[520/*vs/editor/browser/viewParts/rulers/rulers*/], __M([0/*require*/,1/*exports*/,26/*vs/base/browser/fastDomNode*/,33/*vs/editor/browser/view/viewPart*/,34/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,418/*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 = []; _this._rulers = _this._context.configuration.editor.viewInfo.rulers; _this._typicalHalfwidthCharacterWidth = _this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth; return _this; } Rulers.prototype.dispose = function () { _super.prototype.dispose.call(this); }; // --- begin event handlers Rulers.prototype.onConfigurationChanged = function (e) { if (e.viewInfo || e.layoutInfo || e.fontInfo) { this._rulers = this._context.configuration.editor.viewInfo.rulers; this._typicalHalfwidthCharacterWidth = this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth; return true; } return false; }; 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[521/*vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([0/*require*/,1/*exports*/,26/*vs/base/browser/fastDomNode*/,15/*vs/base/common/async*/,33/*vs/editor/browser/view/viewPart*/,449/*vs/editor/browser/viewParts/viewCursors/viewCursor*/,48/*vs/editor/common/config/editorOptions*/,34/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,412/*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; _this._readOnly = _this._context.configuration.editor.readOnly; _this._cursorBlinking = _this._context.configuration.editor.viewInfo.cursorBlinking; _this._cursorStyle = _this._context.configuration.editor.viewInfo.cursorStyle; _this._cursorSmoothCaretAnimation = _this._context.configuration.editor.viewInfo.cursorSmoothCaretAnimation; _this._selectionIsEmpty = true; _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) { if (e.readOnly) { this._readOnly = this._context.configuration.editor.readOnly; } if (e.viewInfo) { this._cursorBlinking = this._context.configuration.editor.viewInfo.cursorBlinking; this._cursorStyle = this._context.configuration.editor.viewInfo.cursorStyle; this._cursorSmoothCaretAnimation = this._context.configuration.editor.viewInfo.cursorSmoothCaretAnimation; } this._primaryCursor.onConfigurationChanged(e); this._updateBlinking(); if (e.viewInfo) { this._updateDomClassName(); } 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[522/*vs/editor/browser/view/viewImpl*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,26/*vs/base/browser/fastDomNode*/,10/*vs/base/common/errors*/,507/*vs/editor/browser/controller/pointerHandler*/,518/*vs/editor/browser/controller/textAreaHandler*/,464/*vs/editor/browser/view/viewController*/,448/*vs/editor/browser/view/viewOverlays*/,33/*vs/editor/browser/view/viewPart*/,229/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/,514/*vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/,515/*vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight*/,230/*vs/editor/browser/viewParts/decorations/decorations*/,503/*vs/editor/browser/viewParts/editorScrollbar/editorScrollbar*/,156/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/,516/*vs/editor/browser/viewParts/indentGuides/indentGuides*/,213/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/,509/*vs/editor/browser/viewParts/lines/viewLines*/,232/*vs/editor/browser/viewParts/linesDecorations/linesDecorations*/,220/*vs/editor/browser/viewParts/margin/margin*/,234/*vs/editor/browser/viewParts/marginDecorations/marginDecorations*/,510/*vs/editor/browser/viewParts/minimap/minimap*/,235/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/,519/*vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler*/,236/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/,520/*vs/editor/browser/viewParts/rulers/rulers*/,511/*vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/,512/*vs/editor/browser/viewParts/selections/selections*/,521/*vs/editor/browser/viewParts/viewCursors/viewCursors*/,237/*vs/editor/browser/viewParts/viewZones/viewZones*/,12/*vs/editor/common/core/position*/,88/*vs/editor/common/view/renderingContext*/,242/*vs/editor/common/view/viewContext*/,238/*vs/editor/common/view/viewEventDispatcher*/,73/*vs/editor/common/view/viewEvents*/,233/*vs/editor/common/viewLayout/viewLinesViewportData*/,86/*vs/editor/common/viewModel/viewEventHandler*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, dom, fastDomNode_1, errors_1, pointerHandler_1, textAreaHandler_1, viewController_1, viewOverlays_1, viewPart_1, contentWidgets_1, currentLineHighlight_1, currentLineMarginHighlight_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, renderingContext_1, viewContext_1, viewEventDispatcher_1, viewEvents, viewLinesViewportData_1, viewEventHandler_1, themeService_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var invalidFunc = function () { throw new Error("Invalid change accessor"); }; 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); _this.createViewParts(); _this._setLayout(); // Pointer handler _this.pointerHandler = 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.createViewParts = function () { // 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 currentLineMarginHighlight_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); }; 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(); }, getLastViewCursorsRenderData: function () { return _this.viewCursors.getLastRenderData() || []; }, 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); }, visibleRangeForPosition2: 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._setLayout = function () { var layoutInfo = this._context.configuration.editor.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.editor.editorClassName + ' ' + themeService_1.getThemeTypeSelector(this._context.theme.type) + focused; }; // --- begin event handlers View.prototype.onConfigurationChanged = function (e) { if (e.editorClassName) { this.domNode.setClassName(this.getEditorClassName()); } if (e.layoutInfo) { this._setLayout(); } 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.pointerHandler.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) { return this.pointerHandler.getTargetAtClientPoint(clientX, clientY); }; View.prototype.createOverviewRuler = function (cssClassName) { return new overviewRuler_1.OverviewRuler(this._context, cssClassName); }; View.prototype.change = function (callback) { var _this = this; var zonesHaveChanged = false; this._renderOnce(function () { var changeAccessor = { addZone: function (zone) { zonesHaveChanged = true; return _this.viewZones.addZone(zone); }, removeZone: function (id) { if (!id) { return; } zonesHaveChanged = _this.viewZones.removeZone(id) || zonesHaveChanged; }, layoutZone: function (id) { if (!id) { return; } zonesHaveChanged = _this.viewZones.layoutZone(id) || zonesHaveChanged; } }; safeInvoke1Arg(callback, changeAccessor); // Invalidate changeAccessor changeAccessor.addZone = invalidFunc; changeAccessor.removeZone = invalidFunc; changeAccessor.layoutZone = invalidFunc; 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.addContentWidget = function (widgetData) { this.contentWidgets.addWidget(widgetData.widget); this.layoutContentWidget(widgetData); this._scheduleRender(); }; View.prototype.layoutContentWidget = function (widgetData) { var newPosition = widgetData.position ? widgetData.position.position : null; var newRange = widgetData.position ? widgetData.position.range : null; var newPreference = widgetData.position ? widgetData.position.preference : null; this.contentWidgets.setWidgetPosition(widgetData.widget, newPosition, 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); } } 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[102/*vs/editor/browser/widget/codeEditorWidget*/], __M([0/*require*/,1/*exports*/,302/*vs/nls!vs/editor/browser/widget/codeEditorWidget*/,7/*vs/base/browser/dom*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,53/*vs/base/common/network*/,60/*vs/editor/browser/config/configuration*/,11/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,522/*vs/editor/browser/view/viewImpl*/,508/*vs/editor/browser/view/viewOutgoingEvents*/,391/*vs/editor/common/controller/cursor*/,38/*vs/editor/common/controller/cursorCommon*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,181/*vs/editor/common/editorAction*/,70/*vs/editor/common/editorCommon*/,21/*vs/editor/common/editorContextKeys*/,16/*vs/editor/common/modes*/,34/*vs/editor/common/view/editorColorRegistry*/,399/*vs/editor/common/viewModel/viewModelImpl*/,27/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,13/*vs/platform/instantiation/common/instantiation*/,91/*vs/platform/instantiation/common/serviceCollection*/,35/*vs/platform/notification/common/notification*/,14/*vs/platform/theme/common/themeService*/,75/*vs/platform/accessibility/common/accessibility*/,20/*vs/base/common/types*/,407/*vs/css!vs/editor/browser/widget/media/editor*/,226/*vs/css!vs/editor/browser/widget/media/tokens*/]), function (require, exports, nls, dom, errors_1, event_1, lifecycle_1, network_1, configuration_1, editorExtensions_1, codeEditorService_1, viewImpl_1, viewOutgoingEvents_1, cursor_1, cursorCommon_1, position_1, range_1, selection_1, editorAction_1, editorCommon, editorContextKeys_1, modes, editorColorRegistry_1, viewModelImpl_1, commands_1, contextkey_1, instantiation_1, serviceCollection_1, notification_1, themeService_1, accessibility_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EDITOR_ID = 0; var SHOW_UNUSED_ENABLED_CLASS = 'showUnused'; 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._onCompositionStart = _this._register(new event_1.Emitter()); _this.onCompositionStart = _this._onCompositionStart.event; _this._onCompositionEnd = _this._register(new event_1.Emitter()); _this.onCompositionEnd = _this._onCompositionEnd.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._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); if (e.layoutInfo) { _this._onDidLayoutChange.fire(_this._configuration.editor.layoutInfo); } if (_this._configuration.editor.showUnused) { _this._domElement.classList.add(SHOW_UNUSED_ENABLED_CLASS); } else { _this._domElement.classList.remove(SHOW_UNUSED_ENABLED_CLASS); } })); _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._attachModel(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, len = contributions.length; i < len; i++) { var ctor = contributions[i]; try { var contribution = _this._instantiationService.createInstance(ctor, _this); _this._contributions[contribution.getId()] = 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.getConfiguration = function () { return this._configuration.editor; }; CodeEditorWidget.prototype.getRawConfiguration = 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 detachedModel = this._detachModel(); this._attachModel(model); 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(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.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.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(new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column)); } return; } if (handlerId === editorCommon.Handler.CompositionStart) { this._onCompositionStart.fire(); } if (handlerId === editorCommon.Handler.CompositionEnd) { this._onCompositionEnd.fire(); } 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); }; 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.editor.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.editor.readOnly) { // read only editor => sorry! return false; } this._modelData.model.pushEditOperations(this._modelData.cursor.getSelections(), edits, function () { return endCursorState ? endCursorState : null; }); if (endCursorState) { this._modelData.cursor.setSelections(source, endCursorState); } 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, this._configuration.editor.readOnly); }; 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 () { return this._configuration.editor.layoutInfo; }; CodeEditorWidget.prototype.createOverviewRuler = function (cssClassName) { if (!this._modelData || !this._modelData.hasRealView) { return null; } return this._modelData.view.createOverviewRuler(cssClassName); }; 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 layoutInfo = this._configuration.editor.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: this._configuration.editor.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.applyFontInfo = function (target) { configuration_1.Configuration.applyFontInfoSlow(target, this._configuration.editor.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, 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), 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) { _this.trigger(source, editorCommon.Handler.Paste, { text: text, pasteOnNewLine: pasteOnNewLine, multicursorText: multicursorText }); }, 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) { _this._commandService.executeCommand(editorCommon.Handler.Paste, { text: text, pasteOnNewLine: pasteOnNewLine, multicursorText: multicursorText }); }, 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.onDidGainFocus = function () { _this._editorTextFocus.setValue(true); // In IE, the focus is not synchronous, so we give it a little help _this._editorWidgetFocus.setValue(true); }; viewOutgoingEvents.onDidScroll = function (e) { return _this._onDidScrollChange.fire(e); }; 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); }; /* __GDPR__FRAGMENT__ "EditorTelemetryData" : {} */ CodeEditorWidget.prototype.getTelemetryData = function () { return this._telemetryData; }; 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._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(); return _this; } EditorContextKeysManager.prototype._updateFromConfig = function () { var config = this._editor.getConfiguration(); this._editorTabMovesFocus.set(config.tabFocusMode); this._editorReadonly.set(config.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(editorColorRegistry_1.editorErrorBorder); if (errorBorderColor) { collector.addRule(".monaco-editor ." + "squiggly-error" /* EditorErrorDecoration */ + " { border-bottom: 4px double " + errorBorderColor + "; }"); } var errorForeground = theme.getColor(editorColorRegistry_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(editorColorRegistry_1.editorWarningBorder); if (warningBorderColor) { collector.addRule(".monaco-editor ." + "squiggly-warning" /* EditorWarningDecoration */ + " { border-bottom: 4px double " + warningBorderColor + "; }"); } var warningForeground = theme.getColor(editorColorRegistry_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(editorColorRegistry_1.editorInfoBorder); if (infoBorderColor) { collector.addRule(".monaco-editor ." + "squiggly-info" /* EditorInfoDecoration */ + " { border-bottom: 4px double " + infoBorderColor + "; }"); } var infoForeground = theme.getColor(editorColorRegistry_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(editorColorRegistry_1.editorHintBorder); if (hintBorderColor) { collector.addRule(".monaco-editor ." + "squiggly-hint" /* EditorHintDecoration */ + " { border-bottom: 2px dotted " + hintBorderColor + "; }"); } var hintForeground = theme.getColor(editorColorRegistry_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("." + SHOW_UNUSED_ENABLED_CLASS + " .monaco-editor ." + "squiggly-inline-unnecessary" /* EditorUnnecessaryInlineDecoration */ + " { opacity: " + unnecessaryForeground.rgba.a + "; }"); } var unnecessaryBorder = theme.getColor(editorColorRegistry_1.editorUnnecessaryCodeBorder); if (unnecessaryBorder) { collector.addRule("." + SHOW_UNUSED_ENABLED_CLASS + " .monaco-editor ." + "squiggly-unnecessary" /* EditorUnnecessaryDecoration */ + " { border-bottom: 2px dashed " + unnecessaryBorder + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * 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/browser/widget/diffReview*/], __M([0/*require*/,1/*exports*/,304/*vs/nls!vs/editor/browser/widget/diffReview*/,7/*vs/base/browser/dom*/,26/*vs/base/browser/fastDomNode*/,79/*vs/base/browser/ui/actionbar/actionbar*/,51/*vs/base/browser/ui/scrollbar/scrollableElement*/,49/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,60/*vs/editor/browser/config/configuration*/,11/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,94/*vs/editor/common/core/lineTokens*/,12/*vs/editor/common/core/position*/,34/*vs/editor/common/view/editorColorRegistry*/,108/*vs/editor/common/viewLayout/viewLineRenderer*/,69/*vs/editor/common/viewModel/viewModel*/,18/*vs/platform/contextkey/common/contextkey*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,408/*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, 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 originalOpts = this._diffEditor.getOriginalEditor().getConfiguration(); var modifiedOpts = this._diffEditor.getModifiedEditor().getConfiguration(); 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, modifiedOpts.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, originalOpts, originalModel, originalModelOpts, modifiedOpts, 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, originalOpts, originalModel, originalModelOpts, modifiedOpts, 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 originalLineNumbersWidth = originalOpts.layoutInfo.glyphMarginWidth + originalOpts.layoutInfo.lineNumbersWidth; var modifiedLineNumbersWidth = 10 + modifiedOpts.layoutInfo.glyphMarginWidth + modifiedOpts.layoutInfo.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, modifiedOpts, modifiedModelOpts.tabSize, modifiedLine)); lineContent = modifiedModel.getLineContent(modifiedLine); } else { cell.insertAdjacentHTML('beforeend', this._renderLine(originalModel, originalOpts, 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, config, tabSize, lineNumber) { var lineContent = model.getLineContent(lineNumber); 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((config.fontInfo.isMonospace && !config.viewInfo.disableMonospaceOptimizations), config.fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, config.fontInfo.spaceWidth, config.viewInfo.stopRenderingLineAfter, config.viewInfo.renderWhitespace, config.viewInfo.renderControlCharacters, config.viewInfo.fontLigatures)); 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[204/*vs/editor/browser/widget/diffEditorWidget*/], __M([0/*require*/,1/*exports*/,303/*vs/nls!vs/editor/browser/widget/diffEditorWidget*/,7/*vs/base/browser/dom*/,26/*vs/base/browser/fastDomNode*/,96/*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*/,64/*vs/editor/browser/core/editorState*/,32/*vs/editor/browser/services/codeEditorService*/,102/*vs/editor/browser/widget/codeEditorWidget*/,524/*vs/editor/browser/widget/diffReview*/,48/*vs/editor/common/config/editorOptions*/,3/*vs/editor/common/core/range*/,124/*vs/editor/common/core/stringBuilder*/,70/*vs/editor/common/editorCommon*/,29/*vs/editor/common/model/textModel*/,63/*vs/editor/common/services/editorWorkerService*/,212/*vs/editor/common/view/overviewZoneManager*/,154/*vs/editor/common/viewLayout/lineDecorations*/,108/*vs/editor/common/viewLayout/viewLineRenderer*/,69/*vs/editor/common/viewModel/viewModel*/,18/*vs/platform/contextkey/common/contextkey*/,13/*vs/platform/instantiation/common/instantiation*/,91/*vs/platform/instantiation/common/serviceCollection*/,35/*vs/platform/notification/common/notification*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,409/*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, 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) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var VisualEditorState = /** @class */ (function () { function VisualEditorState() { this._zones = []; 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]); } _this._zones = []; _this._zonesMap = {}; for (var i = 0, length_3 = newDecorations.zones.length; i < length_3; i++) { newDecorations.zones[i].suppressMouseDown = true; var zoneId = viewChangeAccessor.addZone(newDecorations.zones[i]); _this._zones.push(zoneId); _this._zonesMap[String(zoneId)] = true; } }); 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, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService) { var _this = _super.call(this) || this; _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._domElement = domElement; options = options || {}; // renderSideBySide _this._renderSideBySide = true; if (typeof options.renderSideBySide !== 'undefined') { _this._renderSideBySide = options.renderSideBySide; } // 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); _this._createLeftHandSide(); _this._createRightHandSide(); _this._beginUpdateDecorationsTimeout = -1; _this._currentlyChangingViewZones = false; _this._diffComputationToken = 0; _this._originalEditorState = new VisualEditorState(); _this._modifiedEditorState = new VisualEditorState(); _this._isVisible = true; _this._isHandlingScrollEvent = false; _this._width = 0; _this._height = 0; _this._reviewHeight = 0; _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._createLeftHandSideEditor(options, leftScopedInstantiationService); _this._createRightHandSideEditor(options, rightScopedInstantiationService); _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); if (options.automaticLayout) { _this._measureDomElementToken = window.setInterval(function () { return _this._measureDomElement(false); }, 100); } // enableSplitViewResizing _this._enableSplitViewResizing = true; if (typeof options.enableSplitViewResizing !== 'undefined') { _this._enableSplitViewResizing = options.enableSplitViewResizing; } if (_this._renderSideBySide) { _this._setStrategy(new DiffEdtorWidgetSideBySide(_this._createDataSource(), _this._enableSplitViewResizing)); } else { _this._setStrategy(new DiffEdtorWidgetInline(_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); })); _this._codeEditorService.addDiffEditor(_this); return _this; } 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._createLeftHandSide = function () { 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); }; DiffEditorWidget.prototype._createRightHandSide = function () { 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); }; DiffEditorWidget.prototype._createLeftHandSideEditor = function (options, instantiationService) { var _this = this; this.originalEditor = this._createInnerEditor(instantiationService, this._originalDomNode, this._adjustOptionsForLeftHandSide(options, this._originalIsEditable)); this._register(this.originalEditor.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(this.originalEditor.onDidChangeViewZones(function () { _this._onViewZonesChanged(); })); this._register(this.originalEditor.onDidChangeModelContent(function () { if (_this._isVisible) { _this._beginUpdateDecorationsSoon(); } })); }; DiffEditorWidget.prototype._createRightHandSideEditor = function (options, instantiationService) { var _this = this; this.modifiedEditor = this._createInnerEditor(instantiationService, this._modifiedDomNode, this._adjustOptionsForRightHandSide(options)); this._register(this.modifiedEditor.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(this.modifiedEditor.onDidChangeViewZones(function () { _this._onViewZonesChanged(); })); this._register(this.modifiedEditor.onDidChangeConfiguration(function (e) { if (e.fontInfo && _this.modifiedEditor.getModel()) { _this._onViewZonesChanged(); } })); this._register(this.modifiedEditor.onDidChangeModelContent(function () { if (_this._isVisible) { _this._beginUpdateDecorationsSoon(); } })); }; 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; } window.clearInterval(this._measureDomElementToken); 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; } } 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 DiffEdtorWidgetSideBySide(this._createDataSource(), this._enableSplitViewResizing)); } else { this._setStrategy(new DiffEdtorWidgetInline(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(); if (model) { this.originalEditor.setScrollTop(0); this.modifiedEditor.setScrollTop(0); } // Disable any diff computations that will come in this._diffComputationResult = null; this._diffComputationToken++; if (model) { this._recreateOverviewRulers(); // Begin comparing this._beginUpdateDecorations(); } else { this._diffComputationResult = null; } 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._measureDomElement(false, 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._measureDomElement = function (forceDoLayoutCall, dimensions) { dimensions = dimensions || { width: this._containerDomElement.clientWidth, height: this._containerDomElement.clientHeight }; if (dimensions.width <= 0) { this._width = 0; this._height = 0; this._reviewHeight = 0; return; } if (!forceDoLayoutCall && dimensions.width === this._width && dimensions.height === this._height) { // Nothing has changed return; } this._width = dimensions.width; this._height = dimensions.height; this._reviewHeight = this._reviewPane.isVisible() ? this._height : 0; this._doLayout(); }; DiffEditorWidget.prototype._layoutOverviewRulers = function () { 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: (this._height - this._reviewHeight) }); this._modifiedOverviewRuler.setLayout({ top: 0, right: 0, width: DiffEditorWidget.ONE_OVERVIEW_WIDTH, height: (this._height - this._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; 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).then(function (result) { if (currentToken === _this._diffComputationToken && currentOriginalModel === _this.originalEditor.getModel() && currentModifiedModel === _this.modifiedEditor.getModel()) { _this._diffComputationResult = result; _this._updateDecorationsRunner.schedule(); _this._onDidUpdateDiff.fire(); } }, function (error) { if (currentToken === _this._diffComputationToken && currentOriginalModel === _this.originalEditor.getModel() && currentModifiedModel === _this.modifiedEditor.getModel()) { _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()) { 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.overviewRulerLanes = 1; result.extraEditorClassName = 'original-in-monaco-diff-editor'; return result; }; DiffEditorWidget.prototype._adjustOptionsForRightHandSide = function (options) { var result = this._adjustOptionsForSubEditor(options); result.revealHorizontalRightPadding = editorOptions.EDITOR_DEFAULTS.viewInfo.revealHorizontalRightPadding + DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH; result.scrollbar.verticalHasArrows = false; result.extraEditorClassName = 'modified-in-monaco-diff-editor'; return result; }; DiffEditorWidget.prototype.doLayout = function () { this._measureDomElement(true); }; DiffEditorWidget.prototype._doLayout = function () { var splitPoint = this._strategy.layout(); this._originalDomNode.style.width = splitPoint + 'px'; this._originalDomNode.style.left = '0px'; this._modifiedDomNode.style.width = (this._width - splitPoint) + 'px'; this._modifiedDomNode.style.left = splitPoint + 'px'; this._overviewDomElement.style.top = '0px'; this._overviewDomElement.style.height = (this._height - this._reviewHeight) + 'px'; this._overviewDomElement.style.width = DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH + 'px'; this._overviewDomElement.style.left = (this._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: (this._height - this._reviewHeight) }); this.modifiedEditor.layout({ width: this._width - splitPoint - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH, height: (this._height - this._reviewHeight) }); if (this._originalOverviewRuler || this._modifiedOverviewRuler) { this._layoutOverviewRulers(); } this._reviewPane.layout(this._height - this._reviewHeight, this._width, this._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.contentHeight); var computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * 0); var computedRatio = scrollHeight > 0 ? (computedRepresentableSize / scrollHeight) : 0; var computedSliderSize = Math.max(0, Math.floor(layoutInfo.contentHeight * computedRatio)); var computedSliderPosition = Math.floor(scrollTop * computedRatio); return { height: computedSliderSize, top: computedSliderPosition }; }; DiffEditorWidget.prototype._createDataSource = function () { var _this = this; return { getWidth: function () { return _this._width; }, getHeight: function () { return (_this._height - _this._reviewHeight); }, 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._measureDomElement(true); }; 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]) : Number.MAX_VALUE); 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(2, editorWorkerService_1.IEditorWorkerService), __param(3, contextkey_1.IContextKeyService), __param(4, instantiation_1.IInstantiationService), __param(5, codeEditorService_1.ICodeEditorService), __param(6, themeService_1.IThemeService), __param(7, notification_1.INotificationService) ], 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; 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.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, modifiedForeignVZ) { this.lineChanges = lineChanges; this.originalForeignVZ = originalForeignVZ; this.modifiedForeignVZ = modifiedForeignVZ; } 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_4 = this.lineChanges.length; i <= length_4; i++) { var lineChange = (i < length_4 ? 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.heightInLines, 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.heightInLines, 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', 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', marginClassName: 'line-delete', isWholeLine: true }), lineDeleteMargin: textModel_1.ModelDecorationOptions.register({ marginClassName: 'line-delete', }) }; var DiffEdtorWidgetSideBySide = /** @class */ (function (_super) { __extends(DiffEdtorWidgetSideBySide, _super); function DiffEdtorWidgetSideBySide(dataSource, enableSplitViewResizing) { var _this = _super.call(this, dataSource) || this; _this._disableSash = (enableSplitViewResizing === false); _this._sashRatio = null; _this._sashPosition = 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; } DiffEdtorWidgetSideBySide.prototype.setEnableSplitViewResizing = function (enableSplitViewResizing) { var newDisableSash = (enableSplitViewResizing === false); if (this._disableSash !== newDisableSash) { this._disableSash = newDisableSash; this._sash.state = this._disableSash ? 0 /* Disabled */ : 3 /* Enabled */; } }; DiffEdtorWidgetSideBySide.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 > DiffEdtorWidgetSideBySide.MINIMUM_EDITOR_WIDTH * 2) { if (sashPosition < DiffEdtorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) { sashPosition = DiffEdtorWidgetSideBySide.MINIMUM_EDITOR_WIDTH; } if (sashPosition > contentWidth - DiffEdtorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) { sashPosition = contentWidth - DiffEdtorWidgetSideBySide.MINIMUM_EDITOR_WIDTH; } } else { sashPosition = midPoint; } if (this._sashPosition !== sashPosition) { this._sashPosition = sashPosition; this._sash.layout(); } return this._sashPosition; }; DiffEdtorWidgetSideBySide.prototype.onSashDragStart = function () { this._startSashPosition = this._sashPosition; }; DiffEdtorWidgetSideBySide.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(); }; DiffEdtorWidgetSideBySide.prototype.onSashDragEnd = function () { this._sash.layout(); }; DiffEdtorWidgetSideBySide.prototype.onSashReset = function () { this._sashRatio = 0.5; this._dataSource.relayoutEditors(); this._sash.layout(); }; DiffEdtorWidgetSideBySide.prototype.getVerticalSashTop = function (sash) { return 0; }; DiffEdtorWidgetSideBySide.prototype.getVerticalSashLeft = function (sash) { return this._sashPosition; }; DiffEdtorWidgetSideBySide.prototype.getVerticalSashHeight = function (sash) { return this._dataSource.getHeight(); }; DiffEdtorWidgetSideBySide.prototype._getViewZones = function (lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor) { var c = new SideBySideViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ); return c.getViewZones(); }; DiffEdtorWidgetSideBySide.prototype._getOriginalEditorDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) { var overviewZoneColor = this._removeColor.toString(); var result = { decorations: [], overviewZones: [] }; var originalModel = originalEditor.getModel(); for (var i = 0, length_5 = lineChanges.length; i < length_5; i++) { var lineChange = lineChanges[i]; if (isChangeOrDelete(lineChange)) { result.decorations.push({ range: new range_1.Range(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, Number.MAX_VALUE), options: (renderIndicators ? DECORATIONS.lineDeleteWithSign : DECORATIONS.lineDelete) }); if (!isChangeOrInsert(lineChange) || !lineChange.charChanges) { result.decorations.push(createDecoration(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, Number.MAX_VALUE, 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; }; DiffEdtorWidgetSideBySide.prototype._getModifiedEditorDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) { var overviewZoneColor = this._insertColor.toString(); var result = { decorations: [], overviewZones: [] }; var modifiedModel = modifiedEditor.getModel(); for (var i = 0, length_6 = lineChanges.length; i < length_6; i++) { var lineChange = lineChanges[i]; if (isChangeOrInsert(lineChange)) { result.decorations.push({ range: new range_1.Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, Number.MAX_VALUE), options: (renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert) }); if (!isChangeOrDelete(lineChange) || !lineChange.charChanges) { result.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, Number.MAX_VALUE, 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; }; DiffEdtorWidgetSideBySide.MINIMUM_EDITOR_WIDTH = 100; return DiffEdtorWidgetSideBySide; }(DiffEditorWidgetStyle)); var SideBySideViewZonesComputer = /** @class */ (function (_super) { __extends(SideBySideViewZonesComputer, _super); function SideBySideViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ) { return _super.call(this, lineChanges, originalForeignVZ, modifiedForeignVZ) || 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 DiffEdtorWidgetInline = /** @class */ (function (_super) { __extends(DiffEdtorWidgetInline, _super); function DiffEdtorWidgetInline(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; } DiffEdtorWidgetInline.prototype.setEnableSplitViewResizing = function (enableSplitViewResizing) { // Nothing to do.. }; DiffEdtorWidgetInline.prototype._getViewZones = function (lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators) { var computer = new InlineViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators); return computer.getViewZones(); }; DiffEdtorWidgetInline.prototype._getOriginalEditorDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) { var overviewZoneColor = this._removeColor.toString(); var result = { decorations: [], overviewZones: [] }; for (var i = 0, length_7 = lineChanges.length; i < length_7; 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, Number.MAX_VALUE), options: DECORATIONS.lineDeleteMargin }); result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber, overviewZoneColor)); } } return result; }; DiffEdtorWidgetInline.prototype._getModifiedEditorDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) { var overviewZoneColor = this._insertColor.toString(); var result = { decorations: [], overviewZones: [] }; var modifiedModel = modifiedEditor.getModel(); for (var i = 0, length_8 = lineChanges.length; i < length_8; 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, Number.MAX_VALUE), 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, Number.MAX_VALUE, DECORATIONS.charInsertWholeLine)); } } } return result; }; DiffEdtorWidgetInline.prototype.layout = function () { // An editor should not be smaller than 5px return Math.max(5, this.decorationsLeft); }; return DiffEdtorWidgetInline; }(DiffEditorWidgetStyle)); var InlineViewZonesComputer = /** @class */ (function (_super) { __extends(InlineViewZonesComputer, _super); function InlineViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators) { var _this = _super.call(this, lineChanges, originalForeignVZ, modifiedForeignVZ) || this; _this.originalModel = originalEditor.getModel(); _this.modifiedEditorConfiguration = modifiedEditor.getConfiguration(); _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 lineDecorationsWidth = this.modifiedEditorConfiguration.layoutInfo.decorationsWidth; var lineHeight = this.modifiedEditorConfiguration.lineHeight; var typicalHalfwidthCharacterWidth = this.modifiedEditorConfiguration.fontInfo.typicalHalfwidthCharacterWidth; var maxCharsPerLine = 0; for (var lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) { maxCharsPerLine = Math.max(maxCharsPerLine, this._renderOriginalLine(lineNumber - lineChange.originalStartLineNumber, this.originalModel, this.modifiedEditorConfiguration, this.modifiedEditorTabSize, lineNumber, decorations, sb)); if (this.renderIndicators) { var index = lineNumber - lineChange.originalStartLineNumber; marginHTML = marginHTML.concat([ "
    " ]); } } maxCharsPerLine += this.modifiedEditorConfiguration.viewInfo.scrollBeyondLastColumn; var domNode = document.createElement('div'); domNode.className = 'view-lines line-delete'; domNode.innerHTML = sb.build(); configuration_1.Configuration.applyFontInfoSlow(domNode, this.modifiedEditorConfiguration.fontInfo); var marginDomNode = document.createElement('div'); marginDomNode.className = 'inline-deleted-margin-view-zone'; marginDomNode.innerHTML = marginHTML.join(''); configuration_1.Configuration.applyFontInfoSlow(marginDomNode, this.modifiedEditorConfiguration.fontInfo); return { shouldNotShrink: true, afterLineNumber: (lineChange.modifiedEndLineNumber === 0 ? lineChange.modifiedStartLineNumber : lineChange.modifiedStartLineNumber - 1), heightInLines: lineChangeOriginalLength, minWidthInPx: (maxCharsPerLine * typicalHalfwidthCharacterWidth), domNode: domNode, marginDomNode: marginDomNode }; }; InlineViewZonesComputer.prototype._renderOriginalLine = function (count, originalModel, config, tabSize, lineNumber, decorations, sb) { var lineTokens = originalModel.getLineTokens(lineNumber); var lineContent = lineTokens.getLineContent(); 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((config.fontInfo.isMonospace && !config.viewInfo.disableMonospaceOptimizations), config.fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, actualDecorations, tabSize, config.fontInfo.spaceWidth, config.viewInfo.stopRenderingLineAfter, config.viewInfo.renderWhitespace, config.viewInfo.renderControlCharacters, config.viewInfo.fontLigatures), sb); 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[118/*vs/editor/browser/widget/embeddedCodeEditorWidget*/], __M([0/*require*/,1/*exports*/,31/*vs/base/common/objects*/,32/*vs/editor/browser/services/codeEditorService*/,102/*vs/editor/browser/widget/codeEditorWidget*/,27/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,13/*vs/platform/instantiation/common/instantiation*/,35/*vs/platform/notification/common/notification*/,14/*vs/platform/theme/common/themeService*/,75/*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.getRawConfiguration(), {}, 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.getRawConfiguration()); _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[527/*vs/editor/common/services/markerDecorationsServiceImpl*/], __M([0/*require*/,1/*exports*/,66/*vs/platform/markers/common/markers*/,2/*vs/base/common/lifecycle*/,45/*vs/editor/common/model*/,14/*vs/platform/theme/common/themeService*/,34/*vs/editor/common/view/editorColorRegistry*/,42/*vs/editor/common/services/modelService*/,3/*vs/editor/common/core/range*/,46/*vs/base/common/map*/,53/*vs/base/common/network*/,4/*vs/base/common/event*/,20/*vs/base/common/types*/]), 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) { "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 ids = this.model.deltaDecorations(map_1.keys(this._markersData), 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 = 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.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) { if (!rawMarker.tags || rawMarker.tags.indexOf(1 /* Unnecessary */) === -1) { // * 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; switch (marker.severity) { case markers_1.MarkerSeverity.Hint: if (marker.tags && marker.tags.indexOf(1 /* Unnecessary */) >= 0) { 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; 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; break; } if (marker.tags) { if (marker.tags.indexOf(1 /* Unnecessary */) !== -1) { inlineClassName = "squiggly-inline-unnecessary" /* EditorUnnecessaryInlineDecoration */; } } return { stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: className, showIfCollapsed: true, overviewRuler: { color: color, position: model_1.OverviewRulerLane.Right }, zIndex: zIndex, inlineClassName: inlineClassName, }; }; 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[528/*vs/editor/contrib/bracketMatching/bracketMatching*/], __M([0/*require*/,1/*exports*/,314/*vs/nls!vs/editor/contrib/bracketMatching/bracketMatching*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/browser/editorExtensions*/,12/*vs/editor/common/core/position*/,22/*vs/editor/common/core/selection*/,21/*vs/editor/common/editorContextKeys*/,45/*vs/editor/common/model*/,29/*vs/editor/common/model/textModel*/,34/*vs/editor/common/view/editorColorRegistry*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,58/*vs/platform/actions/common/actions*/,404/*vs/css!vs/editor/contrib/bracketMatching/bracketMatching*/]), function (require, exports, nls, async_1, lifecycle_1, editorExtensions_1, position_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: null, 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: null }) || this; } SelectToBracketAction.prototype.run = function (accessor, editor) { var controller = BracketMatchingController.get(editor); if (!controller) { return; } controller.selectToBracket(); }; return SelectToBracketAction; }(editorExtensions_1.EditorAction)); var BracketsData = /** @class */ (function () { function BracketsData(position, brackets) { this.position = position; this.brackets = brackets; } 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.getConfiguration().contribInfo.matchBrackets; _this._updateBracketsSoon.schedule(); _this._register(editor.onDidChangeCursorPosition(function (e) { if (!_this._matchBrackets) { // 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) { _this._matchBrackets = _this._editor.getConfiguration().contribInfo.matchBrackets; if (!_this._matchBrackets && _this._decorations.length > 0) { // Remove existing decorations if bracket matching is off _this._decorations = _this._editor.deltaDecorations(_this._decorations, []); } _this._updateBracketsSoon.schedule(); })); return _this; } BracketMatchingController.get = function (editor) { return editor.getContribution(BracketMatchingController.ID); }; BracketMatchingController.prototype.getId = function () { return 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 next bracket if the position isn't on a matching 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 () { 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); var openBracket = null; var closeBracket = null; if (!brackets) { var nextBracket = model.findNextBracket(position); if (nextBracket && nextBracket.range) { brackets = model.matchBracket(nextBracket.range.getStartPosition()); } } if (brackets) { if (brackets[0].startLineNumber === brackets[1].startLineNumber) { openBracket = brackets[1].startColumn < brackets[0].startColumn ? brackets[1].getStartPosition() : brackets[0].getStartPosition(); closeBracket = brackets[1].startColumn < brackets[0].startColumn ? brackets[0].getEndPosition() : brackets[1].getEndPosition(); } else { openBracket = brackets[1].startLineNumber < brackets[0].startLineNumber ? brackets[1].getStartPosition() : brackets[0].getStartPosition(); closeBracket = brackets[1].startLineNumber < brackets[0].startLineNumber ? brackets[0].getEndPosition() : brackets[1].getEndPosition(); } } if (openBracket && closeBracket) { newSelections.push(new selection_1.Selection(openBracket.lineNumber, openBracket.column, closeBracket.lineNumber, closeBracket.column)); } }); if (newSelections.length > 0) { this._editor.setSelections(newSelections); this._editor.revealRange(newSelections[0]); } }; BracketMatchingController.prototype._updateBrackets = function () { if (!this._matchBrackets) { return; } this._recomputeBrackets(); var newDecorations = [], newDecorationsLen = 0; for (var i = 0, len = this._lastBracketsData.length; i < len; i++) { var brackets = this._lastBracketsData[i].brackets; if (brackets) { newDecorations[newDecorationsLen++] = { range: brackets[0], options: BracketMatchingController._DECORATION_OPTIONS }; newDecorations[newDecorationsLen++] = { range: brackets[1], options: BracketMatchingController._DECORATION_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 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 selections = this._editor.getSelections(); 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); newData[newDataLen++] = new BracketsData(position, brackets); } } this._lastBracketsData = newData; this._lastVersionId = versionId; }; BracketMatchingController.ID = 'editor.contrib.bracketMatchingController'; BracketMatchingController._DECORATION_OPTIONS = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'bracket-match', overviewRuler: { color: themeService_1.themeColorFromId(overviewRulerBracketMatchForeground), position: model_1.OverviewRulerLane.Center } }); return BracketMatchingController; }(lifecycle_1.Disposable)); exports.BracketMatchingController = BracketMatchingController; editorExtensions_1.registerEditorContribution(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(16 /* 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[529/*vs/editor/contrib/codelens/codelensWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,19/*vs/base/common/arrays*/,5/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,29/*vs/editor/common/model/textModel*/,34/*vs/editor/common/view/editorColorRegistry*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,394/*vs/css!vs/editor/contrib/codelens/codelensWidget*/]), function (require, exports, dom, arrays_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, symbolRange, data) { // Editor.IContentWidget.allowEditorOverflow this.allowEditorOverflow = false; this.suppressMouseDown = true; this._commands = new Map(); this._id = 'codeLensWidget' + (++CodeLensContentWidget._idPool); this._editor = editor; this.setSymbolRange(symbolRange); this._domNode = document.createElement('span'); this._domNode.innerHTML = ' '; dom.addClass(this._domNode, 'codelens-decoration'); this.updateHeight(); this.withCommands(data.map(function (data) { return data.symbol; }), false); } CodeLensContentWidget.prototype.updateHeight = function () { var _a = this._editor.getConfiguration(), fontInfo = _a.fontInfo, lineHeight = _a.lineHeight; this._domNode.style.height = Math.round(lineHeight * 1.1) + "px"; this._domNode.style.lineHeight = lineHeight + "px"; this._domNode.style.fontSize = Math.round(fontInfo.fontSize * 0.9) + "px"; this._domNode.style.paddingRight = Math.round(fontInfo.fontSize * 0.45) + "px"; this._domNode.innerHTML = ' '; }; CodeLensContentWidget.prototype.withCommands = function (inSymbols, animate) { this._commands.clear(); var symbols = arrays_1.coalesce(inSymbols); if (arrays_1.isFalsyOrEmpty(symbols)) { this._domNode.innerHTML = 'no commands'; return; } var html = []; for (var i = 0; i < symbols.length; i++) { var command = symbols[i].command; if (command) { var title = strings_1.escape(command.title); var part = void 0; if (command.id) { part = "" + title + ""; this._commands.set(String(i), command); } else { part = "" + title + ""; } html.push(part); } } var wasEmpty = this._domNode.innerHTML === '' || this._domNode.innerHTML === ' '; this._domNode.innerHTML = html.join(' | '); this._editor.layoutContentWidget(this); if (wasEmpty && animate) { dom.addClass(this._domNode, 'fadein'); } }; 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.setSymbolRange = function (range) { if (!this._editor.hasModel()) { return; } var lineNumber = range.startLineNumber; var column = this._editor.getModel().getLineFirstNonWhitespaceColumn(lineNumber); this._widgetPosition = { position: { lineNumber: lineNumber, column: column }, preference: [1 /* ABOVE */] }; }; CodeLensContentWidget.prototype.getPosition = function () { return this._widgetPosition; }; CodeLensContentWidget.prototype.isVisible = function () { return this._domNode.hasAttribute('monaco-visible-content-widget'); }; 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 CodeLens = /** @class */ (function () { function CodeLens(data, editor, helper, viewZoneChangeAccessor, updateCallback) { var _this = this; this._editor = editor; this._data = data; this._decorationIds = new Array(this._data.length); var range; this._data.forEach(function (codeLensData, i) { 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); } }); if (range) { this._contentWidget = new CodeLensContentWidget(editor, range, this._data); this._viewZone = new CodeLensViewZone(range.startLineNumber - 1, updateCallback); this._viewZoneId = viewZoneChangeAccessor.addZone(this._viewZone); this._editor.addContentWidget(this._contentWidget); } } CodeLens.prototype.dispose = function (helper, viewZoneChangeAccessor) { while (this._decorationIds.length) { helper.removeDecoration(this._decorationIds.pop()); } if (viewZoneChangeAccessor) { viewZoneChangeAccessor.removeZone(this._viewZoneId); } this._editor.removeContentWidget(this._contentWidget); }; CodeLens.prototype.isValid = function () { var _this = this; if (!this._editor.hasModel()) { return false; } var model = this._editor.getModel(); return this._decorationIds.some(function (id, i) { var range = model.getDecorationRange(id); var symbol = _this._data[i].symbol; return !!(range && range_1.Range.isEmpty(symbol.range) === range.isEmpty()); }); }; CodeLens.prototype.updateCodeLensSymbols = function (data, helper) { var _this = this; while (this._decorationIds.length) { helper.removeDecoration(this._decorationIds.pop()); } this._data = data; this._decorationIds = new Array(this._data.length); this._data.forEach(function (codeLensData, i) { helper.addDecoration({ range: codeLensData.symbol.range, options: textModel_1.ModelDecorationOptions.EMPTY }, function (id) { return _this._decorationIds[i] = id; }); }); }; CodeLens.prototype.computeIfNecessary = function (model) { if (!this._contentWidget.isVisible()) { 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; }; CodeLens.prototype.updateCommands = function (symbols) { 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; } } }; CodeLens.prototype.updateHeight = function () { this._contentWidget.updateHeight(); }; CodeLens.prototype.getCommand = function (link) { return this._contentWidget.getCommand(link); }; CodeLens.prototype.getLineNumber = function () { if (this._editor.hasModel()) { var range = this._editor.getModel().getDecorationRange(this._decorationIds[0]); if (range) { return range.startLineNumber; } } return -1; }; CodeLens.prototype.update = function (viewZoneChangeAccessor) { if (this.isValid() && this._editor.hasModel()) { var range = this._editor.getModel().getDecorationRange(this._decorationIds[0]); if (range) { this._viewZone.afterLineNumber = range.startLineNumber - 1; viewZoneChangeAccessor.layoutZone(this._viewZoneId); this._contentWidget.setSymbolRange(range); this._editor.layoutContentWidget(this._contentWidget); } } }; return CodeLens; }()); exports.CodeLens = CodeLens; themeService_1.registerThemingParticipant(function (theme, collector) { var codeLensForeground = theme.getColor(editorColorRegistry_1.editorCodeLensForeground); if (codeLensForeground) { collector.addRule(".monaco-editor .codelens-decoration { color: " + codeLensForeground + "; }"); } var activeLinkForeground = theme.getColor(colorRegistry_1.editorActiveLinkForeground); if (activeLinkForeground) { collector.addRule(".monaco-editor .codelens-decoration > a:hover { 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[530/*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*/,64/*vs/editor/browser/core/editorState*/,11/*vs/editor/browser/editorExtensions*/,16/*vs/editor/common/modes*/,471/*vs/editor/contrib/codelens/codelens*/,529/*vs/editor/contrib/codelens/codelensWidget*/,27/*vs/platform/commands/common/commands*/,35/*vs/platform/notification/common/notification*/,188/*vs/editor/contrib/codelens/codeLensCache*/]), 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) { "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._isEnabled = this._editor.getConfiguration().contribInfo.codeLens; this._globalToDispose = []; this._localToDispose = []; this._lenses = []; this._currentFindCodeLensSymbolsPromise = null; this._modelChangeCounter = 0; this._globalToDispose.push(this._editor.onDidChangeModel(function () { return _this._onModelChange(); })); this._globalToDispose.push(this._editor.onDidChangeModelLanguage(function () { return _this._onModelChange(); })); this._globalToDispose.push(this._editor.onDidChangeConfiguration(function (e) { var prevIsEnabled = _this._isEnabled; _this._isEnabled = _this._editor.getConfiguration().contribInfo.codeLens; if (prevIsEnabled !== _this._isEnabled) { _this._onModelChange(); } })); this._globalToDispose.push(modes_1.CodeLensProviderRegistry.onDidChange(this._onModelChange, this)); this._onModelChange(); } CodeLensContribution.prototype.dispose = function () { this._localDispose(); this._globalToDispose = lifecycle_1.dispose(this._globalToDispose); }; CodeLensContribution.prototype._localDispose = function () { if (this._currentFindCodeLensSymbolsPromise) { this._currentFindCodeLensSymbolsPromise.cancel(); this._currentFindCodeLensSymbolsPromise = null; this._modelChangeCounter++; } if (this._currentResolveCodeLensSymbolsPromise) { this._currentResolveCodeLensSymbolsPromise.cancel(); this._currentResolveCodeLensSymbolsPromise = null; } this._localToDispose = lifecycle_1.dispose(this._localToDispose); }; CodeLensContribution.prototype.getId = function () { return CodeLensContribution.ID; }; 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.push(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.push(registration); } } this._detectVisibleLenses = new async_1.RunOnceScheduler(function () { _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 _this._codeLensCache.put(model, result); _this._renderCodeLensSymbols(result); _this._detectVisibleLenses.schedule(); } }, errors_1.onUnexpectedError); }, 250); this._localToDispose.push(scheduler); this._localToDispose.push(this._detectVisibleLenses); this._localToDispose.push(this._editor.onDidChangeModelContent(function (e) { _this._editor.changeDecorations(function (changeAccessor) { _this._editor.changeViewZones(function (viewAccessor) { 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(viewAccessor); lastLensLineNumber = lens.getLineNumber(); } }); var helper = new codelensWidget_1.CodeLensHelper(); toDispose.forEach(function (l) { l.dispose(helper, viewAccessor); _this._lenses.splice(_this._lenses.indexOf(l), 1); }); helper.commit(changeAccessor); }); }); // Compute new `visible` code lenses _this._detectVisibleLenses.schedule(); // Ask for all references again scheduler.schedule(); })); this._localToDispose.push(this._editor.onDidScrollChange(function (e) { if (e.scrollTopChanged && _this._lenses.length > 0) { _this._detectVisibleLenses.schedule(); } })); this._localToDispose.push(this._editor.onDidLayoutChange(function (e) { _this._detectVisibleLenses.schedule(); })); this._localToDispose.push(lifecycle_1.toDisposable(function () { if (_this._editor.getModel()) { var scrollState = editorState_1.StableEditorScrollState.capture(_this._editor); _this._editor.changeDecorations(function (changeAccessor) { _this._editor.changeViewZones(function (accessor) { _this._disposeAllLenses(changeAccessor, accessor); }); }); scrollState.restore(_this._editor); } else { // No accessors available _this._disposeAllLenses(undefined, undefined); } })); this._localToDispose.push(this._editor.onDidChangeConfiguration(function (e) { if (e.fontInfo) { for (var _i = 0, _a = _this._lenses; _i < _a.length; _i++) { var lens = _a[_i]; lens.updateHeight(); } } })); this._localToDispose.push(this._editor.onMouseUp(function (e) { var _a; if (e.target.type === 9 /* CONTENT_WIDGET */ && e.target.element && e.target.element.tagName === 'A') { for (var _i = 0, _b = _this._lenses; _i < _b.length; _i++) { var lens = _b[_i]; var command = lens.getCommand(e.target.element); if (command) { (_a = _this._commandService).executeCommand.apply(_a, [command.id].concat((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(); this._lenses.forEach(function (lens) { return 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, symbols_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_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 (changeAccessor) { _this._editor.changeViewZones(function (accessor) { var codeLensIndex = 0, groupsIndex = 0, helper = new codelensWidget_1.CodeLensHelper(); 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, accessor); _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.CodeLens(groups[groupsIndex], _this._editor, helper, accessor, function () { return _this._detectVisibleLenses.schedule(); })); codeLensIndex++; groupsIndex++; } } // Delete extra code lenses while (codeLensIndex < _this._lenses.length) { _this._lenses[codeLensIndex].dispose(helper, accessor); _this._lenses.splice(codeLensIndex, 1); } // Create extra symbols while (groupsIndex < groups.length) { _this._lenses.push(new codelensWidget_1.CodeLens(groups[groupsIndex], _this._editor, helper, accessor, function () { return _this._detectVisibleLenses.schedule(); })); groupsIndex++; } helper.commit(changeAccessor); }); }); scrollState.restore(this._editor); }; CodeLensContribution.prototype._onViewportChanged = function () { var _this = this; if (this._currentResolveCodeLensSymbolsPromise) { this._currentResolveCodeLensSymbolsPromise.cancel(); this._currentResolveCodeLensSymbolsPromise = null; } 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; } this._currentResolveCodeLensSymbolsPromise = 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 () { lenses[i].updateCommands(resolvedSymbols); }); }); return Promise.all(promises); }); this._currentResolveCodeLensSymbolsPromise.then(function () { _this._currentResolveCodeLensSymbolsPromise = null; }).catch(function (err) { _this._currentResolveCodeLensSymbolsPromise = null; errors_1.onUnexpectedError(err); }); }; 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); }); /*--------------------------------------------------------------------------------------------- * 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/colorPicker/colorPickerWidget*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,72/*vs/base/browser/globalMouseMoveMonitor*/,44/*vs/base/browser/ui/widget*/,28/*vs/base/common/color*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,393/*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.addDisposableListener(_this.domNode, dom.EventType.MOUSE_DOWN, 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(globalMouseMoveMonitor_1.standardMouseMoveMerger, function (event) { return _this.onDidChangePosition(event.posx - origin.left, event.posy - origin.top); }, function () { return null; }); var mouseUpListener = dom.addDisposableListener(document, dom.EventType.MOUSE_UP, 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.addDisposableListener(_this.domNode, dom.EventType.MOUSE_DOWN, 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(globalMouseMoveMonitor_1.standardMouseMoveMerger, function (event) { return _this.onDidChangeTop(event.posy - origin.top); }, function () { return null; }); var mouseUpListener = dom.addDisposableListener(document, dom.EventType.MOUSE_UP, 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; }); /*--------------------------------------------------------------------------------------------- * 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/find/findDecorations*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,45/*vs/editor/common/model*/,29/*vs/editor/common/model/textModel*/,23/*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 } }); 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 } }); 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[121/*vs/editor/contrib/find/findModel*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,77/*vs/editor/common/commands/replaceCommand*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,137/*vs/editor/common/model/textModelSearch*/,532/*vs/editor/contrib/find/findDecorations*/,249/*vs/editor/contrib/find/replaceAllCommand*/,250/*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', 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._editor = editor; this._state = state; this._toDispose = []; this._isDisposed = false; this._startSearchingTimer = new async_1.TimeoutTimer(); this._decorations = new findDecorations_1.FindDecorations(editor); this._toDispose.push(this._decorations); this._updateDecorationsScheduler = new async_1.RunOnceScheduler(function () { return _this.research(false); }, 100); this._toDispose.push(this._updateDecorationsScheduler); this._toDispose.push(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.push(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.push(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 = lifecycle_1.dispose(this._toDispose); }; 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.getConfiguration().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.getConfiguration().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.getConfiguration().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.getConfiguration().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(), replacePattern.hasReplacementPatterns, false); if (nextMatch) { if (selection.equalsRange(nextMatch.range)) { // selection sits on a find match => replace it! var replaceString = replacePattern.buildReplaceString(nextMatch.matches); 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.getConfiguration().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.getConfiguration().wordSeparators : null); var searchData = searchParams.parseSearchRequest(); if (!searchData) { return; } var searchRegex = searchData.regex; if (!searchRegex.multiline) { var mod = 'm'; 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; if (replacePattern.hasReplacementPatterns) { resultText = modelText.replace(searchRegex, function () { return replacePattern.buildReplaceString(arguments); }); } else { resultText = modelText.replace(searchRegex, replacePattern.buildReplaceString(null)); } 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, 1073741824 /* MAX_SAFE_SMALL_INTEGER */); var replaceStrings = []; for (var i = 0, len = matches.length; i < len; i++) { replaceStrings[i] = replacePattern.buildReplaceString(matches[i].matches); } 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[534/*vs/editor/contrib/find/findOptionsWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,189/*vs/base/browser/ui/findinput/findInputCheckboxes*/,44/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/,121/*vs/editor/contrib/find/findModel*/,23/*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); _this.caseSensitive = _this._register(new findInputCheckboxes_1.CaseSensitiveCheckbox({ appendTitle: _this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleCaseSensitiveCommand), isChecked: _this._state.matchCase, inputActiveOptionBorder: inputActiveOptionBorderColor })); _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 })); _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 })); _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) }; 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 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[535/*vs/editor/contrib/find/findWidget*/], __M([0/*require*/,1/*exports*/,323/*vs/nls!vs/editor/contrib/find/findWidget*/,7/*vs/base/browser/dom*/,96/*vs/base/browser/ui/sash/sash*/,44/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,5/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,121/*vs/editor/contrib/find/findModel*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,457/*vs/platform/browser/contextScopedHistoryWidget*/,388/*vs/css!vs/editor/contrib/find/findWidget*/]), function (require, exports, nls, dom, 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 = 411; var PART_WIDTH = 275; var FIND_INPUT_AREA_WIDTH = PART_WIDTH - 54; var REPLACE_INPUT_AREA_WIDTH = FIND_INPUT_AREA_WIDTH; var MAX_MATCHES_COUNT_WIDTH = 69; var 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 = 34; // The height of Find Widget when Replace Input is not visible. var FIND_REPLACE_AREA_HEIGHT = 64; // The height of Find Widget when Replace Input is visible. 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; var FindWidget = /** @class */ (function (_super) { __extends(FindWidget, _super); function FindWidget(codeEditor, controller, state, contextViewProvider, keybindingService, contextKeyService, themeService) { var _this = _super.call(this) || this; _this._codeEditor = codeEditor; _this._controller = controller; _this._state = state; _this._contextViewProvider = contextViewProvider; _this._keybindingService = keybindingService; _this._contextKeyService = contextKeyService; _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._register(_this._codeEditor.onDidChangeConfiguration(function (e) { if (e.readOnly) { if (_this._codeEditor.getConfiguration().readOnly) { // Hide replace part if editor becomes read only _this._state.change({ isReplaceRevealed: false }, false); } _this._updateButtons(); } if (e.layoutInfo) { _this._tryUpdateWidgetWidth(); } if (e.accessibilitySupport) { _this.updateAccessibilitySupport(); } if (e.contribInfo) { var addExtraSpaceOnTop = _this._codeEditor.getConfiguration().contribInfo.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._replaceInputBox.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.getConfiguration().contribInfo.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; } if (_this._viewZoneId === undefined) { return; } _this._codeEditor.changeViewZones(function (accessor) { if (_this._viewZoneId) { accessor.removeZone(_this._viewZoneId); } _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._replaceInputBox.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.getConfiguration().readOnly && !this._isReplaceVisible) { this._isReplaceVisible = true; this._replaceInputBox.width = this._findInput.inputBox.width; this._updateButtons(); } } else { if (this._isReplaceVisible) { this._isReplaceVisible = false; this._updateButtons(); } } } 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._replaceInputBox.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)); MAX_MATCHES_COUNT_WIDTH = Math.max(MAX_MATCHES_COUNT_WIDTH, this._matchesCount.clientWidth); }; // ----- actions /** * 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; this._toggleSelectionFind.setEnabled(this._isVisible && (isChecked || isSelection)); }; FindWidget.prototype._updateButtons = function () { this._findInput.setEnabled(this._isVisible); this._replaceInputBox.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('collapse', !this._isReplaceVisible); this._toggleReplaceBtn.toggleClass('expand', this._isReplaceVisible); this._toggleReplaceBtn.setExpanded(this._isReplaceVisible); var canReplace = !this._codeEditor.getConfiguration().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(); var isSelection = selection ? (selection.startLineNumber !== selection.endLineNumber || selection.startColumn !== selection.endColumn) : false; if (isSelection && this._codeEditor.getConfiguration().contribInfo.find.autoFindInSelection) { this._toggleSelectionFind.checked = true; } else { this._toggleSelectionFind.checked = false; } 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.getConfiguration().contribInfo.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.getConfiguration().contribInfo.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) { if (_this._state.isReplaceRevealed) { viewZone.heightInPx = FIND_REPLACE_AREA_HEIGHT; } else { viewZone.heightInPx = FIND_INPUT_AREA_HEIGHT; } _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; } var viewZone = this._viewZone; if (!this._isVisible || !viewZone) { return; } this._codeEditor.changeViewZones(function (accessor) { var scrollAdjustment = FIND_INPUT_AREA_HEIGHT; if (_this._viewZoneId !== undefined) { if (_this._state.isReplaceRevealed) { viewZone.heightInPx = FIND_REPLACE_AREA_HEIGHT; scrollAdjustment = FIND_REPLACE_AREA_HEIGHT - FIND_INPUT_AREA_HEIGHT; } else { viewZone.heightInPx = FIND_INPUT_AREA_HEIGHT; scrollAdjustment = FIND_INPUT_AREA_HEIGHT - FIND_REPLACE_AREA_HEIGHT; } accessor.removeZone(_this._viewZoneId); } else { viewZone.heightInPx = FIND_INPUT_AREA_HEIGHT; } _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), 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._replaceInputBox.style(inputStyles); }; FindWidget.prototype._tryUpdateWidgetWidth = function () { if (!this._isVisible) { return; } var editorWidth = this._codeEditor.getConfiguration().layoutInfo.width; var minimapWidth = this._codeEditor.getConfiguration().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._replaceInputBox.inputElement.style.width = dom.getTotalWidth(this._findInput.inputBox.inputElement) + "px"; 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) { var findInputWidth = dom.getTotalWidth(this._findInput.inputBox.inputElement); if (findInputWidth > 0) { this._replaceInputBox.inputElement.style.width = findInputWidth + "px"; } } }; // ----- Public FindWidget.prototype.focusFindInput = function () { this._findInput.select(); // Edge browser requires focus() in addition to select() this._findInput.focus(); }; FindWidget.prototype.focusReplaceInput = function () { this._replaceInputBox.select(); // Edge browser requires focus() in addition to select() this._replaceInputBox.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(3 /* Enter */)) { this._codeEditor.getAction(findModel_1.FIND_IDS.NextMatchFindAction).run().then(undefined, errors_1.onUnexpectedError); e.preventDefault(); return; } if (e.equals(1024 /* Shift */ | 3 /* Enter */)) { this._codeEditor.getAction(findModel_1.FIND_IDS.PreviousMatchFindAction).run().then(undefined, errors_1.onUnexpectedError); e.preventDefault(); return; } if (e.equals(2 /* Tab */)) { if (this._isReplaceVisible) { this._replaceInputBox.focus(); } else { this._findInput.focusOnCaseSensitive(); } e.preventDefault(); return; } if (e.equals(2048 /* CtrlCmd */ | 18 /* DownArrow */)) { this._codeEditor.focus(); e.preventDefault(); return; } }; FindWidget.prototype._onReplaceInputKeyDown = function (e) { if (e.equals(3 /* Enter */)) { this._controller.replace(); e.preventDefault(); return; } if (e.equals(2048 /* CtrlCmd */ | 3 /* Enter */)) { this._controller.replaceAll(); 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; } }; // ----- 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._buildFindPart = function () { var _this = this; // 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 { /* tslint:disable-next-line:no-unused-expression */ new RegExp(value); return null; } catch (e) { return { content: e.message }; } } }, 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._replaceInputBox.focus(); e.preventDefault(); } } })); 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: 'previous', 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: 'next', 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); findPart.appendChild(this._matchesCount); findPart.appendChild(this._prevBtn.domNode); findPart.appendChild(this._nextBtn.domNode); // Toggle selection button this._toggleSelectionFind = this._register(new SimpleCheckbox({ parent: findPart, title: NLS_TOGGLE_SELECTION_FIND_TITLE + this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleSearchScopeCommand), 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); } } })); // Close button this._closeBtn = this._register(new SimpleButton({ label: NLS_CLOSE_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.CloseFindWidgetCommand), className: 'close-fw', 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(); } } } })); findPart.appendChild(this._closeBtn.domNode); return findPart; }; FindWidget.prototype._buildReplacePart = function () { var _this = this; // Replace input var replaceInput = document.createElement('div'); replaceInput.className = 'replace-input'; replaceInput.style.width = REPLACE_INPUT_AREA_WIDTH + 'px'; this._replaceInputBox = this._register(new contextScopedHistoryWidget_1.ContextScopedHistoryInputBox(replaceInput, undefined, { ariaLabel: NLS_REPLACE_INPUT_LABEL, placeholder: NLS_REPLACE_INPUT_PLACEHOLDER, history: [] }, this._contextKeyService)); this._register(dom.addStandardDisposableListener(this._replaceInputBox.inputElement, 'keydown', function (e) { return _this._onReplaceInputKeyDown(e); })); this._register(this._replaceInputBox.onDidChange(function () { _this._state.change({ replaceString: _this._replaceInputBox.value }, false); })); // Replace one button this._replaceBtn = this._register(new SimpleButton({ label: NLS_REPLACE_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.ReplaceOneAction), className: '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: 'replace-all', onTrigger: function () { _this._controller.replaceAll(); } })); var replacePart = document.createElement('div'); replacePart.className = 'replace-part'; replacePart.appendChild(replaceInput); replacePart.appendChild(this._replaceBtn.domNode); replacePart.appendChild(this._replaceAllBtn.domNode); return replacePart; }; FindWidget.prototype._buildDomNode = function () { var _this = this; // Find part var findPart = this._buildFindPart(); // Replace part var replacePart = this._buildReplacePart(); // Toggle replace button this._toggleReplaceBtn = this._register(new SimpleButton({ label: NLS_TOGGLE_REPLACE_MODE_BTN_LABEL, className: 'toggle left', onTrigger: function () { _this._state.change({ isReplaceRevealed: !_this._isReplaceVisible }, false); if (_this._isReplaceVisible) { _this._replaceInputBox.width = _this._findInput.inputBox.width; } _this._showViewZone(); } })); this._toggleReplaceBtn.toggleClass('expand', this._isReplaceVisible); this._toggleReplaceBtn.toggleClass('collapse', !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._buildSash(); }; FindWidget.prototype._buildSash = function () { var _this = this; 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 inputBoxWidth = width - FIND_ALL_CONTROLS_WIDTH; var maxWidth = parseFloat(dom.getComputedStyle(_this._domNode).maxWidth) || 0; if (width > maxWidth) { return; } _this._domNode.style.width = width + "px"; if (_this._isReplaceVisible) { _this._replaceInputBox.width = inputBoxWidth; } })); }; FindWidget.prototype.updateAccessibilitySupport = function () { var value = this._codeEditor.getConfiguration().accessibilitySupport; this._findInput.setFocusInputOnOptionClick(value !== 2 /* Enabled */); }; FindWidget.ID = 'editor.contrib.findWidget'; return FindWidget; }(widget_1.Widget)); exports.FindWidget = FindWidget; var SimpleCheckbox = /** @class */ (function (_super) { __extends(SimpleCheckbox, _super); function SimpleCheckbox(opts) { var _this = _super.call(this) || this; _this._opts = opts; _this._domNode = document.createElement('div'); _this._domNode.className = 'monaco-checkbox'; _this._domNode.title = _this._opts.title; _this._domNode.tabIndex = 0; _this._checkbox = document.createElement('input'); _this._checkbox.type = 'checkbox'; _this._checkbox.className = 'checkbox'; _this._checkbox.id = 'checkbox-' + SimpleCheckbox._COUNTER++; _this._checkbox.tabIndex = -1; _this._label = document.createElement('label'); _this._label.className = 'label'; // Connect the label and the checkbox. Checkbox will get checked when the label receives a click. _this._label.htmlFor = _this._checkbox.id; _this._label.tabIndex = -1; _this._domNode.appendChild(_this._checkbox); _this._domNode.appendChild(_this._label); _this._opts.parent.appendChild(_this._domNode); _this.onchange(_this._checkbox, function () { _this._opts.onChange(); }); return _this; } Object.defineProperty(SimpleCheckbox.prototype, "domNode", { get: function () { return this._domNode; }, enumerable: true, configurable: true }); Object.defineProperty(SimpleCheckbox.prototype, "checked", { get: function () { return this._checkbox.checked; }, set: function (newValue) { this._checkbox.checked = newValue; }, enumerable: true, configurable: true }); SimpleCheckbox.prototype.enable = function () { this._checkbox.removeAttribute('disabled'); }; SimpleCheckbox.prototype.disable = function () { this._checkbox.disabled = true; }; SimpleCheckbox.prototype.setEnabled = function (enabled) { if (enabled) { this.enable(); this.domNode.tabIndex = 0; } else { this.disable(); this.domNode.tabIndex = -1; } }; SimpleCheckbox._COUNTER = 0; return SimpleCheckbox; }(widget_1.Widget)); 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: 2px solid " + hcBorder + "; }"); } 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;}"); } } var inputActiveBorder = theme.getColor(colorRegistry_1.inputActiveOptionBorder); if (inputActiveBorder) { collector.addRule(".monaco-editor .find-widget .monaco-checkbox .checkbox:checked + .label { border: 1px solid " + inputActiveBorder.toString() + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[222/*vs/editor/contrib/find/findController*/], __M([0/*require*/,1/*exports*/,322/*vs/nls!vs/editor/contrib/find/findController*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,11/*vs/editor/browser/editorExtensions*/,21/*vs/editor/common/editorContextKeys*/,121/*vs/editor/contrib/find/findModel*/,534/*vs/editor/contrib/find/findOptionsWidget*/,248/*vs/editor/contrib/find/findState*/,535/*vs/editor/contrib/find/findWidget*/,176/*vs/platform/clipboard/common/clipboardService*/,18/*vs/platform/contextkey/common/contextkey*/,59/*vs/platform/contextview/browser/contextView*/,13/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,68/*vs/platform/storage/common/storage*/,14/*vs/platform/theme/common/themeService*/]), 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) { "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) }, false); if (shouldRestartFind) { _this._start({ forceRevealReplace: false, seedSearchStringFromSelection: false && _this._editor.getConfiguration().contribInfo.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.getId = function () { return CommonFindController.ID; }; 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 */); } }; 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) }, 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.getConfiguration().contribInfo.find.globalFindClipboard && this._clipboardService && this._editor.hasModel() && !this._editor.getModel().isTooLargeForSyncing()) { return this._clipboardService.readFindText(); } return ''; }; CommonFindController.prototype.setGlobalBufferTerm = function (text) { if (this._editor.getConfiguration().contribInfo.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, storageService, clipboardService) { var _this = _super.call(this, editor, _contextKeyService, storageService, clipboardService) || this; _this._contextViewService = _contextViewService; _this._keybindingService = _keybindingService; _this._themeService = _themeService; return _this; } FindController.prototype._start = function (opts) { if (!this._widget) { this._createFindWidget(); } if (!this._widget.getPosition() && this._editor.getConfiguration().contribInfo.find.autoFindInSelection) { // not visible yet so we need to set search scope if `editor.find.autoFindInSelection` is `true` opts.updateSearchScope = true; } _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._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, storage_1.IStorageService), __param(6, 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: null, kbOpts: { kbExpr: null, primary: 2048 /* CtrlCmd */ | 36 /* KEY_F */, weight: 100 /* EditorContrib */ }, menubarOpts: { menuId: 14 /* 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.getConfiguration().contribInfo.find.seedSearchStringFromSelection, seedSearchStringFromGlobalClipboard: editor.getConfiguration().contribInfo.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: null, 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: 1 /* FocusFindInput */, 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.getConfiguration().contribInfo.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: null, 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 PreviousMatchFindAction = /** @class */ (function (_super) { __extends(PreviousMatchFindAction, _super); function PreviousMatchFindAction() { return _super.call(this, { id: findModel_1.FIND_IDS.PreviousMatchFindAction, label: nls.localize(4, null), alias: 'Find Previous', precondition: null, 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 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.getConfiguration().contribInfo.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(5, null), alias: 'Find Next Selection', precondition: null, 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(6, null), alias: 'Find Previous Selection', precondition: null, 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(7, null), alias: 'Replace', precondition: null, kbOpts: { kbExpr: null, primary: 2048 /* CtrlCmd */ | 38 /* KEY_H */, mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 36 /* KEY_F */ }, weight: 100 /* EditorContrib */ }, menubarOpts: { menuId: 14 /* MenubarEditMenu */, group: '3_find', title: nls.localize(8, null), order: 2 } }) || this; } StartFindReplaceAction.prototype.run = function (accessor, editor) { if (!editor.hasModel() || editor.getConfiguration().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.getConfiguration().contribInfo.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.getConfiguration().contribInfo.find.seedSearchStringFromSelection, shouldFocus: shouldFocus, shouldAnimate: true, updateSearchScope: false }); } }; return StartFindReplaceAction; }(editorExtensions_1.EditorAction)); exports.StartFindReplaceAction = StartFindReplaceAction; editorExtensions_1.registerEditorContribution(FindController); editorExtensions_1.registerEditorAction(StartFindAction); editorExtensions_1.registerEditorAction(StartFindWithSelectionAction); editorExtensions_1.registerEditorAction(NextMatchFindAction); editorExtensions_1.registerEditorAction(PreviousMatchFindAction); 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: null, 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: null, 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: null, 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: null, 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.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.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[537/*vs/editor/contrib/inPlaceReplace/inPlaceReplace*/], __M([0/*require*/,1/*exports*/,334/*vs/nls!vs/editor/contrib/inPlaceReplace/inPlaceReplace*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,21/*vs/editor/common/editorContextKeys*/,11/*vs/editor/browser/editorExtensions*/,63/*vs/editor/common/services/editorWorkerService*/,260/*vs/editor/contrib/inPlaceReplace/inPlaceReplaceCommand*/,64/*vs/editor/browser/core/editorState*/,14/*vs/platform/theme/common/themeService*/,34/*vs/editor/common/view/editorColorRegistry*/,29/*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.getId = function () { return InPlaceReplaceController.ID; }; 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); 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[538/*vs/editor/contrib/links/links*/], __M([0/*require*/,1/*exports*/,336/*vs/nls!vs/editor/contrib/links/links*/,15/*vs/base/common/async*/,24/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,87/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,11/*vs/editor/browser/editorExtensions*/,29/*vs/editor/common/model/textModel*/,16/*vs/editor/common/modes*/,205/*vs/editor/contrib/goToDefinition/clickLinkGesture*/,411/*vs/editor/contrib/links/getLinks*/,35/*vs/platform/notification/common/notification*/,56/*vs/platform/opener/common/opener*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,384/*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 }); var HOVER_MESSAGE_GENERAL_META = new htmlContent_1.MarkdownString().appendText(platform.isMacintosh ? nls.localize(0, null) : nls.localize(1, null)); var HOVER_MESSAGE_COMMAND_META = new htmlContent_1.MarkdownString().appendText(platform.isMacintosh ? nls.localize(2, null) : nls.localize(3, null)); var HOVER_MESSAGE_GENERAL_ALT = new htmlContent_1.MarkdownString().appendText(platform.isMacintosh ? nls.localize(4, null) : nls.localize(5, null)); var HOVER_MESSAGE_COMMAND_ALT = new htmlContent_1.MarkdownString().appendText(platform.isMacintosh ? nls.localize(6, null) : nls.localize(7, null)); var decoration = { meta: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, collapseOnReplaceEdit: true, inlineClassName: 'detected-link', hoverMessage: HOVER_MESSAGE_GENERAL_META }), metaActive: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, collapseOnReplaceEdit: true, inlineClassName: 'detected-link-active', hoverMessage: HOVER_MESSAGE_GENERAL_META }), alt: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, collapseOnReplaceEdit: true, inlineClassName: 'detected-link', hoverMessage: HOVER_MESSAGE_GENERAL_ALT }), altActive: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, collapseOnReplaceEdit: true, inlineClassName: 'detected-link-active', hoverMessage: HOVER_MESSAGE_GENERAL_ALT }), altCommand: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, collapseOnReplaceEdit: true, inlineClassName: 'detected-link', hoverMessage: HOVER_MESSAGE_COMMAND_ALT }), altCommandActive: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, collapseOnReplaceEdit: true, inlineClassName: 'detected-link-active', hoverMessage: HOVER_MESSAGE_COMMAND_ALT }), metaCommand: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, collapseOnReplaceEdit: true, inlineClassName: 'detected-link', hoverMessage: HOVER_MESSAGE_COMMAND_META }), metaCommandActive: textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, collapseOnReplaceEdit: true, inlineClassName: 'detected-link-active', hoverMessage: HOVER_MESSAGE_COMMAND_META }), }; 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) { if (link.url && /^command:/i.test(link.url.toString())) { if (useMetaKey) { return (isActive ? decoration.metaCommandActive : decoration.metaCommand); } else { return (isActive ? decoration.altCommandActive : decoration.altCommand); } } else { if (useMetaKey) { return (isActive ? decoration.metaActive : decoration.meta); } else { return (isActive ? decoration.altActive : decoration.alt); } } }; 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.editor = editor; this.openerService = openerService; this.notificationService = notificationService; this.listenersToRemove = []; var clickLinkGesture = new clickLinkGesture_1.ClickLinkGesture(editor); this.listenersToRemove.push(clickLinkGesture); this.listenersToRemove.push(clickLinkGesture.onMouseMoveOrRelevantKeyDown(function (_a) { var mouseEvent = _a[0], keyboardEvent = _a[1]; _this._onEditorMouseMove(mouseEvent, keyboardEvent); })); this.listenersToRemove.push(clickLinkGesture.onExecute(function (e) { _this.onEditorMouseUp(e); })); this.listenersToRemove.push(clickLinkGesture.onCancel(function (e) { _this.cleanUpActiveLinkDecoration(); })); this.enabled = editor.getConfiguration().contribInfo.links; this.listenersToRemove.push(editor.onDidChangeConfiguration(function (e) { var enabled = editor.getConfiguration().contribInfo.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.push(editor.onDidChangeModelContent(function (e) { return _this.onChange(); })); this.listenersToRemove.push(editor.onDidChangeModel(function (e) { return _this.onModelChanged(); })); this.listenersToRemove.push(editor.onDidChangeModelLanguage(function (e) { return _this.onModelModeChanged(); })); this.listenersToRemove.push(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.getId = function () { return 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.getConfiguration().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.getConfiguration().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.getConfiguration().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); }; LinkDetector.prototype.openLinkOccurrence = function (occurrence, openToSide) { var _this = this; 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 }); }, function (err) { // different error cases if (err === 'invalid') { _this.notificationService.warn(nls.localize(8, null, link.url.toString())); } else if (err === 'missing') { _this.notificationService.warn(nls.localize(9, 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 = lifecycle_1.dispose(this.listenersToRemove); 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(10, null), alias: 'Open Link', precondition: null }) || 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); 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[128/*vs/editor/contrib/message/messageController*/], __M([0/*require*/,1/*exports*/,337/*vs/nls!vs/editor/contrib/message/messageController*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,47/*vs/base/browser/ui/aria/aria*/,3/*vs/editor/common/core/range*/,11/*vs/editor/browser/editorExtensions*/,18/*vs/platform/contextkey/common/contextkey*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,382/*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._messageListeners = []; _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.getId = function () { return 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); lifecycle_1.dispose(this._messageWidget); this._messageListeners = lifecycle_1.dispose(this._messageListeners); this._messageWidget = new MessageWidget(this._editor, position, message); // close on blur, cursor, model change, dispose this._messageListeners.push(this._editor.onDidBlurEditorText(function () { return _this.closeMessage(); })); this._messageListeners.push(this._editor.onDidChangeCursorPosition(function () { return _this.closeMessage(); })); this._messageListeners.push(this._editor.onDidDispose(function () { return _this.closeMessage(); })); this._messageListeners.push(this._editor.onDidChangeModel(function () { return _this.closeMessage(); })); // close after 3s this._messageListeners.push(new async_1.TimeoutTimer(function () { return _this.closeMessage(); }, 3000)); // close on mouse move var bounds; this._messageListeners.push(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 = lifecycle_1.dispose(this._messageListeners); this._messageListeners.push(MessageWidget.fadeOut(this._messageWidget)); }; 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 */] }; }; return MessageWidget; }()); editorExtensions_1.registerEditorContribution(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[182/*vs/editor/contrib/codeAction/codeActionCommands*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,11/*vs/editor/browser/editorExtensions*/,98/*vs/editor/browser/services/bulkEditService*/,21/*vs/editor/common/editorContextKeys*/,128/*vs/editor/contrib/message/messageController*/,318/*vs/nls!vs/editor/contrib/codeAction/codeActionCommands*/,27/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,59/*vs/platform/contextview/browser/contextView*/,37/*vs/platform/keybinding/common/keybinding*/,66/*vs/platform/markers/common/markers*/,92/*vs/platform/progress/common/progress*/,174/*vs/editor/contrib/codeAction/codeActionModel*/,151/*vs/editor/contrib/codeAction/codeActionTrigger*/,243/*vs/editor/contrib/codeAction/codeActionWidget*/,470/*vs/editor/contrib/codeAction/lightBulbWidget*/,10/*vs/base/common/errors*/]), function (require, exports, lifecycle_1, strings_1, editorExtensions_1, bulkEditService_1, editorContextKeys_1, messageController_1, nls, commands_1, contextkey_1, contextView_1, keybinding_1, markers_1, progress_1, codeActionModel_1, codeActionTrigger_1, codeActionWidget_1, lightBulbWidget_1, errors_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 QuickFixController = /** @class */ (function (_super) { __extends(QuickFixController, _super); function QuickFixController(editor, markerService, contextKeyService, progressService, contextMenuService, _commandService, _keybindingService, _bulkEditService) { var _this = _super.call(this) || this; _this._commandService = _commandService; _this._keybindingService = _keybindingService; _this._bulkEditService = _bulkEditService; _this._editor = editor; _this._model = new codeActionModel_1.CodeActionModel(_this._editor, markerService, contextKeyService, progressService); _this._codeActionContextMenu = new codeActionWidget_1.CodeActionContextMenu(editor, contextMenuService, function (action) { return _this._onApplyCodeAction(action); }); _this._lightBulbWidget = _this._register(new lightBulbWidget_1.LightBulbWidget(editor)); _this._updateLightBulbTitle(); _this._register(_this._codeActionContextMenu.onDidExecuteCodeAction(function (_) { return _this._model.trigger({ type: 'auto', filter: {} }); })); _this._register(_this._lightBulbWidget.onClick(_this._handleLightBulbSelect, _this)); _this._register(_this._model.onDidChangeState(function (e) { return _this._onDidChangeCodeActionsState(e); })); _this._register(_this._keybindingService.onDidUpdateKeybindings(_this._updateLightBulbTitle, _this)); return _this; } QuickFixController.get = function (editor) { return editor.getContribution(QuickFixController.ID); }; QuickFixController.prototype.dispose = function () { _super.prototype.dispose.call(this); this._model.dispose(); }; QuickFixController.prototype._onDidChangeCodeActionsState = function (newState) { var _this = this; if (this._activeRequest) { this._activeRequest.cancel(); this._activeRequest = undefined; } if (newState.type === 1 /* Triggered */) { this._activeRequest = newState.actions; if (newState.trigger.filter && newState.trigger.filter.kind) { // Triggered for specific scope newState.actions.then(function (fixes) { if (fixes.actions.length > 0) { // Apply if we only have one action or requested autoApply if (newState.trigger.autoApply === 1 /* First */ || (newState.trigger.autoApply === 0 /* IfSingle */ && fixes.actions.length === 1)) { _this._onApplyCodeAction(fixes.actions[0]); return; } } _this._codeActionContextMenu.show(newState.actions, newState.position); }).catch(errors_1.onUnexpectedError); } else if (newState.trigger.type === 'manual') { this._codeActionContextMenu.show(newState.actions, newState.position); } else { // auto magically triggered // * update an existing list of code actions // * manage light bulb if (this._codeActionContextMenu.isVisible) { this._codeActionContextMenu.show(newState.actions, newState.position); } else { this._lightBulbWidget.tryShow(newState); } } } else { this._lightBulbWidget.hide(); } }; QuickFixController.prototype.getId = function () { return QuickFixController.ID; }; QuickFixController.prototype._handleLightBulbSelect = function (e) { this._codeActionContextMenu.show(e.state.actions, e); }; QuickFixController.prototype.triggerFromEditorSelection = function (filter, autoApply) { return this._model.trigger({ type: 'manual', filter: filter, autoApply: autoApply }); }; QuickFixController.prototype._updateLightBulbTitle = function () { var kb = this._keybindingService.lookupKeybinding(QuickFixAction.Id); var title; if (kb) { title = nls.localize(0, null, kb.getLabel()); } else { title = nls.localize(1, null); } this._lightBulbWidget.title = title; }; QuickFixController.prototype._onApplyCodeAction = function (action) { return applyCodeAction(action, this._bulkEditService, this._commandService, this._editor); }; QuickFixController.ID = 'editor.contrib.quickFixController'; QuickFixController = __decorate([ __param(1, markers_1.IMarkerService), __param(2, contextkey_1.IContextKeyService), __param(3, progress_1.IProgressService), __param(4, contextView_1.IContextMenuService), __param(5, commands_1.ICommandService), __param(6, keybinding_1.IKeybindingService), __param(7, bulkEditService_1.IBulkEditService) ], QuickFixController); return QuickFixController; }(lifecycle_1.Disposable)); exports.QuickFixController = QuickFixController; function applyCodeAction(action, bulkEditService, commandService, editor) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: 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*/, 4]; return [4 /*yield*/, commandService.executeCommand.apply(commandService, [action.command.id].concat((action.command.arguments || [])))]; case 3: _a.sent(); _a.label = 4; case 4: return [2 /*return*/]; } }); }); } exports.applyCodeAction = applyCodeAction; function showCodeActionsForEditorSelection(editor, notAvailableMessage, filter, autoApply) { if (!editor.hasModel()) { return; } var controller = QuickFixController.get(editor); if (!controller) { return; } var pos = editor.getPosition(); controller.triggerFromEditorSelection(filter, autoApply).then(function (codeActions) { if (!codeActions || !codeActions.actions.length) { messageController_1.MessageController.get(editor).showMessage(notAvailableMessage, pos); } }); } var QuickFixAction = /** @class */ (function (_super) { __extends(QuickFixAction, _super); function QuickFixAction() { return _super.call(this, { id: QuickFixAction.Id, label: nls.localize(2, 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 showCodeActionsForEditorSelection(editor, nls.localize(3, null)); }; QuickFixAction.Id = 'editor.action.quickFix'; return QuickFixAction; }(editorExtensions_1.EditorAction)); exports.QuickFixAction = QuickFixAction; 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 1 /* First */; case 'never': return 2 /* Never */; case 'ifsingle': return 0 /* IfSingle */; default: return defaultAutoApply; } }; CodeActionCommandArgs.getKindFromUser = function (arg, defaultKind) { return typeof arg.kind === 'string' ? new codeActionTrigger_1.CodeActionKind(arg.kind) : defaultKind; }; CodeActionCommandArgs.getPreferredUser = function (arg) { return typeof arg.preferred === 'boolean' ? arg.preferred : false; }; return CodeActionCommandArgs; }()); var CodeActionCommand = /** @class */ (function (_super) { __extends(CodeActionCommand, _super); function CodeActionCommand() { return _super.call(this, { id: CodeActionCommand.Id, precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider), description: { description: "Trigger a code action", args: [{ name: 'args', schema: { 'type': 'object', 'required': ['kind'], 'properties': { 'kind': { 'type': 'string' }, 'apply': { 'type': 'string', 'default': 'ifSingle', 'enum': ['first', 'ifSingle', 'never'] } } } }] } }) || this; } CodeActionCommand.prototype.runEditorCommand = function (_accessor, editor, userArg) { var args = CodeActionCommandArgs.fromUser(userArg, { kind: codeActionTrigger_1.CodeActionKind.Empty, apply: 0 /* IfSingle */, }); return showCodeActionsForEditorSelection(editor, nls.localize(4, null), { kind: args.kind, includeSourceActions: true, onlyIncludePreferredActions: args.preferred, }, args.apply); }; CodeActionCommand.Id = 'editor.action.codeAction'; return CodeActionCommand; }(editorExtensions_1.EditorCommand)); exports.CodeActionCommand = CodeActionCommand; var RefactorAction = /** @class */ (function (_super) { __extends(RefactorAction, _super); function RefactorAction() { return _super.call(this, { id: RefactorAction.Id, label: nls.localize(5, 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 */ }, menuOpts: { group: '1_modification', order: 2, when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(codeActionTrigger_1.CodeActionKind.Refactor)), }, description: { description: 'Refactor...', args: [{ name: 'args', schema: { 'type': 'object', 'properties': { 'kind': { 'type': 'string' }, 'apply': { 'type': 'string', 'default': 'never', 'enum': ['first', 'ifSingle', 'never'] } } } }] } }) || this; } RefactorAction.prototype.run = function (_accessor, editor, userArg) { var args = CodeActionCommandArgs.fromUser(userArg, { kind: codeActionTrigger_1.CodeActionKind.Refactor, apply: 2 /* Never */ }); return showCodeActionsForEditorSelection(editor, nls.localize(6, null), { kind: codeActionTrigger_1.CodeActionKind.Refactor.contains(args.kind) ? args.kind : codeActionTrigger_1.CodeActionKind.Empty, onlyIncludePreferredActions: args.preferred, }, args.apply); }; RefactorAction.Id = 'editor.action.refactor'; return RefactorAction; }(editorExtensions_1.EditorAction)); exports.RefactorAction = RefactorAction; var SourceAction = /** @class */ (function (_super) { __extends(SourceAction, _super); function SourceAction() { return _super.call(this, { id: SourceAction.Id, label: nls.localize(7, null), alias: 'Source Action', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider), menuOpts: { group: '1_modification', order: 2.1, when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(codeActionTrigger_1.CodeActionKind.Source)), }, description: { description: 'Source Action...', args: [{ name: 'args', schema: { 'type': 'object', 'properties': { 'kind': { 'type': 'string' }, 'apply': { 'type': 'string', 'default': 'never', 'enum': ['first', 'ifSingle', 'never'] } } } }] } }) || this; } SourceAction.prototype.run = function (_accessor, editor, userArg) { var args = CodeActionCommandArgs.fromUser(userArg, { kind: codeActionTrigger_1.CodeActionKind.Source, apply: 2 /* Never */ }); return showCodeActionsForEditorSelection(editor, nls.localize(8, null), { kind: codeActionTrigger_1.CodeActionKind.Source.contains(args.kind) ? args.kind : codeActionTrigger_1.CodeActionKind.Empty, includeSourceActions: true, onlyIncludePreferredActions: args.preferred, }, args.apply); }; SourceAction.Id = 'editor.action.sourceAction'; return SourceAction; }(editorExtensions_1.EditorAction)); exports.SourceAction = SourceAction; var OrganizeImportsAction = /** @class */ (function (_super) { __extends(OrganizeImportsAction, _super); function OrganizeImportsAction() { return _super.call(this, { id: OrganizeImportsAction.Id, label: nls.localize(9, null), alias: 'Organize Imports', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(codeActionTrigger_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 showCodeActionsForEditorSelection(editor, nls.localize(10, null), { kind: codeActionTrigger_1.CodeActionKind.SourceOrganizeImports, includeSourceActions: true }, 0 /* IfSingle */); }; OrganizeImportsAction.Id = 'editor.action.organizeImports'; return OrganizeImportsAction; }(editorExtensions_1.EditorAction)); exports.OrganizeImportsAction = OrganizeImportsAction; var FixAllAction = /** @class */ (function (_super) { __extends(FixAllAction, _super); function FixAllAction() { return _super.call(this, { id: FixAllAction.Id, label: nls.localize(11, null), alias: 'Fix All', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(codeActionTrigger_1.CodeActionKind.SourceFixAll)) }) || this; } FixAllAction.prototype.run = function (_accessor, editor) { return showCodeActionsForEditorSelection(editor, nls.localize(12, null), { kind: codeActionTrigger_1.CodeActionKind.SourceFixAll, includeSourceActions: true }, 0 /* IfSingle */); }; FixAllAction.Id = 'editor.action.fixAll'; 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(13, null), alias: 'Auto Fix', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(codeActionTrigger_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 showCodeActionsForEditorSelection(editor, nls.localize(14, null), { kind: codeActionTrigger_1.CodeActionKind.QuickFix, onlyIncludePreferredActions: true }, 0 /* 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[541/*vs/editor/contrib/codeAction/codeActionContributions*/], __M([0/*require*/,1/*exports*/,11/*vs/editor/browser/editorExtensions*/,182/*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); 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[542/*vs/editor/contrib/multicursor/multicursor*/], __M([0/*require*/,1/*exports*/,338/*vs/nls!vs/editor/contrib/multicursor/multicursor*/,15/*vs/base/common/async*/,36/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/browser/editorExtensions*/,187/*vs/editor/common/controller/cursorMoveCommands*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,21/*vs/editor/common/editorContextKeys*/,45/*vs/editor/common/model*/,29/*vs/editor/common/model/textModel*/,16/*vs/editor/common/modes*/,222/*vs/editor/contrib/find/findController*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/]), 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) { "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: null, 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 */ }, menubarOpts: { menuId: 22 /* 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(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: null, 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 */ }, menubarOpts: { menuId: 22 /* 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(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: null, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 512 /* Alt */ | 39 /* KEY_I */, weight: 100 /* EditorContrib */ }, menubarOpts: { menuId: 22 /* 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: null }) || 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: null }) || 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.getConfiguration().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.getConfiguration().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.getConfiguration().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._editor = editor; _this._ignoreSelectionChange = false; _this._session = null; _this._sessionDispose = []; return _this; } MultiCursorSelectionController.get = function (editor) { return editor.getContribution(MultiCursorSelectionController.ID); }; MultiCursorSelectionController.prototype.dispose = function () { this._endSession(); _super.prototype.dispose.call(this); }; MultiCursorSelectionController.prototype.getId = function () { return MultiCursorSelectionController.ID; }; 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 = [ this._editor.onDidChangeCursorSelection(function (e) { if (_this._ignoreSelectionChange) { return; } _this._endSession(); }), this._editor.onDidBlurEditorText(function () { _this._endSession(); }), findController.getState().onFindReplaceStateChange(function (e) { if (e.matchCase || e.wholeWord) { _this._endSession(); } }) ]; } }; MultiCursorSelectionController.prototype._endSession = function () { this._sessionDispose = lifecycle_1.dispose(this._sessionDispose); 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.getConfiguration().wordSeparators : null, false, 1073741824 /* MAX_SAFE_SMALL_INTEGER */); } else { this._beginSessionIfNeeded(findController); if (!this._session) { return; } matches = this._session.selectAll(); } 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: null, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 2048 /* CtrlCmd */ | 34 /* KEY_D */, weight: 100 /* EditorContrib */ }, menubarOpts: { menuId: 22 /* 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: null, menubarOpts: { menuId: 22 /* 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: null, 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: null }) || 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: null, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 42 /* KEY_L */, weight: 100 /* EditorContrib */ }, menubarOpts: { menuId: 22 /* 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: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 60 /* F2 */, weight: 100 /* EditorContrib */ }, menuOpts: { 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.getConfiguration().contribInfo.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.getConfiguration().contribInfo.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.getId = function () { return SelectionHighlighter.ID; }; 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.getConfiguration().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); editorExtensions_1.registerEditorContribution(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[543/*vs/editor/contrib/parameterHints/parameterHintsWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,62/*vs/base/browser/event*/,47/*vs/base/browser/ui/aria/aria*/,51/*vs/base/browser/ui/scrollbar/scrollableElement*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,67/*vs/editor/common/services/modeService*/,99/*vs/editor/contrib/markdown/markdownRenderer*/,111/*vs/editor/contrib/parameterHints/provideSignatureHelp*/,340/*vs/nls!vs/editor/contrib/parameterHints/parameterHintsWidget*/,18/*vs/platform/contextkey/common/contextkey*/,56/*vs/platform/opener/common/opener*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,486/*vs/editor/contrib/parameterHints/parameterHintsModel*/,381/*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) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var $ = dom.$; var ParameterHintsWidget = /** @class */ (function () { function ParameterHintsWidget(editor, contextKeyService, openerService, modeService) { var _this = this; this.editor = editor; // Editor.IContentWidget.allowEditorOverflow this.allowEditorOverflow = true; this.markdownRenderer = new markdownRenderer_1.MarkdownRenderer(editor, modeService, openerService); this.model = new parameterHintsModel_1.ParameterHintsModel(editor); this.keyVisible = provideSignatureHelp_1.Context.Visible.bindTo(contextKeyService); this.keyMultipleSignatures = provideSignatureHelp_1.Context.MultipleSignatures.bindTo(contextKeyService); this.visible = false; this.disposables = []; this.disposables.push(this.model.onChangedHints(function (newParameterHints) { if (newParameterHints) { _this.show(); _this.render(newParameterHints); } else { _this.hide(); } })); } ParameterHintsWidget.prototype.createParamaterHintDOMNodes = function () { var _this = this; this.element = $('.editor-widget.parameter-hints-widget'); var wrapper = dom.append(this.element, $('.wrapper')); wrapper.tabIndex = -1; var buttons = dom.append(wrapper, $('.buttons')); var previous = dom.append(buttons, $('.button.previous')); var next = dom.append(buttons, $('.button.next')); var onPreviousClick = event_1.stop(event_1.domEvent(previous, 'click')); onPreviousClick(this.previous, this, this.disposables); var onNextClick = event_1.stop(event_1.domEvent(next, 'click')); onNextClick(this.next, this, this.disposables); this.overloads = dom.append(wrapper, $('.overloads')); var body = $('.body'); this.scrollbar = new scrollableElement_1.DomScrollableElement(body, {}); this.disposables.push(this.scrollbar); wrapper.appendChild(this.scrollbar.getDomNode()); this.signature = dom.append(body, $('.signature')); this.docs = dom.append(body, $('.docs')); this.editor.addContentWidget(this); this.hide(); this.element.style.userSelect = 'text'; this.disposables.push(this.editor.onDidChangeCursorSelection(function (e) { if (_this.visible) { _this.editor.layoutContentWidget(_this); } })); var updateFont = function () { var fontInfo = _this.editor.getConfiguration().fontInfo; _this.element.style.fontSize = fontInfo.fontSize + "px"; }; updateFont(); event_2.Event.chain(this.editor.onDidChangeConfiguration.bind(this.editor)) .filter(function (e) { return e.fontInfo; }) .on(updateFont, null, this.disposables); this.disposables.push(this.editor.onDidLayoutChange(function (e) { return _this.updateMaxHeight(); })); this.updateMaxHeight(); }; ParameterHintsWidget.prototype.show = function () { var _this = this; if (!this.model || this.visible) { return; } if (!this.element) { this.createParamaterHintDOMNodes(); } this.keyVisible.set(true); this.visible = true; setTimeout(function () { return dom.addClass(_this.element, 'visible'); }, 100); this.editor.layoutContentWidget(this); }; ParameterHintsWidget.prototype.hide = function () { if (!this.model || !this.visible) { return; } if (!this.element) { this.createParamaterHintDOMNodes(); } this.keyVisible.reset(); this.visible = false; this.announcedLabel = null; dom.removeClass(this.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) { var multiple = hints.signatures.length > 1; dom.toggleClass(this.element, 'multiple', multiple); this.keyMultipleSignatures.set(multiple); this.signature.innerHTML = ''; this.docs.innerHTML = ''; var signature = hints.signatures[hints.activeSignature]; if (!signature) { return; } var code = dom.append(this.signature, $('.code')); var hasParameters = signature.parameters.length > 0; var fontInfo = this.editor.getConfiguration().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); } lifecycle_1.dispose(this.renderDisposeables); this.renderDisposeables = []; 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.push(renderedContents); documentation.appendChild(renderedContents.element); } dom.append(this.docs, $('p', {}, documentation)); } dom.toggleClass(this.signature, 'has-docs', !!signature.documentation); if (signature.documentation === undefined) { /** no op */ } else if (typeof signature.documentation === 'string') { dom.append(this.docs, $('p', {}, signature.documentation)); } else { var renderedContents = this.markdownRenderer.render(signature.documentation); dom.addClass(renderedContents.element, 'markdown-docs'); this.renderDisposeables.push(renderedContents); dom.append(this.docs, renderedContents.element); } var currentOverload = String(hints.activeSignature + 1); if (hints.signatures.length < 10) { currentOverload += "/" + hints.signatures.length; } this.overloads.textContent = currentOverload; 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.scrollbar.scanDomNode(); }; 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 () { if (this.model) { this.editor.focus(); this.model.next(); } }; ParameterHintsWidget.prototype.previous = function () { if (this.model) { this.editor.focus(); this.model.previous(); } }; ParameterHintsWidget.prototype.cancel = function () { if (this.model) { this.model.cancel(); } }; ParameterHintsWidget.prototype.getDomNode = function () { return this.element; }; ParameterHintsWidget.prototype.getId = function () { return ParameterHintsWidget.ID; }; ParameterHintsWidget.prototype.trigger = function (context) { if (this.model) { this.model.trigger(context, 0); } }; ParameterHintsWidget.prototype.updateMaxHeight = function () { var height = Math.max(this.editor.getLayoutInfo().height / 4, 250); this.element.style.maxHeight = height + "px"; }; ParameterHintsWidget.prototype.dispose = function () { this.disposables = lifecycle_1.dispose(this.disposables); this.renderDisposeables = lifecycle_1.dispose(this.renderDisposeables); if (this.model) { this.model.dispose(); this.model = null; } }; 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; }()); 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 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[544/*vs/editor/contrib/parameterHints/parameterHints*/], __M([0/*require*/,1/*exports*/,339/*vs/nls!vs/editor/contrib/parameterHints/parameterHints*/,2/*vs/base/common/lifecycle*/,13/*vs/platform/instantiation/common/instantiation*/,21/*vs/editor/common/editorContextKeys*/,18/*vs/platform/contextkey/common/contextkey*/,11/*vs/editor/browser/editorExtensions*/,543/*vs/editor/contrib/parameterHints/parameterHintsWidget*/,111/*vs/editor/contrib/parameterHints/provideSignatureHelp*/,16/*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 () { function ParameterHintsController(editor, instantiationService) { this.editor = editor; this.widget = instantiationService.createInstance(parameterHintsWidget_1.ParameterHintsWidget, this.editor); } ParameterHintsController.get = function (editor) { return editor.getContribution(ParameterHintsController.ID); }; ParameterHintsController.prototype.getId = function () { return 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.prototype.dispose = function () { lifecycle_1.dispose(this.widget); }; ParameterHintsController.ID = 'editor.controller.parameterHints'; ParameterHintsController = __decorate([ __param(1, instantiation_1.IInstantiationService) ], ParameterHintsController); return ParameterHintsController; }()); 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); 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[105/*vs/editor/contrib/referenceSearch/peekViewWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,79/*vs/base/browser/ui/actionbar/actionbar*/,49/*vs/base/common/actions*/,28/*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*/,118/*vs/editor/browser/widget/embeddedCodeEditorWidget*/,403/*vs/editor/contrib/zoneWidget/zoneWidget*/,341/*vs/nls!vs/editor/contrib/referenceSearch/peekViewWidget*/,18/*vs/platform/contextkey/common/contextkey*/,13/*vs/platform/instantiation/common/instantiation*/,109/*vs/platform/instantiation/common/extensions*/,380/*vs/css!vs/editor/contrib/referenceSearch/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) { "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 = {})); 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(); objects.mixin(_this.options, defaultOptions, false); return _this; } PeekViewWidget.prototype.dispose = function () { _super.prototype.dispose.call(this); this._onDidClose.fire(this); }; Object.defineProperty(PeekViewWidget.prototype, "onDidClose", { get: function () { return this._onDidClose.event; }, enumerable: true, configurable: true }); 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._headingIcon = dom.$('span'); this._primaryHeading = dom.$('span.filename'); this._secondaryHeading = dom.$('span.dirname'); this._metaHeading = dom.$('span.meta'); dom.append(titleElement, this._headingIcon, 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.push(this._actionbarWidget); this._actionbarWidget.push(new actions_1.Action('peekview.close', nls.localize(0, null), 'close-peekview-action', true, function () { _this.dispose(); return Promise.resolve(); }), { label: false, icon: true }); }; PeekViewWidget.prototype._getActionBarOptions = function () { return {}; }; PeekViewWidget.prototype._onTitleClick = function (event) { // implement me }; PeekViewWidget.prototype.setTitleIcon = function (iconClassName) { this._headingIcon.className = iconClassName ? "icon " + iconClassName : ''; }; PeekViewWidget.prototype.setTitle = function (primaryHeading, 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 (value) { this._metaHeading.innerHTML = strings.escape(value); } else { dom.clearNode(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.getConfiguration().lineHeight * 1.2); var bodyHeight = heightInPixel - (headHeight + 2 /* the border-top/bottom width*/); this._doLayoutHead(headHeight, widthInPixel); this._doLayoutBody(bodyHeight, widthInPixel); }; PeekViewWidget.prototype._doLayoutHead = function (heightInPixel, widthInPixel) { this._headElement.style.height = heightInPixel + "px"; this._headElement.style.lineHeight = this._headElement.style.height; }; PeekViewWidget.prototype._doLayoutBody = function (heightInPixel, widthInPixel) { this._bodyElement.style.height = heightInPixel + "px"; }; return PeekViewWidget; }(zoneWidget_1.ZoneWidget)); exports.PeekViewWidget = PeekViewWidget; }); /*--------------------------------------------------------------------------------------------- * 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/contrib/referenceSearch/referencesTree*/], __M([0/*require*/,1/*exports*/,90/*vs/editor/contrib/referenceSearch/referencesModel*/,80/*vs/editor/common/services/resolverService*/,155/*vs/base/browser/ui/iconLabel/iconLabel*/,482/*vs/base/browser/ui/countBadge/countBadge*/,125/*vs/platform/label/common/label*/,14/*vs/platform/theme/common/themeService*/,85/*vs/platform/theme/common/styler*/,7/*vs/base/browser/dom*/,346/*vs/nls!vs/editor/contrib/referenceSearch/referencesTree*/,199/*vs/base/common/labels*/,54/*vs/base/common/resources*/,5/*vs/base/common/strings*/,2/*vs/base/common/lifecycle*/,13/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,65/*vs/base/common/filters*/]), function (require, exports, referencesModel_1, resolverService_1, iconLabel_1, countBadge_1, label_1, themeService_1, styler_1, dom, nls_1, labels_1, resources_1, strings_1, lifecycle_1, instantiation_1, keybinding_1, filters_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) { // todo@joao `OneReference` elements are lazy and their "real" label // isn't known yet return resources_1.basename(element.uri); }; StringRepresentationProvider.prototype.mightProducePrintableCharacter = function (event) { return this._keybindingService.mightProducePrintableCharacter(event); }; 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.id; }; 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) { var parent = document.createElement('div'); this.before = document.createElement('span'); this.inside = document.createElement('span'); this.after = document.createElement('span'); dom.addClass(this.inside, 'referenceMatch'); dom.addClass(parent, 'reference'); parent.appendChild(this.before); parent.appendChild(this.inside); parent.appendChild(this.after); container.appendChild(parent); } OneReferenceTemplate.prototype.set = function (element) { var filePreview = element.parent.preview; var preview = filePreview && filePreview.preview(element.range); if (preview) { var before_1 = preview.before, inside = preview.inside, after_1 = preview.after; this.before.innerHTML = strings_1.escape(before_1); this.inside.innerHTML = strings_1.escape(inside); this.after.innerHTML = strings_1.escape(after_1); } }; 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 (element, index, templateData) { templateData.set(element.element); }; OneReferenceRenderer.prototype.disposeTemplate = function () { // }; OneReferenceRenderer.id = 'OneReferenceRenderer'; return OneReferenceRenderer; }()); exports.OneReferenceRenderer = OneReferenceRenderer; //#endregion var AriaProvider = /** @class */ (function () { function AriaProvider() { } AriaProvider.prototype.getAriaLabel = function (element) { if (element instanceof referencesModel_1.FileReferences) { return element.getAriaMessage(); } else if (element instanceof referencesModel_1.OneReference) { return element.getAriaMessage(); } else { return null; } }; 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[547/*vs/editor/contrib/rename/rename*/], __M([0/*require*/,1/*exports*/,348/*vs/nls!vs/editor/contrib/rename/rename*/,10/*vs/base/common/errors*/,18/*vs/platform/contextkey/common/contextkey*/,92/*vs/platform/progress/common/progress*/,11/*vs/editor/browser/editorExtensions*/,21/*vs/editor/common/editorContextKeys*/,497/*vs/editor/contrib/rename/renameInputField*/,14/*vs/platform/theme/common/themeService*/,16/*vs/editor/common/modes*/,12/*vs/editor/common/core/position*/,47/*vs/base/browser/ui/aria/aria*/,3/*vs/editor/common/core/range*/,128/*vs/editor/contrib/message/messageController*/,64/*vs/editor/browser/core/editorState*/,35/*vs/platform/notification/common/notification*/,98/*vs/editor/browser/services/bulkEditService*/,25/*vs/base/common/uri*/,32/*vs/editor/browser/services/codeEditorService*/,24/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,15/*vs/base/common/async*/]), function (require, exports, nls, errors_1, contextkey_1, progress_1, editorExtensions_1, editorContextKeys_1, renameInputField_1, themeService_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) { "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, word; return __generator(this, function (_a) { switch (_a.label) { case 0: firstProvider = this._providers[0]; if (!firstProvider) { return [2 /*return*/, undefined]; } if (!firstProvider.resolveRenameLocation) return [3 /*break*/, 2]; return [4 /*yield*/, firstProvider.resolveRenameLocation(this.model, this.position, token)]; case 1: res = _a.sent(); _a.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 (_super) { __extends(RenameController, _super); function RenameController(editor, _notificationService, _bulkEditService, _progressService, _contextKeyService, _themeService) { var _this = _super.call(this) || this; _this.editor = editor; _this._notificationService = _notificationService; _this._bulkEditService = _bulkEditService; _this._progressService = _progressService; _this._contextKeyService = _contextKeyService; _this._themeService = _themeService; _this._renameOperationIdPool = 1; _this._register(_this.editor.onDidChangeModel(function () { return _this.onModelChanged(); })); _this._register(_this.editor.onDidChangeModelLanguage(function () { return _this.onModelChanged(); })); _this._register(_this.editor.onDidChangeCursorSelection(function () { return _this.onModelChanged(); })); return _this; } RenameController.get = function (editor) { return editor.getContribution(RenameController.ID); }; Object.defineProperty(RenameController.prototype, "renameInputField", { get: function () { if (!this._renameInputField) { this._renameInputField = this._register(new renameInputField_1.RenameInputField(this.editor, this._themeService, this._contextKeyService)); } return this._renameInputField; }, enumerable: true, configurable: true }); RenameController.prototype.getId = function () { return RenameController.ID; }; RenameController.prototype.run = function () { return __awaiter(this, void 0, void 0, function () { var id; var _this = this; return __generator(this, function (_a) { if (this._activeRename) { this._activeRename.operation.cancel(); } id = this._renameOperationIdPool++; this._activeRename = { id: id, operation: async_1.createCancelablePromise(function (token) { return _this.doRename(token, id); }) }; return [2 /*return*/, this._activeRename.operation]; }); }); }; RenameController.prototype.doRename = function (token, id) { return __awaiter(this, void 0, void 0, function () { var position, skeleton, loc, resolveLocationOperation, e_1, selection, selectionStart, selectionEnd; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: 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]; } _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); resolveLocationOperation = skeleton.resolveRenameLocation(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._activeRename || this._activeRename.id !== id) { 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; } return [2 /*return*/, this.renameInputField.getInput(loc.range, loc.text, selectionStart, selectionEnd).then(function (newNameOrFocusFlag) { if (typeof newNameOrFocusFlag === 'boolean') { if (newNameOrFocusFlag) { _this.editor.focus(); } return undefined; } _this.editor.focus(); var state = new editorState_1.EditorState(_this.editor, 4 /* Position */ | 1 /* Value */ | 2 /* Selection */ | 8 /* Scroll */); var renameOperation = Promise.resolve(skeleton.provideRenameEdits(newNameOrFocusFlag, 0, [], token).then(function (result) { if (!_this.editor.hasModel()) { return undefined; } if (result.rejectReason) { if (state.validate(_this.editor)) { messageController_1.MessageController.get(_this.editor).showMessage(result.rejectReason, _this.editor.getPosition()); } else { _this._notificationService.info(result.rejectReason); } return undefined; } return _this._bulkEditService.apply(result, { editor: _this.editor }).then(function (result) { // alert if (result.ariaSummary) { aria_1.alert(nls.localize(2, null, loc.text, newNameOrFocusFlag, result.ariaSummary)); } }); }, function (err) { _this._notificationService.error(nls.localize(3, null)); return Promise.reject(err); })); _this._progressService.showWhile(renameOperation, 250); return renameOperation; })]; } }); }); }; RenameController.prototype.acceptRenameInput = function () { if (this._renameInputField) { this._renameInputField.acceptInput(); } }; RenameController.prototype.cancelRenameInput = function () { if (this._renameInputField) { this._renameInputField.cancelInput(true); } }; RenameController.prototype.onModelChanged = function () { if (this._activeRename) { this._activeRename.operation.cancel(); this._activeRename = undefined; } }; RenameController.ID = 'editor.contrib.renameController'; RenameController = __decorate([ __param(1, notification_1.INotificationService), __param(2, bulkEditService_1.IBulkEditService), __param(3, progress_1.IProgressService), __param(4, contextkey_1.IContextKeyService), __param(5, themeService_1.IThemeService) ], RenameController); return RenameController; }(lifecycle_1.Disposable)); // ---- action implementation var RenameAction = /** @class */ (function (_super) { __extends(RenameAction, _super); function RenameAction() { return _super.call(this, { id: 'editor.action.rename', label: nls.localize(4, 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 */ }, menuOpts: { 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); 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(); }, kbOpts: { weight: 100 /* EditorContrib */ + 99, kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: 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); }); }); /*--------------------------------------------------------------------------------------------- * 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/contrib/suggest/suggestWidget*/], __M([0/*require*/,1/*exports*/,353/*vs/nls!vs/editor/contrib/suggest/suggestWidget*/,65/*vs/base/common/filters*/,5/*vs/base/common/strings*/,4/*vs/base/common/event*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,7/*vs/base/browser/dom*/,135/*vs/base/browser/ui/list/listWidget*/,51/*vs/base/browser/ui/scrollbar/scrollableElement*/,37/*vs/platform/keybinding/common/keybinding*/,18/*vs/platform/contextkey/common/contextkey*/,100/*vs/editor/contrib/suggest/suggest*/,47/*vs/base/browser/ui/aria/aria*/,97/*vs/platform/telemetry/common/telemetry*/,85/*vs/platform/theme/common/styler*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,68/*vs/platform/storage/common/storage*/,99/*vs/editor/contrib/markdown/markdownRenderer*/,67/*vs/editor/common/services/modeService*/,56/*vs/platform/opener/common/opener*/,15/*vs/base/common/async*/,24/*vs/base/common/cancellation*/,16/*vs/editor/common/modes*/,155/*vs/base/browser/ui/iconLabel/iconLabel*/,443/*vs/editor/common/services/getIconClasses*/,42/*vs/editor/common/services/modelService*/,25/*vs/base/common/uri*/,13/*vs/platform/instantiation/common/instantiation*/,221/*vs/platform/files/common/files*/,374/*vs/css!vs/editor/contrib/suggest/media/suggest*/]), 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, aria_1, telemetry_1, styler_1, themeService_1, colorRegistry_1, storage_1, markdownRenderer_1, modeService_1, opener_1, async_1, cancellation_1, modes_1, iconLabel_1, getIconClasses_1, modelService_1, uri_1, instantiation_1, files_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) { if (item.completion.label.match(colorRegExp)) { out[0] = item.completion.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); } var Renderer = /** @class */ (function () { function Renderer(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(Renderer.prototype, "templateId", { get: function () { return 'suggestion'; }, enumerable: true, configurable: true }); Renderer.prototype.renderTemplate = function (container) { var _this = this; var data = Object.create(null); data.disposables = []; 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.iconLabel = new iconLabel_1.IconLabel(main, { supportHighlights: true }); data.disposables.push(data.iconLabel); data.typeLabel = dom_1.append(main, dom_1.$('span.type-label')); data.readMore = dom_1.append(main, dom_1.$('span.readMore')); data.readMore.title = nls.localize(5, null, this.triggerKeybindingLabel); var configureFont = function () { var configuration = _this.editor.getConfiguration(); var fontFamily = configuration.fontInfo.fontFamily; var fontSize = configuration.contribInfo.suggestFontSize || configuration.fontInfo.fontSize; var lineHeight = configuration.contribInfo.suggestLineHeight || configuration.fontInfo.lineHeight; var fontWeight = configuration.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.lineHeight = lineHeightPx; data.icon.style.height = lineHeightPx; data.icon.style.width = lineHeightPx; data.readMore.style.height = lineHeightPx; data.readMore.style.width = lineHeightPx; }; configureFont(); event_1.Event.chain(this.editor.onDidChangeConfiguration.bind(this.editor)) .filter(function (e) { return e.fontInfo || e.contribInfo; }) .on(configureFont, null, data.disposables); return data; }; Renderer.prototype.renderElement = function (element, _index, templateData) { var _this = this; var data = templateData; var suggestion = element.completion; 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.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'; labelOptions.extraClasses = [].concat(getIconClasses_1.getIconClasses(this._modelService, this._modeService, uri_1.URI.from({ scheme: 'fake', path: suggestion.label }), files_1.FileKind.FILE), getIconClasses_1.getIconClasses(this._modelService, this._modeService, uri_1.URI.from({ scheme: 'fake', path: suggestion.detail }), files_1.FileKind.FILE)); } else if (suggestion.kind === 23 /* Folder */ && this._themeService.getIconTheme().hasFolderIcons) { // special logic for 'folder' completion items data.icon.className = 'icon hide'; labelOptions.extraClasses = [].concat(getIconClasses_1.getIconClasses(this._modelService, this._modeService, uri_1.URI.from({ scheme: 'fake', path: suggestion.label }), 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'; labelOptions.extraClasses = [ "suggest-icon " + modes_1.completionKindToCssClass(suggestion.kind) ]; } data.iconLabel.setLabel(suggestion.label, undefined, labelOptions); data.typeLabel.textContent = (suggestion.detail || '').replace(/\n.*$/m, ''); if (canExpandCompletionItem(element)) { 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.hide(data.readMore); data.readMore.onmousedown = null; data.readMore.onclick = null; } }; Renderer.prototype.disposeTemplate = function (templateData) { templateData.disposables = lifecycle_1.dispose(templateData.disposables); }; Renderer = __decorate([ __param(3, modelService_1.IModelService), __param(4, modeService_1.IModeService), __param(5, themeService_1.IThemeService) ], Renderer); return Renderer; }()); var SuggestionDetails = /** @class */ (function () { function SuggestionDetails(container, widget, editor, markdownRenderer, triggerKeybindingLabel) { var _this = this; this.widget = widget; this.editor = editor; this.markdownRenderer = markdownRenderer; this.triggerKeybindingLabel = triggerKeybindingLabel; this.borderWidth = 1; this.disposables = []; this.el = dom_1.append(container, dom_1.$('.details')); this.disposables.push(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.push(this.scrollbar); this.header = dom_1.append(this.body, dom_1.$('.header')); this.close = dom_1.append(this.header, dom_1.$('span.close')); this.close.title = nls.localize(6, null, this.triggerKeybindingLabel); this.type = dom_1.append(this.header, dom_1.$('p.type')); this.docs = dom_1.append(this.body, dom_1.$('p.docs')); this.ariaLabel = null; this.configureFont(); event_1.Event.chain(this.editor.onDidChangeConfiguration.bind(this.editor)) .filter(function (e) { return e.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.render = function (item) { var _this = this; this.renderDisposeable = lifecycle_1.dispose(this.renderDisposeable); if (!item || !canExpandCompletionItem(item)) { this.type.textContent = ''; this.docs.textContent = ''; dom_1.addClass(this.el, 'no-docs'); this.ariaLabel = null; return; } dom_1.removeClass(this.el, 'no-docs'); if (typeof item.completion.documentation === 'string') { dom_1.removeClass(this.docs, 'markdown-docs'); this.docs.textContent = item.completion.documentation; } else { dom_1.addClass(this.docs, 'markdown-docs'); this.docs.innerHTML = ''; var renderedContents = this.markdownRenderer.render(item.completion.documentation); this.renderDisposeable = renderedContents; this.docs.appendChild(renderedContents.element); } if (item.completion.detail) { this.type.innerText = item.completion.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.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(); this.ariaLabel = strings.format('{0}{1}', item.completion.detail || '', item.completion.documentation ? (typeof item.completion.documentation === 'string' ? item.completion.documentation : item.completion.documentation.value) : ''); }; SuggestionDetails.prototype.getAriaLabel = function () { return this.ariaLabel; }; 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 configuration = this.editor.getConfiguration(); var fontFamily = configuration.fontInfo.fontFamily; var fontSize = configuration.contribInfo.suggestFontSize || configuration.fontInfo.fontSize; var lineHeight = configuration.contribInfo.suggestLineHeight || configuration.fontInfo.lineHeight; var fontWeight = configuration.fontInfo.fontWeight; var fontSizePx = fontSize + "px"; var lineHeightPx = lineHeight + "px"; this.el.style.fontSize = fontSizePx; this.el.style.fontWeight = fontWeight; this.type.style.fontFamily = fontFamily; this.close.style.height = lineHeightPx; this.close.style.width = lineHeightPx; }; SuggestionDetails.prototype.dispose = function () { this.disposables = lifecycle_1.dispose(this.disposables); this.renderDisposeable = lifecycle_1.dispose(this.renderDisposeable); }; return SuggestionDetails; }()); var SuggestWidget = /** @class */ (function () { function SuggestWidget(editor, telemetryService, contextKeyService, themeService, storageService, keybindingService, modeService, openerService, instantiationService) { var _this = this; this.editor = editor; this.telemetryService = telemetryService; // Editor.IContentWidget.allowEditorOverflow this.allowEditorOverflow = true; this.ignoreFocusEvents = false; this.editorBlurTimeout = new async_1.TimeoutTimer(); this.showTimeout = new async_1.TimeoutTimer(); 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; var kb = keybindingService.lookupKeybinding('editor.action.triggerSuggest'); var triggerKeybindingLabel = !kb ? '' : " (" + kb.getLabel() + ")"; var markdownRenderer = new markdownRenderer_1.MarkdownRenderer(editor, modeService, openerService); this.isAuto = false; this.focusedItem = null; this.storageService = storageService; this.element = dom_1.$('.editor-widget.suggest-widget'); this.messageElement = dom_1.append(this.element, dom_1.$('.message')); this.listElement = dom_1.append(this.element, dom_1.$('.tree')); this.details = new SuggestionDetails(this.element, this, this.editor, markdownRenderer, triggerKeybindingLabel); var applyIconStyle = function () { return dom_1.toggleClass(_this.element, 'no-icons', !_this.editor.getConfiguration().contribInfo.suggest.showIcons); }; applyIconStyle(); var renderer = instantiationService.createInstance(Renderer, this, this.editor, triggerKeybindingLabel); this.list = new listWidget_1.List(this.listElement, this, [renderer], { useShadows: false, openController: { shouldOpen: function () { return false; } }, mouseSupport: false }); this.toDispose = [ styler_1.attachListStyler(this.list, themeService, { listInactiveFocusBackground: exports.editorSuggestWidgetSelectedBackground, listInactiveFocusOutline: colorRegistry_1.activeContrastBorder }), themeService.onThemeChange(function (t) { return _this.onThemeChange(t); }), editor.onDidLayoutChange(function () { return _this.onEditorLayoutChange(); }), this.list.onMouseDown(function (e) { return _this.onListMouseDown(e); }), this.list.onSelectionChange(function (e) { return _this.onListSelection(e); }), this.list.onFocusChange(function (e) { return _this.onListFocus(e); }), this.editor.onDidChangeCursorSelection(function () { return _this.onCursorSelectionChanged(); }), this.editor.onDidChangeConfiguration(function (e) { return e.contribInfo && 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()); } 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.onListMouseDown = 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 _this = this; var completionModel = this.completionModel; if (!completionModel) { return; } item.resolve(cancellation_1.CancellationToken.None).then(function () { _this.onDidSelectEmitter.fire({ item: item, index: index, model: completionModel }); _this.editor.focus(); }); }; SuggestWidget.prototype._getSuggestionAriaAlertLabel = function (item) { if (this.expandDocsSettingFromStorage()) { return nls.localize(9, null, item.completion.label, this.details.getAriaLabel()); } else { return item.completion.label; } }; SuggestWidget.prototype._ariaAlert = function (newAriaAlertLabel) { if (this._lastAriaAlertLabel === newAriaAlertLabel) { return; } this._lastAriaAlertLabel = newAriaAlertLabel; if (this._lastAriaAlertLabel) { aria_1.alert(this._lastAriaAlertLabel, true); } }; SuggestWidget.prototype.onThemeChange = function (theme) { var backgroundColor = theme.getColor(exports.editorSuggestWidgetBackground); if (backgroundColor) { this.listElement.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.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; if (this.ignoreFocusEvents) { return; } if (!e.elements.length) { if (this.currentSuggestionDetails) { this.currentSuggestionDetails.cancel(); this.currentSuggestionDetails = null; this.focusedItem = null; } this._ariaAlert(null); return; } if (!this.completionModel) { return; } var item = e.elements[0]; var index = e.indexes[0]; this.firstFocusInCurrentList = !this.focusedItem; if (item !== this.focusedItem) { if (this.currentSuggestionDetails) { this.currentSuggestionDetails.cancel(); this.currentSuggestionDetails = null; } this.focusedItem = item; this.list.reveal(index); this.currentSuggestionDetails = async_1.createCancelablePromise(function (token) { return item.resolve(token); }); this.currentSuggestionDetails.then(function () { if (_this.list.length < 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(); } else { dom_1.removeClass(_this.element, 'docs-side'); } _this._ariaAlert(_this._getSuggestionAriaAlertLabel(item)); }).catch(errors_1.onUnexpectedError).then(function () { if (_this.focusedItem === item) { _this.currentSuggestionDetails = null; } }); } // 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.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); 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); 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.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.show(); this._ariaAlert(this.details.getAriaLabel()); break; } }; SuggestWidget.prototype.showTriggered = function (auto, delay) { var _this = this; if (this.state !== 0 /* Hidden */) { return; } this.isAuto = !!auto; if (!this.isAuto) { this.loadingTimeout = setTimeout(function () { _this.loadingTimeout = null; _this.setState(1 /* Loading */); }, delay); } }; SuggestWidget.prototype.showSuggestions = function (completionModel, selectionIndex, isFrozen, isAuto) { this.preferDocPositionTop = false; this.docsPositionPreviousWidgetY = null; if (this.loadingTimeout) { clearTimeout(this.loadingTimeout); this.loadingTimeout = null; } 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}", "${EditorTelemetryData}" ] } */ this.telemetryService.publicLog('suggestWidget', __assign({}, stats, this.editor.getTelemetryData())); } 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; } } /* __GDPR__ "suggestWidget:toggleDetailsFocus" : { "${include}": [ "${EditorTelemetryData}" ] } */ this.telemetryService.publicLog('suggestWidget:toggleDetailsFocus', this.editor.getTelemetryData()); }; 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); /* __GDPR__ "suggestWidget:collapseDetails" : { "${include}": [ "${EditorTelemetryData}" ] } */ this.telemetryService.publicLog('suggestWidget:collapseDetails', this.editor.getTelemetryData()); } else { if (this.state !== 3 /* Open */ && this.state !== 5 /* Details */ && this.state !== 4 /* Frozen */) { return; } this.updateExpandDocsSetting(true); this.showDetails(); this._ariaAlert(this.details.getAriaLabel()); /* __GDPR__ "suggestWidget:expandDetails" : { "${include}": [ "${EditorTelemetryData}" ] } */ this.telemetryService.publicLog('suggestWidget:expandDetails', this.editor.getTelemetryData()); } }; SuggestWidget.prototype.showDetails = function () { this.expandSideOrBelow(); dom_1.show(this.details.element); this.details.render(this.list.getFocusedElements()[0]); this.details.element.style.maxHeight = this.maxWidgetHeight + 'px'; // 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.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 () { clearTimeout(this.loadingTimeout); 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.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.getConfiguration().contribInfo.suggest.maxVisibleSuggestions; height = Math.min(suggestionCount, maxVisibleSuggestions) * this.unfocusedHeight; } this.element.style.lineHeight = this.unfocusedHeight + "px"; this.listElement.style.height = 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.getConfiguration().fontInfo.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 */ 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.getConfiguration().contribInfo.suggest.maxVisibleSuggestions; }, enumerable: true, configurable: true }); Object.defineProperty(SuggestWidget.prototype, "unfocusedHeight", { get: function () { var configuration = this.editor.getConfiguration(); return configuration.contribInfo.suggestLineHeight || configuration.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.dispose = function () { this.state = null; this.currentSuggestionDetails = null; this.focusedItem = null; this.element = null; // StrictNullOverride: nulling out ok in dispose this.messageElement = null; // StrictNullOverride: nulling out ok in dispose this.listElement = null; // StrictNullOverride: nulling out ok in dispose this.details.dispose(); this.details = null; // StrictNullOverride: nulling out ok in dispose this.list.dispose(); this.list = null; // StrictNullOverride: nulling out ok in dispose this.toDispose = lifecycle_1.dispose(this.toDispose); if (this.loadingTimeout) { clearTimeout(this.loadingTimeout); this.loadingTimeout = null; } this.editorBlurTimeout.dispose(); this.showTimeout.dispose(); }; SuggestWidget.ID = 'editor.widget.suggestWidget'; SuggestWidget.LOADING_MESSAGE = nls.localize(7, null); SuggestWidget.NO_SUGGESTIONS_MESSAGE = nls.localize(8, null); SuggestWidget = __decorate([ __param(1, telemetry_1.ITelemetryService), __param(2, contextkey_1.IContextKeyService), __param(3, themeService_1.IThemeService), __param(4, storage_1.IStorageService), __param(5, keybinding_1.IKeybindingService), __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[549/*vs/editor/contrib/wordHighlighter/wordHighlighter*/], __M([0/*require*/,1/*exports*/,356/*vs/nls!vs/editor/contrib/wordHighlighter/wordHighlighter*/,19/*vs/base/common/arrays*/,15/*vs/base/common/async*/,24/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/editorContextKeys*/,45/*vs/editor/common/model*/,29/*vs/editor/common/model/textModel*/,16/*vs/editor/common/modes*/,18/*vs/platform/contextkey/common/contextkey*/,23/*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 }); exports.editorWordHighlight = colorRegistry_1.registerColor('editor.wordHighlightBackground', { dark: '#575757B8', light: '#57575740', hc: null }, nls.localize(0, null), true); exports.editorWordHighlightStrong = colorRegistry_1.registerColor('editor.wordHighlightStrongBackground', { dark: '#004972B8', light: '#0e639c40', hc: null }, nls.localize(1, null), true); exports.editorWordHighlightBorder = colorRegistry_1.registerColor('editor.wordHighlightBorder', { light: null, dark: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(2, null)); exports.editorWordHighlightStrongBorder = colorRegistry_1.registerColor('editor.wordHighlightStrongBorder', { light: null, dark: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(3, null)); exports.overviewRulerWordHighlightForeground = colorRegistry_1.registerColor('editorOverviewRuler.wordHighlightForeground', { dark: '#A0A0A0CC', light: '#A0A0A0CC', hc: '#A0A0A0CC' }, nls.localize(4, null), true); exports.overviewRulerWordHighlightStrongForeground = colorRegistry_1.registerColor('editorOverviewRuler.wordHighlightStrongForeground', { dark: '#C0A0C0CC', light: '#C0A0C0CC', hc: '#C0A0C0CC' }, nls.localize(5, null), true); exports.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.registerDefaultLanguageCommand('_executeDocumentHighlights', function (model, position) { return getOccurrencesAtPosition(model, position, cancellation_1.CancellationToken.None); }); var WordHighlighter = /** @class */ (function () { function WordHighlighter(editor, contextKeyService) { var _this = this; this.workerRequestTokenId = 0; this.workerRequestCompleted = false; this.workerRequestValue = []; this.lastCursorPositionChangeTime = 0; this.renderDecorationsTimer = -1; this.editor = editor; this._hasWordHighlights = exports.ctxHasWordHighlights.bindTo(contextKeyService); this._ignorePositionChangeEvent = false; this.occurrencesHighlight = this.editor.getConfiguration().contribInfo.occurrencesHighlight; this.model = this.editor.getModel(); this.toUnhook = []; this.toUnhook.push(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.push(editor.onDidChangeModelContent(function (e) { _this._stopAll(); })); this.toUnhook.push(editor.onDidChangeConfiguration(function (e) { var newValue = _this.editor.getConfiguration().contribInfo.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.getConfiguration().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 = lifecycle_1.dispose(this.toUnhook); }; WordHighlighter._WRITE_OPTIONS = textModel_1.ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */, className: 'wordHighlightStrong', overviewRuler: { color: themeService_1.themeColorFromId(exports.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(exports.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; 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.getId = function () { return 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: exports.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: exports.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: exports.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); 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(exports.editorWordHighlight); if (wordHighlight) { collector.addRule(".monaco-editor .wordHighlight { background-color: " + wordHighlight + "; }"); } var wordHighlightStrong = theme.getColor(exports.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(exports.editorWordHighlightBorder); if (wordHighlightBorder) { collector.addRule(".monaco-editor .wordHighlight { border: 1px " + (theme.type === 'hc' ? 'dashed' : 'solid') + " " + wordHighlightBorder + "; box-sizing: border-box; }"); } var wordHighlightStrongBorder = theme.getColor(exports.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[550/*vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,26/*vs/base/browser/fastDomNode*/,119/*vs/base/browser/htmlContentRenderer*/,47/*vs/base/browser/ui/aria/aria*/,44/*vs/base/browser/ui/widget*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,5/*vs/base/common/strings*/,25/*vs/base/common/uri*/,11/*vs/editor/browser/editorExtensions*/,21/*vs/editor/common/editorContextKeys*/,164/*vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/,18/*vs/platform/contextkey/common/contextkey*/,13/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,56/*vs/platform/opener/common/opener*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,50/*vs/editor/common/standaloneStrings*/,372/*vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/]), function (require, exports, browser, dom, fastDomNode_1, htmlContentRenderer_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.getId = function () { return 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.getRawConfiguration().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 opts = this._editor.getConfiguration(); 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 (opts.wrappingInfo.inDiffEditor) { if (opts.readOnly) { text += standaloneStrings_1.AccessibilityHelpNLS.readonlyDiffEditor; } else { text += standaloneStrings_1.AccessibilityHelpNLS.editableDiffEditor; } } else { if (opts.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 (opts.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 (opts.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(htmlContentRenderer_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: null, 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); 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 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[551/*vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([0/*require*/,1/*exports*/,28/*vs/base/common/color*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,11/*vs/editor/browser/editorExtensions*/,16/*vs/editor/common/modes*/,61/*vs/editor/common/modes/nullMode*/,67/*vs/editor/common/services/modeService*/,82/*vs/editor/standalone/common/standaloneThemeService*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,50/*vs/editor/common/standaloneStrings*/,370/*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.getId = function () { return 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: null }) || 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); 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 + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[131/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/], __M([0/*require*/,1/*exports*/,11/*vs/editor/browser/editorExtensions*/,29/*vs/editor/common/model/textModel*/,499/*vs/editor/standalone/browser/quickOpen/quickOpenEditorWidget*/,14/*vs/platform/theme/common/themeService*/,369/*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.editor = editor; } QuickOpenController.get = function (editor) { return editor.getContribution(QuickOpenController.ID); }; QuickOpenController.prototype.getId = function () { return 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); }); /*--------------------------------------------------------------------------------------------- * 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/standalone/browser/quickOpen/gotoLine*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,120/*vs/base/parts/quickopen/browser/quickOpenModel*/,106/*vs/editor/browser/editorBrowser*/,11/*vs/editor/browser/editorExtensions*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/editorContextKeys*/,131/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/,50/*vs/editor/common/standaloneStrings*/,368/*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: null, 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[554/*vs/editor/standalone/browser/quickOpen/quickCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,30/*vs/base/browser/browser*/,10/*vs/base/common/errors*/,65/*vs/base/common/filters*/,120/*vs/base/parts/quickopen/browser/quickOpenModel*/,11/*vs/editor/browser/editorExtensions*/,21/*vs/editor/common/editorContextKeys*/,131/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/,37/*vs/platform/keybinding/common/keybinding*/,50/*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: null, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.focus, primary: (browser.isIE ? 512 /* Alt */ | 59 /* F1 */ : 59 /* F1 */), weight: 100 /* EditorContrib */ }, menuOpts: { 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[555/*vs/editor/standalone/browser/quickOpen/quickOutline*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/cancellation*/,65/*vs/base/common/filters*/,5/*vs/base/common/strings*/,120/*vs/base/parts/quickopen/browser/quickOpenModel*/,11/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/editorContextKeys*/,16/*vs/editor/common/modes*/,487/*vs/editor/contrib/quickOpen/quickOpen*/,131/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/,50/*vs/editor/common/standaloneStrings*/,366/*vs/css!vs/editor/standalone/browser/quickOpen/quickOutline*/]), 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 */ }, menuOpts: { 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 = null; if (element.containerName) { description = element.containerName; } // Add results.push(this.symbolEntry(label, modes_1.symbolKindToCssClass(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[556/*vs/editor/standalone/browser/standaloneCodeServiceImpl*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,53/*vs/base/common/network*/,502/*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[557/*vs/editor/standalone/common/themes*/], __M([0/*require*/,1/*exports*/,34/*vs/editor/common/view/editorColorRegistry*/,23/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, editorColorRegistry_1, colorRegistry_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _a, _b, _c; /* -------------------------------- 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: '09885A' }, { 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: '09885A' }, { token: 'attribute.value.unit', foreground: '09885A' }, { 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[558/*vs/editor/standalone/browser/standaloneThemeServiceImpl*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,28/*vs/base/common/color*/,4/*vs/base/common/event*/,16/*vs/editor/common/modes*/,256/*vs/editor/common/modes/supports/tokenization*/,557/*vs/editor/standalone/common/themes*/,40/*vs/platform/registry/common/platform*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, dom, color_1, event_1, modes_1, tokenization_1, themes_1, platform_1, colorRegistry_1, themeService_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 = Object.create(null); for (var id in this.themeData.colors) { colors[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[id]) { colors[id] = color_1.Color.fromHex(baseData.colors[id]); } } } this.colors = colors; } return this.colors; }; StandaloneTheme.prototype.getColor = function (colorId, useDefault) { var color = this.getColors()[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 }); 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 () { function StandaloneThemeServiceImpl() { this.environment = Object.create(null); this._onThemeChange = new event_1.Emitter(); this._onIconThemeChange = new event_1.Emitter(); 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._styleElement = dom.createStyleSheet(); this._styleElement.className = 'monaco-colors'; this.setTheme(VS_THEME_NAME); } Object.defineProperty(StandaloneThemeServiceImpl.prototype, "onThemeChange", { get: function () { return this._onThemeChange.event; }, enumerable: true, configurable: true }); 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._styleElement.innerHTML = cssRules.join('\n'); 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; }()); 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[559/*vs/platform/contextview/browser/contextMenuService*/], __M([0/*require*/,1/*exports*/,500/*vs/platform/contextview/browser/contextMenuHandler*/,59/*vs/platform/contextview/browser/contextView*/,97/*vs/platform/telemetry/common/telemetry*/,4/*vs/base/common/event*/,35/*vs/platform/notification/common/notification*/,14/*vs/platform/theme/common/themeService*/,37/*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[138/*vs/platform/list/browser/listService*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,135/*vs/base/browser/ui/list/listWidget*/,2/*vs/base/common/lifecycle*/,359/*vs/nls!vs/platform/list/browser/listService*/,41/*vs/platform/configuration/common/configuration*/,89/*vs/platform/configuration/common/configurationRegistry*/,18/*vs/platform/contextkey/common/contextkey*/,13/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,40/*vs/platform/registry/common/platform*/,85/*vs/platform/theme/common/styler*/,14/*vs/platform/theme/common/themeService*/,185/*vs/base/browser/ui/tree/objectTree*/,291/*vs/base/browser/ui/tree/asyncDataTree*/,289/*vs/base/browser/ui/tree/dataTree*/,75/*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, objectTree_1, asyncDataTree_1, dataTree_1, accessibility_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _a; exports.IListService = instantiation_1.createDecorator('listService'); var ListService = /** @class */ (function () { function ListService(contextKeyService) { this.lists = []; this._lastFocusedWidget = undefined; } 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.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; } var result = 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; } }) ]); return result; }; ListService = __decorate([ __param(0, contextkey_1.IContextKeyService) ], ListService); return ListService; }()); exports.ListService = ListService; var RawWorkbenchListFocusContextKey = new contextkey_1.RawContextKey('listFocus', true); exports.WorkbenchListSupportsMultiSelectContextKey = new contextkey_1.RawContextKey('listSupportsMultiselect', true); 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'; 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 = []; var result = __assign({}, options); if (options.multipleSelectionSupport !== false && !options.multipleSelectionController) { var multipleSelectionController = new MultipleSelectionController(configurationService); result.multipleSelectionController = multipleSelectionController; disposables.push(multipleSelectionController); } var openController = new WorkbenchOpenController(configurationService, options.openController); result.openController = openController; disposables.push(openController); if (options.keyboardNavigationLabelProvider) { var tlp_1 = options.keyboardNavigationLabelProvider; result.keyboardNavigationLabelProvider = { getKeyboardNavigationLabel: function (e) { return tlp_1.getKeyboardNavigationLabel(e); }, mightProducePrintableCharacter: function (e) { return keybindingService.mightProducePrintableCharacter(e); } }; } return [result, lifecycle_1.combinedDisposable(disposables)]; } var sharedListStyleSheet; function getSharedListStyleSheet() { if (!sharedListStyleSheet) { sharedListStyleSheet = dom_1.createStyleSheet(); } return sharedListStyleSheet; } 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(container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) { var _this = this; var _a = workbenchTreeDataPreamble(container, options, contextKeyService, themeService, configurationService, keybindingService, accessibilityService), treeOptions = _a.options, getAutomaticKeyboardNavigation = _a.getAutomaticKeyboardNavigation, disposable = _a.disposable; _this = _super.call(this, container, delegate, renderers, treeOptions) || this; _this.disposables.push(disposable); _this.internals = new WorkbenchTreeInternals(_this, treeOptions, getAutomaticKeyboardNavigation, contextKeyService, listService, themeService, configurationService, accessibilityService); _this.disposables.push(_this.internals); return _this; } WorkbenchObjectTree = __decorate([ __param(4, contextkey_1.IContextKeyService), __param(5, exports.IListService), __param(6, themeService_1.IThemeService), __param(7, configuration_1.IConfigurationService), __param(8, keybinding_1.IKeybindingService), __param(9, accessibility_1.IAccessibilityService) ], WorkbenchObjectTree); return WorkbenchObjectTree; }(objectTree_1.ObjectTree)); exports.WorkbenchObjectTree = WorkbenchObjectTree; var WorkbenchDataTree = /** @class */ (function (_super) { __extends(WorkbenchDataTree, _super); function WorkbenchDataTree(container, delegate, renderers, dataSource, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) { var _this = this; var _a = workbenchTreeDataPreamble(container, options, contextKeyService, themeService, configurationService, keybindingService, accessibilityService), treeOptions = _a.options, getAutomaticKeyboardNavigation = _a.getAutomaticKeyboardNavigation, disposable = _a.disposable; _this = _super.call(this, container, delegate, renderers, dataSource, treeOptions) || this; _this.disposables.push(disposable); _this.internals = new WorkbenchTreeInternals(_this, treeOptions, getAutomaticKeyboardNavigation, contextKeyService, listService, themeService, configurationService, accessibilityService); _this.disposables.push(_this.internals); return _this; } WorkbenchDataTree = __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) ], WorkbenchDataTree); return WorkbenchDataTree; }(dataTree_1.DataTree)); exports.WorkbenchDataTree = WorkbenchDataTree; var WorkbenchAsyncDataTree = /** @class */ (function (_super) { __extends(WorkbenchAsyncDataTree, _super); function WorkbenchAsyncDataTree(container, delegate, renderers, dataSource, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) { var _this = this; var _a = workbenchTreeDataPreamble(container, options, contextKeyService, themeService, configurationService, keybindingService, accessibilityService), treeOptions = _a.options, getAutomaticKeyboardNavigation = _a.getAutomaticKeyboardNavigation, disposable = _a.disposable; _this = _super.call(this, container, delegate, renderers, dataSource, treeOptions) || this; _this.disposables.push(disposable); _this.internals = new WorkbenchTreeInternals(_this, treeOptions, getAutomaticKeyboardNavigation, contextKeyService, listService, themeService, configurationService, accessibilityService); _this.disposables.push(_this.internals); return _this; } Object.defineProperty(WorkbenchAsyncDataTree.prototype, "contextKeyService", { get: function () { return this.internals.contextKeyService; }, enumerable: true, configurable: true }); WorkbenchAsyncDataTree = __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) ], WorkbenchAsyncDataTree); return WorkbenchAsyncDataTree; }(asyncDataTree_1.AsyncDataTree)); exports.WorkbenchAsyncDataTree = WorkbenchAsyncDataTree; function workbenchTreeDataPreamble(container, options, contextKeyService, themeService, 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.getAccessibilitySupport() === 2 /* Enabled */; 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]; return { getAutomaticKeyboardNavigation: getAutomaticKeyboardNavigation, disposable: disposable, options: __assign({ keyboardSupport: false, styleController: new listWidget_1.DefaultStyleController(getSharedListStyleSheet()) }, styler_1.computeStyles(themeService.getTheme(), styler_1.defaultListStyles), workbenchListOptions, { indent: configurationService.getValue(treeIndentKey), automaticKeyboardNavigation: getAutomaticKeyboardNavigation(), simpleKeyboardNavigation: keyboardNavigation === 'simple', filterOnType: keyboardNavigation === 'filter', horizontalScrolling: horizontalScrolling, openOnSingleClick: openOnSingleClick, keyboardNavigationEventFilter: createKeyboardNavigationEventFilter(container, keybindingService) }) }; } var WorkbenchTreeInternals = /** @class */ (function () { function WorkbenchTreeInternals(tree, options, getAutomaticKeyboardNavigation, contextKeyService, listService, themeService, configurationService, accessibilityService) { var _this = this; 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.getAccessibilitySupport() === 2 /* Enabled */; var keyboardNavigation = accessibilityOn ? 'simple' : configurationService.getValue(exports.keyboardNavigationSettingKey); tree.updateOptions({ simpleKeyboardNavigation: keyboardNavigation === 'simple', filterOnType: keyboardNavigation === 'filter' }); }; this.disposables.push(this.contextKeyService, listService.register(tree), styler_1.attachListStyler(tree, themeService), 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(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.onDidChangeAccessibilitySupport(function () { return updateKeyboardNavigation(); })); } WorkbenchTreeInternals.prototype.dispose = function () { this.disposables = lifecycle_1.dispose(this.disposables); }; WorkbenchTreeInternals = __decorate([ __param(3, contextkey_1.IContextKeyService), __param(4, exports.IListService), __param(5, themeService_1.IThemeService), __param(6, configuration_1.IConfigurationService), __param(7, 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[exports.keyboardNavigationSettingKey] = { 'type': 'string', 'enum': ['simple', 'highlight', 'filter'], 'enumDescriptions': [ nls_1.localize(9, null), nls_1.localize(10, null), nls_1.localize(11, null) ], 'default': 'highlight', 'description': nls_1.localize(12, null) }, _a[exports.automaticKeyboardNavigationSettingKey] = { 'type': 'boolean', 'default': true, markdownDescription: nls_1.localize(13, 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[141/*vs/editor/contrib/referenceSearch/referencesWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,28/*vs/base/common/color*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,53/*vs/base/common/network*/,54/*vs/base/common/resources*/,118/*vs/editor/browser/widget/embeddedCodeEditorWidget*/,3/*vs/editor/common/core/range*/,29/*vs/editor/common/model/textModel*/,80/*vs/editor/common/services/resolverService*/,546/*vs/editor/contrib/referenceSearch/referencesTree*/,347/*vs/nls!vs/editor/contrib/referenceSearch/referencesWidget*/,18/*vs/platform/contextkey/common/contextkey*/,13/*vs/platform/instantiation/common/instantiation*/,125/*vs/platform/label/common/label*/,138/*vs/platform/list/browser/listService*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,105/*vs/editor/contrib/referenceSearch/peekViewWidget*/,90/*vs/editor/contrib/referenceSearch/referencesModel*/,446/*vs/base/browser/ui/splitview/splitview*/,378/*vs/css!vs/editor/contrib/referenceSearch/media/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, contextkey_1, instantiation_1, label_1, listService_1, colorRegistry_1, themeService_1, peekViewWidget_1, 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 = []; this._callOnModelChange = []; this._callOnDispose.push(this._editor.onDidChangeModel(function () { return _this._onModelChanged(); })); this._onModelChanged(); } DecorationsManager.prototype.dispose = function () { this._callOnModelChange = lifecycle_1.dispose(this._callOnModelChange); this._callOnDispose = lifecycle_1.dispose(this._callOnDispose); this.removeDecorations(); }; DecorationsManager.prototype._onModelChanged = function () { this._callOnModelChange = lifecycle_1.dispose(this._callOnModelChange); var model = this._editor.getModel(); if (model) { for (var _i = 0, _a = this._model.groups; _i < _a.length; _i++) { var ref = _a[_i]; if (ref.uri.toString() === model.uri.toString()) { this._addDecorations(ref); return; } } } }; DecorationsManager.prototype._addDecorations = function (reference) { var _this = this; if (!this._editor.hasModel()) { return; } this._callOnModelChange.push(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() { } 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; exports.ctxReferenceWidgetSearchTreeFocused = new contextkey_1.RawContextKey('referenceSearchTreeFocused', true); /** * 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 = []; _this._callOnDispose = []; _this._onDidSelectReference = new event_1.Emitter(); _this._dim = { height: 0, width: 0 }; _this._applyTheme(themeService.getTheme()); _this._callOnDispose.push(themeService.onThemeChange(_this._applyTheme.bind(_this))); _this._peekViewService.addExclusiveWidget(editor, _this); _this.create(); return _this; } ReferenceWidget.prototype.dispose = function () { this.setModel(undefined); this._callOnDispose = lifecycle_1.dispose(this._callOnDispose); lifecycle_1.dispose(this._preview, this._previewNotAvailableMessage, this._tree, this._previewModelReference); this._splitView.dispose(); _super.prototype.dispose.call(this); }; ReferenceWidget.prototype._applyTheme = function (theme) { var borderColor = theme.getColor(exports.peekViewBorder) || color_1.Color.transparent; this.style({ arrowColor: borderColor, frameColor: borderColor, headerBackgroundColor: theme.getColor(exports.peekViewTitleBackground) || color_1.Color.transparent, primaryHeadingColor: theme.getColor(exports.peekViewTitleForeground), secondaryHeadingColor: theme.getColor(exports.peekViewTitleInfoForeground) }); }; Object.defineProperty(ReferenceWidget.prototype, "onDidSelectReference", { get: function () { return this._onDidSelectReference.event; }, enumerable: true, configurable: true }); ReferenceWidget.prototype.show = function (where) { this.editor.revealRangeInCenterIfOutsideViewport(where, 0 /* Smooth */); _super.prototype.show.call(this, where, this.layoutData.heightInLines || 18); }; ReferenceWidget.prototype.focus = function () { this._tree.domFocus(); }; 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 }, 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() }; this._tree = this._instantiationService.createInstance(listService_1.WorkbenchAsyncDataTree, 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); exports.ctxReferenceWidgetSearchTreeFocused.bindTo(this._tree.contextKeyService); // 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._splitView.onDidSashChange(function () { if (_this._dim.width) { _this.layoutData.ratio = _this._splitView.getViewSize(0) / _this._dim.width; } }, undefined, this._disposables); // 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.onDidChangeSelection(function (e) { var aside = false; var goto = false; if (e.browserEvent instanceof KeyboardEvent) { // todo@joh make this a command goto = true; } if (aside) { onEvent(e.elements[0], 'side'); } else if (goto) { onEvent(e.elements[0], 'goto'); } else { onEvent(e.elements[0], 'show'); } }); this._tree.onDidOpen(function (e) { var aside = (e.browserEvent instanceof MouseEvent) && (e.browserEvent.ctrlKey || e.browserEvent.metaKey || e.browserEvent.altKey); var goto = !e.browserEvent || ((e.browserEvent instanceof MouseEvent) && e.browserEvent.detail === 2); if (aside) { onEvent(e.elements[0], 'side'); } else if (goto) { onEvent(e.elements[0], 'goto'); } else { 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 = lifecycle_1.dispose(this._disposeOnNewModel); 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.empty) { 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.push(this._decorationsManager); // listen on model changes this._disposeOnNewModel.push(this._model.onDidChangeReferenceRange(function (reference) { return _this._tree.rerender(reference); })); // listen on editor this._disposeOnNewModel.push(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.focus(); // 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, peekViewWidget_1.IPeekViewService), __param(7, label_1.ILabelService) ], ReferenceWidget); return ReferenceWidget; }(peekViewWidget_1.PeekViewWidget)); exports.ReferenceWidget = ReferenceWidget; // theming exports.peekViewTitleBackground = colorRegistry_1.registerColor('peekViewTitle.background', { dark: '#1E1E1E', light: '#FFFFFF', hc: '#0C141F' }, nls.localize(4, null)); exports.peekViewTitleForeground = colorRegistry_1.registerColor('peekViewTitleLabel.foreground', { dark: '#FFFFFF', light: '#333333', hc: '#FFFFFF' }, nls.localize(5, null)); exports.peekViewTitleInfoForeground = colorRegistry_1.registerColor('peekViewTitleDescription.foreground', { dark: '#ccccccb3', light: '#6c6c6cb3', hc: '#FFFFFF99' }, nls.localize(6, null)); exports.peekViewBorder = colorRegistry_1.registerColor('peekView.border', { dark: '#007acc', light: '#007acc', hc: colorRegistry_1.contrastBorder }, nls.localize(7, null)); exports.peekViewResultsBackground = colorRegistry_1.registerColor('peekViewResult.background', { dark: '#252526', light: '#F3F3F3', hc: color_1.Color.black }, nls.localize(8, null)); exports.peekViewResultsMatchForeground = colorRegistry_1.registerColor('peekViewResult.lineForeground', { dark: '#bbbbbb', light: '#646465', hc: color_1.Color.white }, nls.localize(9, null)); exports.peekViewResultsFileForeground = colorRegistry_1.registerColor('peekViewResult.fileForeground', { dark: color_1.Color.white, light: '#1E1E1E', hc: color_1.Color.white }, nls.localize(10, null)); exports.peekViewResultsSelectionBackground = colorRegistry_1.registerColor('peekViewResult.selectionBackground', { dark: '#3399ff33', light: '#3399ff33', hc: null }, nls.localize(11, null)); exports.peekViewResultsSelectionForeground = colorRegistry_1.registerColor('peekViewResult.selectionForeground', { dark: color_1.Color.white, light: '#6C6C6C', hc: color_1.Color.white }, nls.localize(12, null)); exports.peekViewEditorBackground = colorRegistry_1.registerColor('peekViewEditor.background', { dark: '#001F33', light: '#F2F8FC', hc: color_1.Color.black }, nls.localize(13, null)); exports.peekViewEditorGutterBackground = colorRegistry_1.registerColor('peekViewEditorGutter.background', { dark: exports.peekViewEditorBackground, light: exports.peekViewEditorBackground, hc: exports.peekViewEditorBackground }, nls.localize(14, null)); exports.peekViewResultsMatchHighlight = colorRegistry_1.registerColor('peekViewResult.matchHighlightBackground', { dark: '#ea5c004d', light: '#ea5c004d', hc: null }, nls.localize(15, null)); exports.peekViewEditorMatchHighlight = colorRegistry_1.registerColor('peekViewEditor.matchHighlightBackground', { dark: '#ff8f0099', light: '#f5d802de', hc: null }, nls.localize(16, null)); exports.peekViewEditorMatchHighlightBorder = colorRegistry_1.registerColor('peekViewEditor.matchHighlightBorder', { dark: null, light: null, hc: colorRegistry_1.activeContrastBorder }, nls.localize(17, null)); themeService_1.registerThemingParticipant(function (theme, collector) { var findMatchHighlightColor = theme.getColor(exports.peekViewResultsMatchHighlight); if (findMatchHighlightColor) { collector.addRule(".monaco-editor .reference-zone-widget .ref-tree .referenceMatch { background-color: " + findMatchHighlightColor + "; }"); } var referenceHighlightColor = theme.getColor(exports.peekViewEditorMatchHighlight); if (referenceHighlightColor) { collector.addRule(".monaco-editor .reference-zone-widget .preview .reference-decoration { background-color: " + referenceHighlightColor + "; }"); } var referenceHighlightBorder = theme.getColor(exports.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 { border: 1px dotted " + hcOutline + "; box-sizing: border-box; }"); } var resultsBackground = theme.getColor(exports.peekViewResultsBackground); if (resultsBackground) { collector.addRule(".monaco-editor .reference-zone-widget .ref-tree { background-color: " + resultsBackground + "; }"); } var resultsMatchForeground = theme.getColor(exports.peekViewResultsMatchForeground); if (resultsMatchForeground) { collector.addRule(".monaco-editor .reference-zone-widget .ref-tree { color: " + resultsMatchForeground + "; }"); } var resultsFileForeground = theme.getColor(exports.peekViewResultsFileForeground); if (resultsFileForeground) { collector.addRule(".monaco-editor .reference-zone-widget .ref-tree .reference-file { color: " + resultsFileForeground + "; }"); } var resultsSelectedBackground = theme.getColor(exports.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(exports.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(exports.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(exports.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[562/*vs/editor/contrib/gotoError/gotoErrorWidget*/], __M([0/*require*/,1/*exports*/,331/*vs/nls!vs/editor/contrib/gotoError/gotoErrorWidget*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,66/*vs/platform/markers/common/markers*/,3/*vs/editor/common/core/range*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,28/*vs/base/common/color*/,34/*vs/editor/common/view/editorColorRegistry*/,51/*vs/base/browser/ui/scrollbar/scrollableElement*/,199/*vs/base/common/labels*/,19/*vs/base/common/arrays*/,4/*vs/base/common/event*/,105/*vs/editor/contrib/referenceSearch/peekViewWidget*/,54/*vs/base/common/resources*/,141/*vs/editor/contrib/referenceSearch/referencesWidget*/,386/*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, editorColorRegistry_1, scrollableElement_1, labels_1, arrays_1, event_1, peekViewWidget_1, resources_1, referencesWidget_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MessageWidget = /** @class */ (function () { function MessageWidget(parent, editor, onRelatedInformation) { var _this = this; this._lines = 0; this._longestLineLength = 0; this._relatedDiagnostics = new WeakMap(); this._disposables = []; 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.push(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.push(this._scrollable.onScroll(function (e) { domNode.style.left = "-" + e.scrollLeft + "px"; domNode.style.top = "-" + e.scrollTop + "px"; })); this._disposables.push(this._scrollable); } MessageWidget.prototype.dispose = function () { lifecycle_1.dispose(this._disposables); }; MessageWidget.prototype.update = function (_a) { var source = _a.source, message = _a.message, relatedInformation = _a.relatedInformation, code = _a.code; 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, 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) { var codeElement = document.createElement('span'); codeElement.innerText = "(" + code + ")"; dom.addClass(codeElement, 'code'); detailsElement.appendChild(codeElement); } } 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.getConfiguration().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.getConfiguration().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) { var _this = _super.call(this, editor, { showArrow: true, showFrame: true, isAccessible: true }) || this; _this.actions = actions; _this._themeService = _themeService; _this._callOnDispose = []; _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.push(_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(referencesWidget_1.peekViewTitleForeground), secondaryHeadingColor: theme.getColor(referencesWidget_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 = lifecycle_1.dispose(this._callOnDispose); _super.prototype.dispose.call(this); }; MarkerNavigationWidget.prototype.focus = function () { this._parentContainer.focus(); }; MarkerNavigationWidget.prototype._fillHead = function (container) { _super.prototype._fillHead.call(this, container); this._actionbarWidget.push(this.actions, { label: false, icon: true }); }; MarkerNavigationWidget.prototype._getActionBarOptions = function () { return { orientation: 1 /* HORIZONTAL_REVERSE */ }; }; 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._disposables.push(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); } var headingIconClassName = 'error'; if (this._severity === markers_1.MarkerSeverity.Warning) { headingIconClassName = 'warning'; } else if (this._severity === markers_1.MarkerSeverity.Info) { headingIconClassName = 'info'; } this.setTitleIcon(headingIconClassName); this.editor.revealPositionInCenter(position, 0 /* Smooth */); if (this.editor.getConfiguration().accessibilitySupport !== 1 /* Disabled */) { this.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; }(peekViewWidget_1.PeekViewWidget)); exports.MarkerNavigationWidget = MarkerNavigationWidget; // theming var errorDefault = colorRegistry_1.oneOf(editorColorRegistry_1.editorErrorForeground, editorColorRegistry_1.editorErrorBorder); var warningDefault = colorRegistry_1.oneOf(editorColorRegistry_1.editorWarningForeground, editorColorRegistry_1.editorWarningBorder); var infoDefault = colorRegistry_1.oneOf(editorColorRegistry_1.editorInfoForeground, editorColorRegistry_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 link = theme.getColor(colorRegistry_1.textLinkForeground); if (link) { collector.addRule(".monaco-editor .marker-widget a { color: " + link + "; }"); } }); }); /*--------------------------------------------------------------------------------------------- * 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/gotoError/gotoError*/], __M([0/*require*/,1/*exports*/,330/*vs/nls!vs/editor/contrib/gotoError/gotoError*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,18/*vs/platform/contextkey/common/contextkey*/,66/*vs/platform/markers/common/markers*/,3/*vs/editor/common/core/range*/,11/*vs/editor/browser/editorExtensions*/,14/*vs/platform/theme/common/themeService*/,21/*vs/editor/common/editorContextKeys*/,562/*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*/,58/*vs/platform/actions/common/actions*/,49/*vs/base/common/actions*/,37/*vs/platform/keybinding/common/keybinding*/]), 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) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MarkerModel = /** @class */ (function () { function MarkerModel(editor, markers) { var _this = this; this._editor = editor; this._markers = []; this._nextIdx = -1; this._toUnbind = []; this._ignoreSelectionChange = false; this._onCurrentMarkerChanged = new event_1.Emitter(); this._onMarkerSetChanged = new event_1.Emitter(); this.setMarkers(markers); // listen on editor this._toUnbind.push(this._editor.onDidDispose(function () { return _this.dispose(); })); this._toUnbind.push(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) { for (var _i = 0, _a = this._markers; _i < _a.length; _i++) { var marker = _a[_i]; if (range_1.Range.containsPosition(marker, pos)) { return marker; } } return undefined; }; 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 = lifecycle_1.dispose(this._toUnbind); }; return MarkerModel; }()); var MarkerController = /** @class */ (function () { function MarkerController(editor, _markerService, _contextKeyService, _themeService, _editorService, _keybindingService) { this._markerService = _markerService; this._contextKeyService = _contextKeyService; this._themeService = _themeService; this._editorService = _editorService; this._keybindingService = _keybindingService; this._model = null; this._widget = null; this._disposeOnClose = []; this._editor = editor; this._widgetVisible = CONTEXT_MARKERS_NAVIGATION_VISIBLE.bindTo(this._contextKeyService); } MarkerController.get = function (editor) { return editor.getContribution(MarkerController.ID); }; MarkerController.prototype.getId = function () { return MarkerController.ID; }; MarkerController.prototype.dispose = function () { this._cleanUp(); }; MarkerController.prototype._cleanUp = function () { this._widgetVisible.reset(); this._disposeOnClose = lifecycle_1.dispose(this._disposeOnClose); this._widget = null; this._model = null; }; MarkerController.prototype.getOrCreateModel = function () { var _this = this; var _a; 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(PrevMarkerAction.ID, PrevMarkerAction.LABEL + (prevMarkerKeybinding ? " (" + prevMarkerKeybinding.getLabel() + ")" : ''), 'show-previous-problem 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*/]; }); }); }), new actions_2.Action(NextMarkerAction.ID, NextMarkerAction.LABEL + (nextMarkerKeybinding ? " (" + nextMarkerKeybinding.getLabel() + ")" : ''), 'show-next-problem 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*/]; }); }); }) ]; this._widget = new gotoErrorWidget_1.MarkerNavigationWidget(this._editor, actions, this._themeService); this._widgetVisible.set(true); this._widget.onDidClose(function () { return _this._cleanUp(); }, this, this._disposeOnClose); this._disposeOnClose.push(this._model); this._disposeOnClose.push(this._widget); (_a = this._disposeOnClose).push.apply(_a, actions); this._disposeOnClose.push(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.push(this._editor.onDidChangeModel(function () { return _this._cleanUp(); })); this._disposeOnClose.push(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.push(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 editorModel.uri.toString() === r.toString(); })) { 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) ], 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 (newMarker.resource.toString() === editorModel.uri.toString()) { // 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 Error or Warning', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, 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 Error or Warning', precondition: editorContextKeys_1.EditorContextKeys.writable, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, 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 Error or Warning in Files', 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 Error or Warning in Files', 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); 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(16 /* MenubarGoMenu */, { group: '6_problem_nav', command: { id: 'editor.action.marker.nextInFiles', title: nls.localize(4, null) }, order: 1 }); actions_1.MenuRegistry.appendMenuItem(16 /* 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. *--------------------------------------------------------------------------------------------*/ define(__m[564/*vs/editor/contrib/hover/modesContentHover*/], __M([0/*require*/,1/*exports*/,333/*vs/nls!vs/editor/contrib/hover/modesContentHover*/,7/*vs/base/browser/dom*/,24/*vs/base/common/cancellation*/,28/*vs/base/common/color*/,87/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,29/*vs/editor/common/model/textModel*/,16/*vs/editor/common/modes*/,173/*vs/editor/contrib/colorPicker/color*/,172/*vs/editor/contrib/colorPicker/colorDetector*/,244/*vs/editor/contrib/colorPicker/colorPickerModel*/,531/*vs/editor/contrib/colorPicker/colorPickerWidget*/,483/*vs/editor/contrib/hover/getHover*/,203/*vs/editor/contrib/hover/hoverOperation*/,202/*vs/editor/contrib/hover/hoverWidgets*/,99/*vs/editor/contrib/markdown/markdownRenderer*/,19/*vs/base/common/arrays*/,66/*vs/platform/markers/common/markers*/,54/*vs/base/common/resources*/,10/*vs/base/common/errors*/,56/*vs/platform/opener/common/opener*/,197/*vs/editor/contrib/gotoError/gotoError*/,15/*vs/base/common/async*/,177/*vs/editor/contrib/codeAction/codeAction*/,182/*vs/editor/contrib/codeAction/codeActionCommands*/,49/*vs/base/common/actions*/,151/*vs/editor/contrib/codeAction/codeActionTrigger*/,20/*vs/base/common/types*/]), 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, arrays_1, markers_1, resources_1, errors_1, opener_1, gotoError_1, async_1, codeAction_1, codeActionCommands_1, actions_1, codeActionTrigger_1, types_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._range = null; } 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: types_1.withNullAsUndefined(this._range), contents: [new htmlContent_1.MarkdownString().appendText(nls.localize(0, null))] }; }; return ModesContentComputer; }()); var ModesContentHoverWidget = /** @class */ (function (_super) { __extends(ModesContentHoverWidget, _super); function ModesContentHoverWidget(editor, markerDecorationsService, _themeService, _keybindingService, _contextMenuService, _bulkEditService, _commandService, _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._contextMenuService = _contextMenuService; _this._bulkEditService = _bulkEditService; _this._commandService = _commandService; _this._modeService = _modeService; _this._openerService = _openerService; _this.renderDisposable = lifecycle_1.Disposable.None; _this._messages = []; _this._lastRange = null; _this._computer = new ModesContentComputer(_this._editor, markerDecorationsService); _this._highlightDecorations = []; _this._isChangingDecorations = false; _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.getConfiguration().contribInfo.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.getConfiguration().contribInfo.hover.delay); })); return _this; } ModesContentHoverWidget.prototype.dispose = function () { this.renderDisposable.dispose(); this.renderDisposable = lifecycle_1.Disposable.None; 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.dispose(); this.renderDisposable = lifecycle_1.Disposable.None; 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 = Number.MAX_VALUE; 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 = []; 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(red * 255, green * 255, 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.getConfiguration().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 = model_1.presentation.additionalTextEdits.slice(); _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 = lifecycle_1.combinedDisposable([colorListener, colorChangeListener, widget_1].concat(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 = new markdownRenderer_1.MarkdownRenderer(_this._editor, _this._modeService, _this._openerService); markdownDisposeables.push(renderer.onDidRenderCodeBlock(function () { hoverContentsElement.className = 'hover-contents code-hover-contents'; _this.onContentsChange(); })); var renderedContents = renderer.render(contents); hoverContentsElement.appendChild(renderedContents.element); fragment.appendChild(markdownHoverElement); markdownDisposeables.push(renderedContents); 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) { var detailsElement = dom.append(markerElement, $('span')); detailsElement.style.opacity = '0.6'; detailsElement.style.paddingLeft = '6px'; detailsElement.innerText = source && code ? source + "(" + code + ")" : source ? source : "(" + code + ")"; } 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 })).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 = []; var actionsElement = dom.append(hoverElement, $('div.actions')); disposables.push(this.renderAction(actionsElement, { label: nls.localize(1, null), commandId: codeActionCommands_1.QuickFixAction.Id, run: function (target) { return __awaiter(_this, void 0, void 0, function () { var codeActionsPromise, actions, elementPosition; return __generator(this, function (_a) { switch (_a.label) { case 0: codeActionsPromise = this.getCodeActions(markerHover.marker); disposables.push(lifecycle_1.toDisposable(function () { return codeActionsPromise.cancel(); })); return [4 /*yield*/, codeActionsPromise]; case 1: actions = _a.sent(); elementPosition = dom.getDomNodePagePosition(target); this._contextMenuService.showContextMenu({ getAnchor: function () { return ({ x: elementPosition.left + 6, y: elementPosition.top + elementPosition.height + 6 }); }, getActions: function () { return actions; } }); return [2 /*return*/]; } }); }); } })); if (markerHover.marker.severity === markers_1.MarkerSeverity.Error || markerHover.marker.severity === markers_1.MarkerSeverity.Warning || markerHover.marker.severity === markers_1.MarkerSeverity.Info) { disposables.push(this.renderAction(actionsElement, { label: nls.localize(2, null), commandId: gotoError_1.NextMarkerAction.ID, run: function () { _this.hide(); gotoError_1.MarkerController.get(_this._editor).show(markerHover.marker); _this._editor.focus(); } })); } this.renderDisposable = lifecycle_1.combinedDisposable(disposables); return hoverElement; }; ModesContentHoverWidget.prototype.getCodeActions = function (marker) { var _this = this; return async_1.createCancelablePromise(function (cancellationToken) { return __awaiter(_this, void 0, void 0, function () { var codeActions; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, codeAction_1.getCodeActions(this._editor.getModel(), new range_1.Range(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn), { type: 'manual', filter: { kind: codeActionTrigger_1.CodeActionKind.QuickFix } }, cancellationToken)]; case 1: codeActions = _a.sent(); if (codeActions.actions.length) { return [2 /*return*/, codeActions.actions.map(function (codeAction) { return new actions_1.Action(codeAction.command ? codeAction.command.id : codeAction.title, codeAction.title, undefined, true, function () { return codeActionCommands_1.applyCodeAction(codeAction, _this._bulkEditService, _this._commandService); }); })]; } return [2 /*return*/, [ new actions_1.Action('', nls.localize(3, null)) ]]; } }); }); }); }; 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; } }); /*--------------------------------------------------------------------------------------------- * 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/contrib/hover/hover*/], __M([0/*require*/,1/*exports*/,332/*vs/nls!vs/editor/contrib/hover/hover*/,36/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/editorContextKeys*/,67/*vs/editor/common/services/modeService*/,564/*vs/editor/contrib/hover/modesContentHover*/,439/*vs/editor/contrib/hover/modesGlyphHover*/,56/*vs/platform/opener/common/opener*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,211/*vs/editor/common/services/markersDecorationService*/,37/*vs/platform/keybinding/common/keybinding*/,59/*vs/platform/contextview/browser/contextView*/,98/*vs/editor/browser/services/bulkEditService*/,27/*vs/platform/commands/common/commands*/,385/*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, contextView_1, bulkEditService_1, commands_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ModesHoverController = /** @class */ (function () { function ModesHoverController(_editor, _openerService, _modeService, _markerDecorationsService, _keybindingService, _contextMenuService, _bulkEditService, _commandService, _themeService) { var _this = this; this._editor = _editor; this._openerService = _openerService; this._modeService = _modeService; this._markerDecorationsService = _markerDecorationsService; this._keybindingService = _keybindingService; this._contextMenuService = _contextMenuService; this._bulkEditService = _bulkEditService; this._commandService = _commandService; this._themeService = _themeService; this._toUnhook = []; this._isMouseDown = false; this._hoverClicked = false; this._hookEvents(); this._didChangeConfigurationHandler = this._editor.onDidChangeConfiguration(function (e) { if (e.contribInfo) { _this._hideWidgets(); _this._unhookEvents(); _this._hookEvents(); } }); } Object.defineProperty(ModesHoverController.prototype, "contentWidget", { get: function () { if (!this._contentWidget) { this._createHoverWidget(); } return this._contentWidget; }, enumerable: true, configurable: true }); Object.defineProperty(ModesHoverController.prototype, "glyphWidget", { get: function () { if (!this._glyphWidget) { this._createHoverWidget(); } return this._glyphWidget; }, 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.getConfiguration().contribInfo.hover; this._isHoverEnabled = hoverOpts.enabled; this._isHoverSticky = hoverOpts.sticky; if (this._isHoverEnabled) { this._toUnhook.push(this._editor.onMouseDown(function (e) { return _this._onEditorMouseDown(e); })); this._toUnhook.push(this._editor.onMouseUp(function (e) { return _this._onEditorMouseUp(e); })); this._toUnhook.push(this._editor.onMouseMove(function (e) { return _this._onEditorMouseMove(e); })); this._toUnhook.push(this._editor.onKeyDown(function (e) { return _this._onKeyDown(e); })); this._toUnhook.push(this._editor.onDidChangeModelDecorations(function () { return _this._onModelDecorationsChanged(); })); } else { this._toUnhook.push(this._editor.onMouseMove(hideWidgetsEventHandler)); } this._toUnhook.push(this._editor.onMouseLeave(hideWidgetsEventHandler)); this._toUnhook.push(this._editor.onDidChangeModel(hideWidgetsEventHandler)); this._toUnhook.push(this._editor.onDidScrollChange(function (e) { return _this._onEditorScrollChanged(e); })); }; ModesHoverController.prototype._unhookEvents = function () { this._toUnhook = lifecycle_1.dispose(this._toUnhook); }; 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) { // const this._editor.getConfiguration().contribInfo.hover.sticky; 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.getConfiguration().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._contentWidget || (this._isMouseDown && this._hoverClicked && this._contentWidget.isColorPickerVisible())) { return; } this._glyphWidget.hide(); this._contentWidget.hide(); }; ModesHoverController.prototype._createHoverWidget = function () { this._contentWidget = new modesContentHover_1.ModesContentHoverWidget(this._editor, this._markerDecorationsService, this._themeService, this._keybindingService, this._contextMenuService, this._bulkEditService, this._commandService, this._modeService, this._openerService); this._glyphWidget = 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.getId = function () { return ModesHoverController.ID; }; ModesHoverController.prototype.dispose = function () { this._unhookEvents(); this._didChangeConfigurationHandler.dispose(); if (this._glyphWidget) { this._glyphWidget.dispose(); } if (this._contentWidget) { 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, contextView_1.IContextMenuService), __param(6, bulkEditService_1.IBulkEditService), __param(7, commands_1.ICommandService), __param(8, 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: null, 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.getConfiguration().accessibilitySupport === 2 /* Enabled */; controller.showContentHover(range, 1 /* Immediate */, focus); }; return ShowHoverAction; }(editorExtensions_1.EditorAction)); editorExtensions_1.registerEditorContribution(ModesHoverController); editorExtensions_1.registerEditorAction(ShowHoverAction); // 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 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[143/*vs/editor/contrib/referenceSearch/referencesController*/], __M([0/*require*/,1/*exports*/,343/*vs/nls!vs/editor/contrib/referenceSearch/referencesController*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,32/*vs/editor/browser/services/codeEditorService*/,13/*vs/platform/instantiation/common/instantiation*/,18/*vs/platform/contextkey/common/contextkey*/,41/*vs/platform/configuration/common/configuration*/,68/*vs/platform/storage/common/storage*/,141/*vs/editor/contrib/referenceSearch/referencesWidget*/,3/*vs/editor/common/core/range*/,12/*vs/editor/common/core/position*/,35/*vs/platform/notification/common/notification*/]), function (require, exports, nls, errors_1, lifecycle_1, codeEditorService_1, instantiation_1, contextkey_1, configuration_1, storage_1, referencesWidget_1, range_1, position_1, notification_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._editorService = _editorService; this._notificationService = _notificationService; this._instantiationService = _instantiationService; this._storageService = _storageService; this._configurationService = _configurationService; this._requestIdPool = 0; this._disposables = []; this._ignoreModelChangeEvent = false; this._editor = editor; this._referenceSearchVisible = exports.ctxReferenceSearchVisible.bindTo(contextKeyService); } ReferencesController.get = function (editor) { return editor.getContribution(ReferencesController.ID); }; ReferencesController.prototype.getId = function () { return ReferencesController.ID; }; ReferencesController.prototype.dispose = function () { this._referenceSearchVisible.reset(); lifecycle_1.dispose(this._disposables); if (this._widget) { lifecycle_1.dispose(this._widget); this._widget = null; } if (this._model) { lifecycle_1.dispose(this._model); this._model = null; } }; ReferencesController.prototype.toggleWidget = function (range, modelPromise, options) { 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._referenceSearchVisible.set(true); // close the widget on model/mode changes this._disposables.push(this._editor.onDidChangeModelLanguage(function () { _this.closeWidget(); })); this._disposables.push(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.push(this._widget.onDidClose(function () { modelPromise.cancel(); if (_this._widget) { _this._storageService.store(storageKey, JSON.stringify(_this._widget.layoutData), 0 /* GLOBAL */); _this._widget = null; } _this.closeWidget(); })); this._disposables.push(this._widget.onDidSelectReference(function (event) { var element = event.element, kind = event.kind; 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 break; } case 'side': if (element) { _this.openReference(element, kind === 'side'); } break; case 'goto': if (element) { if (options.onGoto) { options.onGoto(element); } else { _this._gotoReference(element); } } 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 _this._widget.setMetaTitle(options.getMetaTitle(_this._model)); // 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); } } return undefined; }); }, function (error) { _this._notificationService.error(error); }); }; ReferencesController.prototype.goToNextOrPreviousReference = function (fwd) { return __awaiter(this, void 0, void 0, function () { var currentPosition, source, target, editorFocus; 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(); 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(); } return [2 /*return*/]; } }); }); }; ReferencesController.prototype.closeWidget = function () { if (this._widget) { lifecycle_1.dispose(this._widget); this._widget = null; } this._referenceSearchVisible.reset(); this._disposables = lifecycle_1.dispose(this._disposables); if (this._model) { lifecycle_1.dispose(this._model); this._model = null; } 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) { _this._ignoreModelChangeEvent = false; if (!openedEditor || openedEditor !== _this._editor) { // TODO@Alex TODO@Joh // when opening the current reference we might end up // in a different editor instance. that means we also have // a different instance of this reference search controller // and cannot hold onto the widget (which likely doesn't // exist). Instead of bailing out we should find the // 'sister' action and pass our current model on to it. _this.closeWidget(); return; } if (_this._widget) { _this._widget.show(range); _this._widget.focus(); } }, 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; }); /*--------------------------------------------------------------------------------------------- * 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/goToDefinition/goToDefinitionCommands*/], __M([0/*require*/,1/*exports*/,47/*vs/base/browser/ui/aria/aria*/,15/*vs/base/common/async*/,36/*vs/base/common/keyCodes*/,17/*vs/base/common/platform*/,11/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/editorContextKeys*/,16/*vs/editor/common/modes*/,128/*vs/editor/contrib/message/messageController*/,105/*vs/editor/contrib/referenceSearch/peekViewWidget*/,143/*vs/editor/contrib/referenceSearch/referencesController*/,90/*vs/editor/contrib/referenceSearch/referencesModel*/,328/*vs/nls!vs/editor/contrib/goToDefinition/goToDefinitionCommands*/,58/*vs/platform/actions/common/actions*/,18/*vs/platform/contextkey/common/contextkey*/,35/*vs/platform/notification/common/notification*/,92/*vs/platform/progress/common/progress*/,170/*vs/editor/contrib/goToDefinition/goToDefinition*/,27/*vs/platform/commands/common/commands*/,64/*vs/editor/browser/core/editorState*/]), function (require, exports, aria_1, async_1, keyCodes_1, platform, editorExtensions_1, codeEditorService_1, range_1, editorContextKeys_1, modes_1, messageController_1, peekViewWidget_1, referencesController_1, referencesModel_1, nls, actions_1, contextkey_1, notification_1, progress_1, goToDefinition_1, commands_1, editorState_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DefinitionActionConfig = /** @class */ (function () { function DefinitionActionConfig(openToSide, openInPeek, filterCurrent, showMessage) { if (openToSide === void 0) { openToSide = false; } if (openInPeek === void 0) { openInPeek = false; } if (filterCurrent === void 0) { filterCurrent = true; } if (showMessage === void 0) { showMessage = true; } this.openToSide = openToSide; this.openInPeek = openInPeek; this.filterCurrent = filterCurrent; this.showMessage = showMessage; // } return DefinitionActionConfig; }()); exports.DefinitionActionConfig = DefinitionActionConfig; var DefinitionAction = /** @class */ (function (_super) { __extends(DefinitionAction, _super); function DefinitionAction(configuration, opts) { var _this = _super.call(this, opts) || this; _this._configuration = configuration; return _this; } DefinitionAction.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.IProgressService); var model = editor.getModel(); var pos = editor.getPosition(); var cts = new editorState_1.EditorStateCancellationTokenSource(editor, 1 /* Value */ | 4 /* Position */); var definitionPromise = this._getTargetLocationForPosition(model, pos, cts.token).then(function (references) { return __awaiter(_this, void 0, void 0, function () { var idxOfCurrent, result, _i, references_1, reference, newLen, info, current; return __generator(this, function (_a) { if (cts.token.isCancellationRequested || model.isDisposed() || editor.getModel() !== model) { // new model, no more model return [2 /*return*/]; } idxOfCurrent = -1; result = []; for (_i = 0, references_1 = references; _i < references_1.length; _i++) { reference = references_1[_i]; if (!reference || !reference.range) { continue; } newLen = result.push(reference); if (this._configuration.filterCurrent && reference.uri.toString() === model.uri.toString() && range_1.Range.containsPosition(reference.range, pos) && idxOfCurrent === -1) { idxOfCurrent = newLen - 1; } } if (result.length === 0) { // no result -> show message if (this._configuration.showMessage) { info = model.getWordAtPosition(pos); messageController_1.MessageController.get(editor).showMessage(this._getNoResultFoundMessage(info), pos); } } else if (result.length === 1 && idxOfCurrent !== -1) { current = result[0]; return [2 /*return*/, this._openReference(editor, editorService, current, false).then(function () { return undefined; })]; } else { // handle multile results return [2 /*return*/, this._onResult(editorService, editor, new referencesModel_1.ReferencesModel(result))]; } return [2 /*return*/]; }); }); }, function (err) { // report an error notificationService.error(err); }).finally(function () { cts.dispose(); }); progressService.showWhile(definitionPromise, 250); return definitionPromise; }; DefinitionAction.prototype._getTargetLocationForPosition = function (model, position, token) { return goToDefinition_1.getDefinitionsAtPosition(model, position, token); }; DefinitionAction.prototype._getNoResultFoundMessage = function (info) { return info && info.word ? nls.localize(0, null, info.word) : nls.localize(1, null); }; DefinitionAction.prototype._getMetaTitle = function (model) { return model.references.length > 1 ? nls.localize(2, null, model.references.length) : ''; }; DefinitionAction.prototype._onResult = function (editorService, editor, model) { return __awaiter(this, void 0, void 0, function () { var msg, gotoLocation, next, targetEditor; return __generator(this, function (_a) { switch (_a.label) { case 0: msg = model.getAriaMessage(); aria_1.alert(msg); gotoLocation = editor.getConfiguration().contribInfo.gotoLocation; if (!(this._configuration.openInPeek || (gotoLocation.multiple === 'peek' && model.references.length > 1))) return [3 /*break*/, 1]; this._openInPeek(editorService, editor, model); return [3 /*break*/, 3]; case 1: if (!editor.hasModel()) return [3 /*break*/, 3]; next = model.firstReference(); if (!next) { return [2 /*return*/]; } return [4 /*yield*/, this._openReference(editor, editorService, next, this._configuration.openToSide)]; case 2: targetEditor = _a.sent(); if (targetEditor && model.references.length > 1 && gotoLocation.multiple === 'gotoAndPeek') { this._openInPeek(editorService, targetEditor, model); } else { model.dispose(); } _a.label = 3; case 3: return [2 /*return*/]; } }); }); }; DefinitionAction.prototype._openReference = function (editor, editorService, reference, sideBySide) { // range is the target-selection-range when we have one // and the the fallback is the 'full' range var range = undefined; if (modes_1.isLocationLink(reference)) { range = reference.targetSelectionRange; } if (!range) { range = reference.range; } return editorService.openCodeEditor({ resource: reference.uri, options: { selection: range_1.Range.collapseToStart(range), revealIfOpened: true, revealInCenterIfOutsideViewport: true } }, editor, sideBySide); }; DefinitionAction.prototype._openInPeek = function (editorService, target, model) { var _this = this; var controller = referencesController_1.ReferencesController.get(target); if (controller && target.hasModel()) { controller.toggleWidget(target.getSelection(), async_1.createCancelablePromise(function (_) { return Promise.resolve(model); }), { getMetaTitle: function (model) { return _this._getMetaTitle(model); }, onGoto: function (reference) { controller.closeWidget(); return _this._openReference(target, editorService, reference, false); } }); } else { model.dispose(); } }; return DefinitionAction; }(editorExtensions_1.EditorAction)); exports.DefinitionAction = DefinitionAction; var goToDefinitionKb = platform.isWeb ? 2048 /* CtrlCmd */ | 70 /* F12 */ : 70 /* F12 */; var GoToDefinitionAction = /** @class */ (function (_super) { __extends(GoToDefinitionAction, _super); function GoToDefinitionAction() { var _this = _super.call(this, new DefinitionActionConfig(), { id: GoToDefinitionAction.id, label: nls.localize(3, 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 */ }, menuOpts: { group: 'navigation', order: 1.1 } }) || this; commands_1.CommandsRegistry.registerCommandAlias('editor.action.goToDeclaration', GoToDefinitionAction.id); return _this; } GoToDefinitionAction.id = 'editor.action.revealDefinition'; return GoToDefinitionAction; }(DefinitionAction)); exports.GoToDefinitionAction = GoToDefinitionAction; var OpenDefinitionToSideAction = /** @class */ (function (_super) { __extends(OpenDefinitionToSideAction, _super); function OpenDefinitionToSideAction() { var _this = _super.call(this, new DefinitionActionConfig(true), { id: OpenDefinitionToSideAction.id, label: nls.localize(4, 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; } OpenDefinitionToSideAction.id = 'editor.action.revealDefinitionAside'; return OpenDefinitionToSideAction; }(DefinitionAction)); exports.OpenDefinitionToSideAction = OpenDefinitionToSideAction; var PeekDefinitionAction = /** @class */ (function (_super) { __extends(PeekDefinitionAction, _super); function PeekDefinitionAction() { var _this = _super.call(this, new DefinitionActionConfig(undefined, true, false), { id: PeekDefinitionAction.id, label: nls.localize(5, null), alias: 'Peek Definition', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDefinitionProvider, peekViewWidget_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 */ }, menuOpts: { group: 'navigation', order: 1.2 } }) || this; commands_1.CommandsRegistry.registerCommandAlias('editor.action.previewDeclaration', PeekDefinitionAction.id); return _this; } PeekDefinitionAction.id = 'editor.action.peekDefinition'; return PeekDefinitionAction; }(DefinitionAction)); exports.PeekDefinitionAction = PeekDefinitionAction; var DeclarationAction = /** @class */ (function (_super) { __extends(DeclarationAction, _super); function DeclarationAction() { return _super !== null && _super.apply(this, arguments) || this; } DeclarationAction.prototype._getTargetLocationForPosition = function (model, position, token) { return goToDefinition_1.getDeclarationsAtPosition(model, position, token); }; DeclarationAction.prototype._getNoResultFoundMessage = function (info) { return info && info.word ? nls.localize(6, null, info.word) : nls.localize(7, null); }; DeclarationAction.prototype._getMetaTitle = function (model) { return model.references.length > 1 ? nls.localize(8, null, model.references.length) : ''; }; return DeclarationAction; }(DefinitionAction)); exports.DeclarationAction = DeclarationAction; var GoToDeclarationAction = /** @class */ (function (_super) { __extends(GoToDeclarationAction, _super); function GoToDeclarationAction() { return _super.call(this, new DefinitionActionConfig(), { id: GoToDeclarationAction.id, label: nls.localize(9, null), alias: 'Go to Declaration', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDeclarationProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), menuOpts: { group: 'navigation', order: 1.3 } }) || this; } GoToDeclarationAction.prototype._getNoResultFoundMessage = function (info) { return info && info.word ? nls.localize(10, null, info.word) : nls.localize(11, null); }; GoToDeclarationAction.prototype._getMetaTitle = function (model) { return model.references.length > 1 ? nls.localize(12, null, model.references.length) : ''; }; GoToDeclarationAction.id = 'editor.action.revealDeclaration'; return GoToDeclarationAction; }(DeclarationAction)); exports.GoToDeclarationAction = GoToDeclarationAction; var PeekDeclarationAction = /** @class */ (function (_super) { __extends(PeekDeclarationAction, _super); function PeekDeclarationAction() { return _super.call(this, new DefinitionActionConfig(undefined, true, false), { id: 'editor.action.peekDeclaration', label: nls.localize(13, null), alias: 'Peek Declaration', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDeclarationProvider, peekViewWidget_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), menuOpts: { group: 'navigation', order: 1.31 } }) || this; } return PeekDeclarationAction; }(DeclarationAction)); exports.PeekDeclarationAction = PeekDeclarationAction; var ImplementationAction = /** @class */ (function (_super) { __extends(ImplementationAction, _super); function ImplementationAction() { return _super !== null && _super.apply(this, arguments) || this; } ImplementationAction.prototype._getTargetLocationForPosition = function (model, position, token) { return goToDefinition_1.getImplementationsAtPosition(model, position, token); }; ImplementationAction.prototype._getNoResultFoundMessage = function (info) { return info && info.word ? nls.localize(14, null, info.word) : nls.localize(15, null); }; ImplementationAction.prototype._getMetaTitle = function (model) { return model.references.length > 1 ? nls.localize(16, null, model.references.length) : ''; }; return ImplementationAction; }(DefinitionAction)); exports.ImplementationAction = ImplementationAction; var GoToImplementationAction = /** @class */ (function (_super) { __extends(GoToImplementationAction, _super); function GoToImplementationAction() { return _super.call(this, new DefinitionActionConfig(), { id: GoToImplementationAction.ID, label: nls.localize(17, null), alias: 'Go to Implementation', 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 */ } }) || this; } GoToImplementationAction.ID = 'editor.action.goToImplementation'; return GoToImplementationAction; }(ImplementationAction)); exports.GoToImplementationAction = GoToImplementationAction; var PeekImplementationAction = /** @class */ (function (_super) { __extends(PeekImplementationAction, _super); function PeekImplementationAction() { return _super.call(this, new DefinitionActionConfig(false, true, false), { id: PeekImplementationAction.ID, label: nls.localize(18, null), alias: 'Peek Implementation', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasImplementationProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 70 /* F12 */, weight: 100 /* EditorContrib */ } }) || this; } PeekImplementationAction.ID = 'editor.action.peekImplementation'; return PeekImplementationAction; }(ImplementationAction)); exports.PeekImplementationAction = PeekImplementationAction; var TypeDefinitionAction = /** @class */ (function (_super) { __extends(TypeDefinitionAction, _super); function TypeDefinitionAction() { return _super !== null && _super.apply(this, arguments) || this; } TypeDefinitionAction.prototype._getTargetLocationForPosition = function (model, position, token) { return goToDefinition_1.getTypeDefinitionsAtPosition(model, position, token); }; TypeDefinitionAction.prototype._getNoResultFoundMessage = function (info) { return info && info.word ? nls.localize(19, null, info.word) : nls.localize(20, null); }; TypeDefinitionAction.prototype._getMetaTitle = function (model) { return model.references.length > 1 ? nls.localize(21, null, model.references.length) : ''; }; return TypeDefinitionAction; }(DefinitionAction)); exports.TypeDefinitionAction = TypeDefinitionAction; var GoToTypeDefinitionAction = /** @class */ (function (_super) { __extends(GoToTypeDefinitionAction, _super); function GoToTypeDefinitionAction() { return _super.call(this, new DefinitionActionConfig(), { id: GoToTypeDefinitionAction.ID, label: nls.localize(22, 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 */ }, menuOpts: { group: 'navigation', order: 1.4 } }) || this; } GoToTypeDefinitionAction.ID = 'editor.action.goToTypeDefinition'; return GoToTypeDefinitionAction; }(TypeDefinitionAction)); exports.GoToTypeDefinitionAction = GoToTypeDefinitionAction; var PeekTypeDefinitionAction = /** @class */ (function (_super) { __extends(PeekTypeDefinitionAction, _super); function PeekTypeDefinitionAction() { return _super.call(this, new DefinitionActionConfig(false, true, false), { id: PeekTypeDefinitionAction.ID, label: nls.localize(23, null), alias: 'Peek 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 */ } }) || this; } PeekTypeDefinitionAction.ID = 'editor.action.peekTypeDefinition'; return PeekTypeDefinitionAction; }(TypeDefinitionAction)); exports.PeekTypeDefinitionAction = PeekTypeDefinitionAction; editorExtensions_1.registerEditorAction(GoToDefinitionAction); editorExtensions_1.registerEditorAction(OpenDefinitionToSideAction); editorExtensions_1.registerEditorAction(PeekDefinitionAction); editorExtensions_1.registerEditorAction(GoToDeclarationAction); editorExtensions_1.registerEditorAction(PeekDeclarationAction); editorExtensions_1.registerEditorAction(GoToImplementationAction); editorExtensions_1.registerEditorAction(PeekImplementationAction); editorExtensions_1.registerEditorAction(GoToTypeDefinitionAction); editorExtensions_1.registerEditorAction(PeekTypeDefinitionAction); // Go to menu actions_1.MenuRegistry.appendMenuItem(16 /* MenubarGoMenu */, { group: '4_symbol_nav', command: { id: 'editor.action.goToDeclaration', title: nls.localize(24, null) }, order: 2 }); actions_1.MenuRegistry.appendMenuItem(16 /* MenubarGoMenu */, { group: '4_symbol_nav', command: { id: 'editor.action.goToTypeDefinition', title: nls.localize(25, null) }, order: 3 }); actions_1.MenuRegistry.appendMenuItem(16 /* MenubarGoMenu */, { group: '4_symbol_nav', command: { id: 'editor.action.goToImplementation', title: nls.localize(26, null) }, order: 4 }); }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ define(__m[568/*vs/editor/contrib/goToDefinition/goToDefinitionMouse*/], __M([0/*require*/,1/*exports*/,329/*vs/nls!vs/editor/contrib/goToDefinition/goToDefinitionMouse*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,87/*vs/base/common/htmlContent*/,67/*vs/editor/common/services/modeService*/,3/*vs/editor/common/core/range*/,16/*vs/editor/common/modes*/,11/*vs/editor/browser/editorExtensions*/,170/*vs/editor/contrib/goToDefinition/goToDefinition*/,2/*vs/base/common/lifecycle*/,80/*vs/editor/common/services/resolverService*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,64/*vs/editor/browser/core/editorState*/,224/*vs/editor/contrib/goToDefinition/goToDefinitionCommands*/,205/*vs/editor/contrib/goToDefinition/clickLinkGesture*/,12/*vs/editor/common/core/position*/,20/*vs/base/common/types*/,190/*vs/css!vs/editor/contrib/goToDefinition/goToDefinitionMouse*/]), function (require, exports, nls, async_1, errors_1, htmlContent_1, modeService_1, range_1, modes_1, editorExtensions_1, goToDefinition_1, lifecycle_1, resolverService_1, themeService_1, colorRegistry_1, editorState_1, goToDefinitionCommands_1, clickLinkGesture_1, position_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var GotoDefinitionWithMouseEditorContribution = /** @class */ (function () { function GotoDefinitionWithMouseEditorContribution(editor, textModelResolverService, modeService) { var _this = this; this.textModelResolverService = textModelResolverService; this.modeService = modeService; this.toUnhook = []; this.decorations = []; this.editor = editor; this.previousPromise = null; var linkGesture = new clickLinkGesture_1.ClickLinkGesture(editor); this.toUnhook.push(linkGesture); this.toUnhook.push(linkGesture.onMouseMoveOrRelevantKeyDown(function (_a) { var mouseEvent = _a[0], keyboardEvent = _a[1]; _this.startFindDefinition(mouseEvent, types_1.withNullAsUndefined(keyboardEvent)); })); this.toUnhook.push(linkGesture.onExecute(function (mouseEvent) { if (_this.isEnabled(mouseEvent)) { _this.gotoDefinition(mouseEvent.target, mouseEvent.hasSideBySideModifier).then(function () { _this.removeDecorations(); }, function (error) { _this.removeDecorations(); errors_1.onUnexpectedError(error); }); } })); this.toUnhook.push(linkGesture.onCancel(function () { _this.removeDecorations(); _this.currentWordUnderMouse = null; })); } GotoDefinitionWithMouseEditorContribution.prototype.startFindDefinition = function (mouseEvent, withKey) { var _this = this; // check if we are active and on a content widget if (mouseEvent.target.type === 9 /* CONTENT_WIDGET */ && this.decorations.length > 0) { return; } if (!this.editor.hasModel() || !this.isEnabled(mouseEvent, withKey)) { this.currentWordUnderMouse = null; this.removeDecorations(); return; } // Find word at mouse position var word = mouseEvent.target.position ? this.editor.getModel().getWordAtPosition(mouseEvent.target.position) : null; if (!word) { this.currentWordUnderMouse = null; this.removeDecorations(); return; } var position = mouseEvent.target.position; // Return early if word at position is still the same if (this.currentWordUnderMouse && this.currentWordUnderMouse.startColumn === word.startColumn && this.currentWordUnderMouse.endColumn === word.endColumn && this.currentWordUnderMouse.word === word.word) { return; } this.currentWordUnderMouse = 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(mouseEvent.target, token); }); this.previousPromise.then(function (results) { if (!results || !results.length || !state.validate(_this.editor)) { _this.removeDecorations(); 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); 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.fsPath); _this.addDecoration(wordRange, new htmlContent_1.MarkdownString().appendCodeblock(modeId ? modeId : '', previewValue)); ref.dispose(); }); } }).then(undefined, errors_1.onUnexpectedError); }; GotoDefinitionWithMouseEditorContribution.prototype.getPreviewValue = function (textEditorModel, startLineNumber) { var rangeToUse = this.getPreviewRangeBasedOnBrackets(textEditorModel, startLineNumber); var numberOfLinesInRange = rangeToUse.endLineNumber - rangeToUse.startLineNumber; if (numberOfLinesInRange >= GotoDefinitionWithMouseEditorContribution.MAX_SOURCE_PREVIEW_LINES) { rangeToUse = this.getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber); } var previewValue = this.stripIndentationFromPreviewRange(textEditorModel, startLineNumber, rangeToUse); return previewValue; }; GotoDefinitionWithMouseEditorContribution.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; }; GotoDefinitionWithMouseEditorContribution.prototype.getPreviewRangeBasedOnIndentation = function (textEditorModel, startLineNumber) { var startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber); var maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionWithMouseEditorContribution.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); }; GotoDefinitionWithMouseEditorContribution.prototype.getPreviewRangeBasedOnBrackets = function (textEditorModel, startLineNumber) { var maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionWithMouseEditorContribution.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 === currentBracket.open && 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); }; GotoDefinitionWithMouseEditorContribution.prototype.addDecoration = function (range, hoverMessage) { var newDecorations = { range: range, options: { inlineClassName: 'goto-definition-link', hoverMessage: hoverMessage } }; this.decorations = this.editor.deltaDecorations(this.decorations, [newDecorations]); }; GotoDefinitionWithMouseEditorContribution.prototype.removeDecorations = function () { if (this.decorations.length > 0) { this.decorations = this.editor.deltaDecorations(this.decorations, []); } }; GotoDefinitionWithMouseEditorContribution.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()); }; GotoDefinitionWithMouseEditorContribution.prototype.findDefinition = function (target, token) { var model = this.editor.getModel(); if (!model) { return Promise.resolve(null); } return goToDefinition_1.getDefinitionsAtPosition(model, target.position, token); }; GotoDefinitionWithMouseEditorContribution.prototype.gotoDefinition = function (target, sideBySide) { var _this = this; this.editor.setPosition(target.position); var action = new goToDefinitionCommands_1.DefinitionAction(new goToDefinitionCommands_1.DefinitionActionConfig(sideBySide, false, true, false), { alias: '', label: '', id: '', precondition: null }); return this.editor.invokeWithinContext(function (accessor) { return action.run(accessor, _this.editor); }); }; GotoDefinitionWithMouseEditorContribution.prototype.getId = function () { return GotoDefinitionWithMouseEditorContribution.ID; }; GotoDefinitionWithMouseEditorContribution.prototype.dispose = function () { this.toUnhook = lifecycle_1.dispose(this.toUnhook); }; GotoDefinitionWithMouseEditorContribution.ID = 'editor.contrib.gotodefinitionwithmouse'; GotoDefinitionWithMouseEditorContribution.MAX_SOURCE_PREVIEW_LINES = 8; GotoDefinitionWithMouseEditorContribution = __decorate([ __param(1, resolverService_1.ITextModelService), __param(2, modeService_1.IModeService) ], GotoDefinitionWithMouseEditorContribution); return GotoDefinitionWithMouseEditorContribution; }()); editorExtensions_1.registerEditorContribution(GotoDefinitionWithMouseEditorContribution); 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[569/*vs/editor/contrib/referenceSearch/referenceSearch*/], __M([0/*require*/,1/*exports*/,342/*vs/nls!vs/editor/contrib/referenceSearch/referenceSearch*/,18/*vs/platform/contextkey/common/contextkey*/,95/*vs/platform/keybinding/common/keybindingsRegistry*/,12/*vs/editor/common/core/position*/,11/*vs/editor/browser/editorExtensions*/,16/*vs/editor/common/modes*/,3/*vs/editor/common/core/range*/,105/*vs/editor/contrib/referenceSearch/peekViewWidget*/,143/*vs/editor/contrib/referenceSearch/referencesController*/,90/*vs/editor/contrib/referenceSearch/referencesModel*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/,21/*vs/editor/common/editorContextKeys*/,118/*vs/editor/browser/widget/embeddedCodeEditorWidget*/,106/*vs/editor/browser/editorBrowser*/,138/*vs/platform/list/browser/listService*/,141/*vs/editor/contrib/referenceSearch/referencesWidget*/,27/*vs/platform/commands/common/commands*/,25/*vs/base/common/uri*/,32/*vs/editor/browser/services/codeEditorService*/,24/*vs/base/common/cancellation*/]), function (require, exports, nls, contextkey_1, keybindingsRegistry_1, position_1, editorExtensions_1, modes_1, range_1, peekViewWidget_1, referencesController_1, referencesModel_1, async_1, errors_1, editorContextKeys_1, embeddedCodeEditorWidget_1, editorBrowser_1, listService_1, referencesWidget_1, commands_1, uri_1, codeEditorService_1, cancellation_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultReferenceSearchOptions = { getMetaTitle: function (model) { return model.references.length > 1 ? nls.localize(0, null, model.references.length) : ''; } }; var ReferenceController = /** @class */ (function () { function ReferenceController(editor, contextKeyService) { if (editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget) { peekViewWidget_1.PeekContext.inPeekEditor.bindTo(contextKeyService); } } ReferenceController.prototype.dispose = function () { }; ReferenceController.prototype.getId = function () { return ReferenceController.ID; }; ReferenceController.ID = 'editor.contrib.referenceController'; ReferenceController = __decorate([ __param(1, contextkey_1.IContextKeyService) ], ReferenceController); return ReferenceController; }()); exports.ReferenceController = ReferenceController; var ReferenceAction = /** @class */ (function (_super) { __extends(ReferenceAction, _super); function ReferenceAction() { return _super.call(this, { id: 'editor.action.referenceSearch.trigger', label: nls.localize(1, null), alias: 'Find All References', precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasReferenceProvider, peekViewWidget_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus, primary: 1024 /* Shift */ | 70 /* F12 */, weight: 100 /* EditorContrib */ }, menuOpts: { group: 'navigation', order: 1.5 } }) || this; } ReferenceAction.prototype.run = function (_accessor, editor) { var controller = referencesController_1.ReferencesController.get(editor); if (!controller) { return; } if (editor.hasModel()) { var range_2 = editor.getSelection(); var model_1 = editor.getModel(); var references = async_1.createCancelablePromise(function (token) { return provideReferences(model_1, range_2.getStartPosition(), token).then(function (references) { return new referencesModel_1.ReferencesModel(references); }); }); controller.toggleWidget(range_2, references, exports.defaultReferenceSearchOptions); } }; return ReferenceAction; }(editorExtensions_1.EditorAction)); exports.ReferenceAction = ReferenceAction; editorExtensions_1.registerEditorContribution(ReferenceController); editorExtensions_1.registerEditorAction(ReferenceAction); var findReferencesCommand = function (accessor, resource, position) { if (!(resource instanceof uri_1.URI)) { throw new Error('illegal argument, uri'); } if (!position) { throw new Error('illegal argument, 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 provideReferences(control.getModel(), position_1.Position.lift(position), token).then(function (references) { return new referencesModel_1.ReferencesModel(references); }); }); var range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column); return Promise.resolve(controller.toggleWidget(range, references, exports.defaultReferenceSearchOptions)); }); }; var showReferencesCommand = function (accessor, resource, position, references) { if (!(resource instanceof uri_1.URI)) { throw new Error('illegal argument, uri expected'); } if (!references) { throw new Error('missing references'); } var codeEditorService = accessor.get(codeEditorService_1.ICodeEditorService); return codeEditorService.openCodeEditor({ resource: resource }, codeEditorService.getFocusedCodeEditor()).then(function (control) { if (!editorBrowser_1.isCodeEditor(control)) { return undefined; } var controller = referencesController_1.ReferencesController.get(control); if (!controller) { return undefined; } return controller.toggleWidget(new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column), async_1.createCancelablePromise(function (_) { return Promise.resolve(new referencesModel_1.ReferencesModel(references)); }), exports.defaultReferenceSearchOptions); }); }; // register commands commands_1.CommandsRegistry.registerCommand({ id: 'editor.action.findReferences', handler: findReferencesCommand }); commands_1.CommandsRegistry.registerCommand({ id: 'editor.action.showReferences', handler: showReferencesCommand, description: { description: 'Show references at a position in a file', args: [ { name: 'uri', description: 'The text document in which to show references', constraint: uri_1.URI }, { name: 'position', description: 'The position at which to show', constraint: position_1.Position.isIPosition }, { name: 'locations', description: 'An array of locations.', constraint: Array }, ] } }); function closeActiveReferenceSearch(accessor, args) { withController(accessor, function (controller) { return controller.closeWidget(); }); } function openReferenceToSide(accessor, args) { var listService = accessor.get(listService_1.IListService); var focus = listService.lastFocusedList && listService.lastFocusedList.getFocus(); if (focus instanceof referencesModel_1.OneReference) { withController(accessor, function (controller) { return controller.openReference(focus, true); }); } } function withController(accessor, fn) { var outerEditor = peekViewWidget_1.getOuterEditor(accessor); if (!outerEditor) { return; } var controller = referencesController_1.ReferencesController.get(outerEditor); if (!controller) { return; } fn(controller); } keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'goToNextReference', weight: 200 /* WorkbenchContrib */ + 50, primary: 62 /* F4 */, when: referencesController_1.ctxReferenceSearchVisible, handler: function (accessor) { withController(accessor, function (controller) { controller.goToNextOrPreviousReference(true); }); } }); keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'goToNextReferenceFromEmbeddedEditor', weight: 100 /* EditorContrib */ + 50, primary: 62 /* F4 */, when: peekViewWidget_1.PeekContext.inPeekEditor, handler: function (accessor) { withController(accessor, function (controller) { controller.goToNextOrPreviousReference(true); }); } }); keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'goToPreviousReference', weight: 200 /* WorkbenchContrib */ + 50, primary: 1024 /* Shift */ | 62 /* F4 */, when: referencesController_1.ctxReferenceSearchVisible, handler: function (accessor) { withController(accessor, function (controller) { controller.goToNextOrPreviousReference(false); }); } }); keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'goToPreviousReferenceFromEmbeddedEditor', weight: 100 /* EditorContrib */ + 50, primary: 1024 /* Shift */ | 62 /* F4 */, when: peekViewWidget_1.PeekContext.inPeekEditor, handler: function (accessor) { withController(accessor, function (controller) { controller.goToNextOrPreviousReference(false); }); } }); keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'closeReferenceSearch', weight: 200 /* WorkbenchContrib */ + 50, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */], when: contextkey_1.ContextKeyExpr.and(referencesController_1.ctxReferenceSearchVisible, contextkey_1.ContextKeyExpr.not('config.editor.stablePeek')), handler: closeActiveReferenceSearch }); keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'closeReferenceSearchEditor', weight: 100 /* EditorContrib */ - 101, primary: 9 /* Escape */, secondary: [1024 /* Shift */ | 9 /* Escape */], when: contextkey_1.ContextKeyExpr.and(peekViewWidget_1.PeekContext.inPeekEditor, contextkey_1.ContextKeyExpr.not('config.editor.stablePeek')), handler: closeActiveReferenceSearch }); 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(referencesController_1.ctxReferenceSearchVisible, referencesWidget_1.ctxReferenceWidgetSearchTreeFocused), handler: openReferenceToSide }); function provideReferences(model, position, token) { // collect references from all providers var promises = modes_1.ReferenceProviderRegistry.ordered(model).map(function (provider) { return Promise.resolve(provider.provideReferences(model, position, { includeDeclaration: true }, token)).then(function (result) { if (Array.isArray(result)) { return result; } return undefined; }, function (err) { errors_1.onUnexpectedExternalError(err); }); }); return Promise.all(promises).then(function (references) { var result = []; for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { var ref = references_1[_i]; if (ref) { result.push.apply(result, ref); } } return result; }); } exports.provideReferences = provideReferences; editorExtensions_1.registerDefaultLanguageCommand('_executeReferenceProvider', function (model, position) { return provideReferences(model, position, 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[570/*vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch*/], __M([0/*require*/,1/*exports*/,11/*vs/editor/browser/editorExtensions*/,32/*vs/editor/browser/services/codeEditorService*/,143/*vs/editor/contrib/referenceSearch/referencesController*/,41/*vs/platform/configuration/common/configuration*/,18/*vs/platform/contextkey/common/contextkey*/,13/*vs/platform/instantiation/common/instantiation*/,35/*vs/platform/notification/common/notification*/,68/*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(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[150/*vs/platform/workspace/common/workspace*/], __M([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/,54/*vs/base/common/resources*/,13/*vs/platform/instantiation/common/instantiation*/,46/*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.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. *--------------------------------------------------------------------------------------------*/ define(__m[153/*vs/editor/standalone/browser/simpleServices*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,7/*vs/base/browser/dom*/,52/*vs/base/browser/keyboardEvent*/,4/*vs/base/common/event*/,36/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,123/*vs/base/common/severity*/,25/*vs/base/common/uri*/,106/*vs/editor/browser/editorBrowser*/,112/*vs/editor/common/config/commonEditorConfig*/,55/*vs/editor/common/core/editOperation*/,12/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,16/*vs/editor/common/modes*/,27/*vs/platform/commands/common/commands*/,41/*vs/platform/configuration/common/configuration*/,454/*vs/platform/configuration/common/configurationModels*/,422/*vs/platform/keybinding/common/abstractKeybindingService*/,167/*vs/platform/keybinding/common/keybindingResolver*/,95/*vs/platform/keybinding/common/keybindingsRegistry*/,426/*vs/platform/keybinding/common/resolvedKeybindingItem*/,427/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/,35/*vs/platform/notification/common/notification*/,150/*vs/platform/workspace/common/workspace*/,50/*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() { } SimpleEditorModelResolverService.prototype.setEditor = function (editor) { this.editor = editor; }; SimpleEditorModelResolverService.prototype.createModelReference = function (resource) { var _this = this; var 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 = editor.getModel(); if (model && model.uri.toString() !== resource.toString()) { return null; } return model; }; return SimpleEditorModelResolverService; }()); exports.SimpleEditorModelResolverService = SimpleEditorModelResolverService; var SimpleProgressService = /** @class */ (function () { function SimpleProgressService() { } SimpleProgressService.prototype.showWhile = function (promise, delay) { return Promise.resolve(undefined); }; return SimpleProgressService; }()); exports.SimpleProgressService = SimpleProgressService; 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.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._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 }); var result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler].concat(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(); } })); return _this; } StandaloneKeybindingService.prototype.addDynamicKeybinding = function (commandId, _keybinding, handler, when) { var _this = this; var keybinding = keyCodes_1.createKeybinding(_keybinding, platform_1.OS); if (!keybinding) { throw new Error("Invalid keybinding"); } var toDispose = []; this._dynamicKeybindings.push({ keybinding: keybinding, command: commandId, when: when, weight1: 1000, weight2: 0 }); toDispose.push(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.push(commandService.addCommand({ id: commandId, handler: handler })); } else { throw new Error('Unknown command service!'); } this.updateResolver({ source: 1 /* Default */ }); return lifecycle_1.combinedDisposable(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 ? item.when.normalize() : 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(null, 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._onDidChangeConfigurationEmitter = new event_1.Emitter(); this.configurationService.onDidChangeConfiguration(function (e) { _this._onDidChangeConfigurationEmitter.fire(e); }); } 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) { var filesConfiguration = this.configurationService.getValue('files'); if (filesConfiguration && filesConfiguration.eol) { if (filesConfiguration.eol !== 'auto') { return filesConfiguration.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); }; 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.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.isResourceTextEdit(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.concat(edit.edits)); } } var totalEdits = 0; var totalFiles = 0; edits.forEach(function (edits, model) { model.applyEdits(edits.map(function (edit) { return editOperation_1.EditOperation.replaceMove(range_1.Range.lift(edit.range), edit.text); })); 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. *--------------------------------------------------------------------------------------------*/ define(__m[573/*vs/editor/standalone/browser/standaloneCodeEditor*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/browser*/,47/*vs/base/browser/ui/aria/aria*/,2/*vs/base/common/lifecycle*/,32/*vs/editor/browser/services/codeEditorService*/,102/*vs/editor/browser/widget/codeEditorWidget*/,204/*vs/editor/browser/widget/diffEditorWidget*/,181/*vs/editor/common/editorAction*/,63/*vs/editor/common/services/editorWorkerService*/,153/*vs/editor/standalone/browser/simpleServices*/,82/*vs/editor/standalone/common/standaloneThemeService*/,58/*vs/platform/actions/common/actions*/,27/*vs/platform/commands/common/commands*/,41/*vs/platform/configuration/common/configuration*/,18/*vs/platform/contextkey/common/contextkey*/,59/*vs/platform/contextview/browser/contextView*/,13/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,35/*vs/platform/notification/common/notification*/,14/*vs/platform/theme/common/themeService*/,75/*vs/platform/accessibility/common/accessibility*/,50/*vs/editor/common/standaloneStrings*/]), 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) { "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; } // 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 () { return Promise.resolve(_descriptor.run(_this)); }; var toDispose = []; // Generate a unique id to allow the same descriptor.id across multiple editor instances var uniqueId = this.getId() + ':' + id; // Register the command toDispose.push(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.push(actions_1.MenuRegistry.appendMenuItem(7 /* EditorContext */, menuItem)); } // Register the keybindings if (Array.isArray(keybindings)) { toDispose = toDispose.concat(keybindings.map(function (kb) { return _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.push(lifecycle_1.toDisposable(function () { delete _this._actions[id]; })); return lifecycle_1.combinedDisposable(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); 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); 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) { var _this = this; simpleServices_1.applyConfigurationValues(configurationService, options, true); options = options || {}; if (typeof options.theme === 'string') { options.theme = themeService.setTheme(options.theme); } _this = _super.call(this, domElement, options, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService) || this; _this._contextViewService = contextViewService; _this._configurationService = configurationService; _this._register(toDispose); _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) ], 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[192/*vs/editor/standalone/browser/standaloneServices*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,98/*vs/editor/browser/services/bulkEditService*/,32/*vs/editor/browser/services/codeEditorService*/,63/*vs/editor/common/services/editorWorkerService*/,161/*vs/editor/common/services/editorWorkerServiceImpl*/,67/*vs/editor/common/services/modeService*/,451/*vs/editor/common/services/modeServiceImpl*/,42/*vs/editor/common/services/modelService*/,453/*vs/editor/common/services/modelServiceImpl*/,115/*vs/editor/common/services/resourceConfiguration*/,153/*vs/editor/standalone/browser/simpleServices*/,556/*vs/editor/standalone/browser/standaloneCodeServiceImpl*/,558/*vs/editor/standalone/browser/standaloneThemeServiceImpl*/,82/*vs/editor/standalone/common/standaloneThemeService*/,58/*vs/platform/actions/common/actions*/,27/*vs/platform/commands/common/commands*/,41/*vs/platform/configuration/common/configuration*/,455/*vs/platform/contextkey/browser/contextKeyService*/,18/*vs/platform/contextkey/common/contextkey*/,559/*vs/platform/contextview/browser/contextMenuService*/,59/*vs/platform/contextview/browser/contextView*/,430/*vs/platform/contextview/browser/contextViewService*/,419/*vs/platform/dialogs/common/dialogs*/,13/*vs/platform/instantiation/common/instantiation*/,421/*vs/platform/instantiation/common/instantiationService*/,91/*vs/platform/instantiation/common/serviceCollection*/,37/*vs/platform/keybinding/common/keybinding*/,125/*vs/platform/label/common/label*/,138/*vs/platform/list/browser/listService*/,140/*vs/platform/log/common/log*/,435/*vs/platform/markers/common/markerService*/,66/*vs/platform/markers/common/markers*/,35/*vs/platform/notification/common/notification*/,92/*vs/platform/progress/common/progress*/,68/*vs/platform/storage/common/storage*/,97/*vs/platform/telemetry/common/telemetry*/,14/*vs/platform/theme/common/themeService*/,150/*vs/platform/workspace/common/workspace*/,417/*vs/platform/actions/common/menuService*/,211/*vs/editor/common/services/markersDecorationService*/,527/*vs/editor/common/services/markerDecorationsServiceImpl*/,184/*vs/editor/contrib/suggest/suggestMemory*/,75/*vs/platform/accessibility/common/accessibility*/,362/*vs/platform/accessibility/common/accessibilityService*/,163/*vs/platform/layout/browser/layoutService*/,188/*vs/editor/contrib/codelens/codeLensCache*/]), function (require, exports, lifecycle_1, bulkEditService_1, codeEditorService_1, editorWorkerService_1, editorWorkerServiceImpl_1, modeService_1, modeServiceImpl_1, modelService_1, modelServiceImpl_1, resourceConfiguration_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, suggestMemory_1, accessibility_1, accessibilityService_1, layoutService_1, codeLensCache_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(); // 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(resourceConfiguration_1.ITextResourceConfigurationService, function () { return new simpleServices_1.SimpleResourceConfigurationService(configurationServiceImpl); }); StaticServices.resourcePropertiesService = define(resourceConfiguration_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.accessibilityService = define(accessibility_1.IAccessibilityService, function () { return new accessibilityService_1.BrowserAccessibilityService(); }); 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.modelService = define(modelService_1.IModelService, function (o) { return new modelServiceImpl_1.ModelServiceImpl(StaticServices.configurationService.get(o), StaticServices.resourcePropertiesService.get(o)); }); StaticServices.markerDecorationsService = define(markersDecorationService_1.IMarkerDecorationsService, function (o) { return new markerDecorationsServiceImpl_1.MarkerDecorationsService(StaticServices.modelService.get(o), StaticServices.markerService.get(o)); }); StaticServices.standaloneThemeService = define(standaloneThemeService_1.IStandaloneThemeService, function () { return new standaloneThemeServiceImpl_1.StandaloneThemeServiceImpl(); }); StaticServices.codeEditorService = define(codeEditorService_1.ICodeEditorService, function (o) { return new standaloneCodeServiceImpl_1.StandaloneCodeEditorServiceImpl(StaticServices.standaloneThemeService.get(o)); }); StaticServices.progressService = define(progress_1.IProgressService, function () { return new simpleServices_1.SimpleProgressService(); }); StaticServices.storageService = define(storage_1.IStorageService, function () { return new storage_1.InMemoryStorageService(); }); StaticServices.logService = define(log_1.ILogService, function () { return new log_1.NullLogService(); }); 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.suggestMemoryService = define(suggestMemory_1.ISuggestMemoryService, function (o) { return new suggestMemory_1.SuggestMemoryService(StaticServices.storageService.get(o), StaticServices.configurationService.get(o)); }); StaticServices.codeLensCacheService = define(codeLensCache_1.ICodeLensCache, function (o) { return new codeLensCache_1.CodeLensCache(StaticServices.storageService.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(listService_1.IListService, function () { return new listService_1.ListService(contextKeyService); }); 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[575/*vs/editor/standalone/browser/standaloneEditor*/], __M([0/*require*/,1/*exports*/,32/*vs/editor/browser/services/codeEditorService*/,410/*vs/editor/browser/services/openerService*/,166/*vs/editor/browser/widget/diffNavigator*/,48/*vs/editor/common/config/editorOptions*/,114/*vs/editor/common/config/fontInfo*/,70/*vs/editor/common/editorCommon*/,45/*vs/editor/common/model*/,16/*vs/editor/common/modes*/,61/*vs/editor/common/modes/nullMode*/,63/*vs/editor/common/services/editorWorkerService*/,80/*vs/editor/common/services/resolverService*/,433/*vs/editor/common/services/webWorker*/,148/*vs/editor/common/standalone/standaloneEnums*/,405/*vs/editor/standalone/browser/colorizer*/,153/*vs/editor/standalone/browser/simpleServices*/,573/*vs/editor/standalone/browser/standaloneCodeEditor*/,192/*vs/editor/standalone/browser/standaloneServices*/,82/*vs/editor/standalone/common/standaloneThemeService*/,27/*vs/platform/commands/common/commands*/,41/*vs/platform/configuration/common/configuration*/,18/*vs/platform/contextkey/common/contextkey*/,59/*vs/platform/contextview/browser/contextView*/,13/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,35/*vs/platform/notification/common/notification*/,56/*vs/platform/opener/common/opener*/,75/*vs/platform/accessibility/common/accessibility*/,60/*vs/editor/browser/config/configuration*/,365/*vs/css!vs/editor/standalone/browser/standalone-tokens*/]), function (require, exports, codeEditorService_1, openerService_1, diffNavigator_1, editorOptions, fontInfo_1, editorCommon, 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) { "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(); 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)); }); } 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 path = uri ? uri.path : null; 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(path, 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 ScrollbarVisibility: standaloneEnums.ScrollbarVisibility, WrappingIndent: standaloneEnums.WrappingIndent, OverviewRulerLane: standaloneEnums.OverviewRulerLane, EndOfLinePreference: standaloneEnums.EndOfLinePreference, DefaultEndOfLine: standaloneEnums.DefaultEndOfLine, EndOfLineSequence: standaloneEnums.EndOfLineSequence, TrackedRangeStickiness: standaloneEnums.TrackedRangeStickiness, CursorChangeReason: standaloneEnums.CursorChangeReason, MouseTargetType: standaloneEnums.MouseTargetType, TextEditorCursorStyle: standaloneEnums.TextEditorCursorStyle, TextEditorCursorBlinkingStyle: standaloneEnums.TextEditorCursorBlinkingStyle, ContentWidgetPositionPreference: standaloneEnums.ContentWidgetPositionPreference, OverlayWidgetPositionPreference: standaloneEnums.OverlayWidgetPositionPreference, RenderMinimap: standaloneEnums.RenderMinimap, ScrollType: standaloneEnums.ScrollType, RenderLineNumbersType: standaloneEnums.RenderLineNumbersType, // classes InternalEditorOptions: editorOptions.InternalEditorOptions, BareFontInfo: fontInfo_1.BareFontInfo, FontInfo: fontInfo_1.FontInfo, TextModelResolvedOptions: model_1.TextModelResolvedOptions, FindMatch: model_1.FindMatch, // vars EditorType: editorCommon.EditorType }; } 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[576/*vs/editor/standalone/browser/standaloneLanguages*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,103/*vs/editor/common/core/token*/,16/*vs/editor/common/modes*/,39/*vs/editor/common/modes/languageConfigurationRegistry*/,93/*vs/editor/common/modes/modesRegistry*/,148/*vs/editor/common/standalone/standaloneEnums*/,192/*vs/editor/standalone/browser/standaloneServices*/,269/*vs/editor/standalone/common/monarch/monarchCompile*/,179/*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 provider['tokenizeEncoded']; } function isThenable(obj) { if (typeof obj.then === 'function') { return true; } return false; } /** * 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; /** * @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, // enums DocumentHighlightKind: standaloneEnums.DocumentHighlightKind, CompletionItemKind: standaloneEnums.CompletionItemKind, CompletionItemInsertTextRule: standaloneEnums.CompletionItemInsertTextRule, SymbolKind: standaloneEnums.SymbolKind, 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[577/*vs/editor/editor.api*/], __M([0/*require*/,1/*exports*/,48/*vs/editor/common/config/editorOptions*/,210/*vs/editor/common/standalone/standaloneBase*/,575/*vs/editor/standalone/browser/standaloneEditor*/,576/*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.EDITOR_DEFAULTS.wrappingIndent = 0 /* None */; editorOptions_1.EDITOR_DEFAULTS.viewInfo.glyphMargin = false; editorOptions_1.EDITOR_DEFAULTS.autoIndent = false; 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[578/*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; }); /*--------------------------------------------------------------------------------------------- * 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/snippet/snippetVariables*/], __M([0/*require*/,1/*exports*/,351/*vs/nls!vs/editor/contrib/snippet/snippetVariables*/,74/*vs/base/common/path*/,145/*vs/editor/contrib/snippet/snippetParser*/,39/*vs/editor/common/modes/languageConfigurationRegistry*/,5/*vs/base/common/strings*/,578/*vs/platform/workspaces/common/workspaces*/]), function (require, exports, nls, path_1, snippetParser_1, languageConfigurationRegistry_1, strings_1, workspaces_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(_model) { this._model = _model; // } ModelBasedVariableResolver.prototype.resolve = function (variable) { var name = variable.name; if (name === 'TM_FILENAME') { return path_1.basename(this._model.uri.fsPath); } else if (name === 'TM_FILENAME_BASE') { var name_1 = path_1.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') { var dir = path_1.dirname(this._model.uri.fsPath); return dir !== '.' ? dir : ''; } else if (name === 'TM_FILEPATH') { return this._model.uri.fsPath; } return undefined; }; return ModelBasedVariableResolver; }()); exports.ModelBasedVariableResolver = ModelBasedVariableResolver; var ClipboardBasedVariableResolver = /** @class */ (function () { function ClipboardBasedVariableResolver(_clipboardService, _selectionIdx, _selectionCount) { this._clipboardService = _clipboardService; this._selectionIdx = _selectionIdx; this._selectionCount = _selectionCount; // } ClipboardBasedVariableResolver.prototype.resolve = function (variable) { if (variable.name !== 'CLIPBOARD' || !this._clipboardService) { return undefined; } var text = this._clipboardService.readText(); if (!text) { return undefined; } var lines = text.split(/\r\n|\n|\r/).filter(function (s) { return !strings_1.isFalsyOrWhitespace(s); }); if (lines.length === this._selectionCount) { return lines[this._selectionIdx]; } else { return text; } }; 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()]; } 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 (variable.name !== 'WORKSPACE_NAME' || !this._workspaceService) { return undefined; } var workspaceIdentifier = workspaces_1.toWorkspaceIdentifier(this._workspaceService.getWorkspace()); if (!workspaceIdentifier) { return undefined; } if (workspaces_1.isSingleFolderWorkspaceIdentifier(workspaceIdentifier)) { return path_1.basename(workspaceIdentifier.path); } var filename = path_1.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; }; return WorkspaceBasedVariableResolver; }()); exports.WorkspaceBasedVariableResolver = WorkspaceBasedVariableResolver; }); /*--------------------------------------------------------------------------------------------- * 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/snippet/snippetSession*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,55/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,29/*vs/editor/common/model/textModel*/,176/*vs/platform/clipboard/common/clipboardService*/,150/*vs/platform/workspace/common/workspace*/,13/*vs/platform/instantiation/common/instantiation*/,145/*vs/editor/contrib/snippet/snippetParser*/,579/*vs/editor/contrib/snippet/snippetVariables*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,376/*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) { "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 skipThisPlaceholder = false; if (fwd === true && this._placeholderGroupsIdx < this._placeholderGroups.length - 1) { this._placeholderGroupsIdx += 1; skipThisPlaceholder = true; } else if (fwd === false && this._placeholderGroupsIdx > 0) { this._placeholderGroupsIdx -= 1; skipThisPlaceholder = 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) skipThisPlaceholder = skipThisPlaceholder && (range.isEmpty() && placeholder.toString().length > 0); 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 !skipThisPlaceholder ? newSelections : this.move(fwd); }; 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 SnippetSession = /** @class */ (function () { function SnippetSession(editor, template, overwriteBefore, overwriteAfter, adjustWhitespace) { if (overwriteBefore === void 0) { overwriteBefore = 0; } if (overwriteAfter === void 0) { overwriteAfter = 0; } if (adjustWhitespace === void 0) { adjustWhitespace = true; } this._templateMerges = []; this._snippets = []; this._editor = editor; this._template = template; this._overwriteBefore = overwriteBefore; this._overwriteAfter = overwriteAfter; this._adjustWhitespace = adjustWhitespace; } SnippetSession.adjustWhitespace = function (model, position, snippet) { 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/); 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); } 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) { var edits = []; var snippets = []; if (!editor.hasModel()) { return { edits: edits, snippets: snippets }; } var model = editor.getModel(); var modelBasedVariableResolver = new snippetVariables_1.ModelBasedVariableResolver(model); var clipboardService = editor.invokeWithinContext(function (accessor) { return accessor.get(clipboardService_1.IClipboardService, instantiation_1.optional); }); var workspaceService = editor.invokeWithinContext(function (accessor) { return accessor.get(workspace_1.IWorkspaceContextService, instantiation_1.optional); }); 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(); if (adjustWhitespace || (idx > 0 && firstLineFirstNonWhitespace !== model.getLineFirstNonWhitespaceColumn(selection.positionLineNumber))) { SnippetSession.adjustWhitespace(model, start, snippet); } snippet.resolveVariables(new snippetVariables_1.CompositeSnippetVariableResolver([ modelBasedVariableResolver, new snippetVariables_1.ClipboardBasedVariableResolver(clipboardService, idx, indexedSelections.length), new snippetVariables_1.SelectionBasedVariableResolver(model, selection), new snippetVariables_1.CommentBasedVariableResolver(model), new snippetVariables_1.TimeBasedVariableResolver, new snippetVariables_1.WorkspaceBasedVariableResolver(workspaceService), ])); 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; } var model = this._editor.getModel(); // make insert edit and start with first selections var _a = SnippetSession.createEditsAndSnippets(this._editor, this._template, this._overwriteBefore, this._overwriteAfter, false, this._adjustWhitespace), edits = _a.edits, snippets = _a.snippets; this._snippets = snippets; var selections = model.pushEditOperations(this._editor.getSelections(), 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.setSelections(selections); this._editor.revealRange(selections[0]); }; SnippetSession.prototype.merge = function (template, overwriteBefore, overwriteAfter, adjustWhitespace) { var _this = this; if (overwriteBefore === void 0) { overwriteBefore = 0; } if (overwriteAfter === void 0) { overwriteAfter = 0; } if (adjustWhitespace === void 0) { adjustWhitespace = true; } if (!this._editor.hasModel()) { return; } this._templateMerges.push([this._snippets[0]._nestingLevel, this._snippets[0]._placeholderGroupsIdx, template]); var _a = SnippetSession.createEditsAndSnippets(this._editor, template, overwriteBefore, overwriteAfter, true, adjustWhitespace), edits = _a.edits, snippets = _a.snippets; this._editor.setSelections(this._editor.getModel().pushEditOperations(this._editor.getSelections(), 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[159/*vs/editor/contrib/snippet/snippetController2*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,11/*vs/editor/browser/editorExtensions*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,21/*vs/editor/common/editorContextKeys*/,100/*vs/editor/contrib/suggest/suggest*/,18/*vs/platform/contextkey/common/contextkey*/,140/*vs/platform/log/common/log*/,580/*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 SnippetController2 = /** @class */ (function () { function SnippetController2(_editor, _logService, contextKeyService) { this._editor = _editor; this._logService = _logService; this._snippetListener = []; 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'); }; SnippetController2.prototype.dispose = function () { this._inSnippet.reset(); this._hasPrevTabstop.reset(); this._hasNextTabstop.reset(); lifecycle_1.dispose(this._session); }; SnippetController2.prototype.getId = function () { return 'snippetController2'; }; SnippetController2.prototype.insert = function (template, overwriteBefore, overwriteAfter, undoStopBefore, undoStopAfter, adjustWhitespace) { if (overwriteBefore === void 0) { overwriteBefore = 0; } if (overwriteAfter === void 0) { overwriteAfter = 0; } if (undoStopBefore === void 0) { undoStopBefore = true; } if (undoStopAfter === void 0) { undoStopAfter = true; } if (adjustWhitespace === void 0) { adjustWhitespace = true; } // 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, overwriteBefore, overwriteAfter, undoStopBefore, undoStopAfter, adjustWhitespace); } 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, overwriteBefore, overwriteAfter, undoStopBefore, undoStopAfter, adjustWhitespace) { var _this = this; if (overwriteBefore === void 0) { overwriteBefore = 0; } if (overwriteAfter === void 0) { overwriteAfter = 0; } if (undoStopBefore === void 0) { undoStopBefore = true; } if (undoStopAfter === void 0) { undoStopAfter = true; } if (adjustWhitespace === void 0) { adjustWhitespace = true; } if (!this._editor.hasModel()) { return; } // don't listen while inserting the snippet // as that is the inflight state causing cancelation this._snippetListener = lifecycle_1.dispose(this._snippetListener); if (undoStopBefore) { this._editor.getModel().pushStackElement(); } if (!this._session) { this._modelVersionId = this._editor.getModel().getAlternativeVersionId(); this._session = new snippetSession_1.SnippetSession(this._editor, template, overwriteBefore, overwriteAfter, adjustWhitespace); this._session.insert(); } else { this._session.merge(template, overwriteBefore, overwriteAfter, adjustWhitespace); } if (undoStopAfter) { this._editor.getModel().pushStackElement(); } this._updateState(); this._snippetListener = [ this._editor.onDidChangeModelContent(function (e) { return e.isFlush && _this.cancel(); }), this._editor.onDidChangeModel(function () { return _this.cancel(); }), 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(); lifecycle_1.dispose(this._snippetListener); 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.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); 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[582/*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*/,16/*vs/editor/common/modes*/,309/*vs/editor/contrib/suggest/completionModel*/,100/*vs/editor/contrib/suggest/suggest*/,159/*vs/editor/contrib/snippet/snippetController2*/,24/*vs/base/common/cancellation*/,267/*vs/editor/contrib/suggest/wordDistance*/]), 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) { "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 = []; this._triggerQuickSuggest = new async_1.TimeoutTimer(); this._triggerRefilter = new async_1.TimeoutTimer(); this._state = 0 /* Idle */; 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.push(this._editor.onDidChangeModel(function () { _this._updateTriggerCharacters(); _this.cancel(); })); this._toDispose.push(this._editor.onDidChangeModelLanguage(function () { _this._updateTriggerCharacters(); _this.cancel(); })); this._toDispose.push(this._editor.onDidChangeConfiguration(function () { _this._updateTriggerCharacters(); _this._updateQuickSuggest(); })); this._toDispose.push(modes_1.CompletionProviderRegistry.onDidChange(function () { _this._updateTriggerCharacters(); _this._updateActiveSuggestSession(); })); this._toDispose.push(this._editor.onDidChangeCursorSelection(function (e) { _this._onCursorChange(e); })); var editorIsComposing = false; this._toDispose.push(this._editor.onCompositionStart(function () { editorIsComposing = true; })); this._toDispose.push(this._editor.onCompositionEnd(function () { // refilter when composition ends editorIsComposing = false; _this._refilterCompletionItems(); })); this._toDispose.push(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._onDidCancel, this._onDidSuggest, this._onDidTrigger, this._triggerCharacterListener, this._triggerQuickSuggest, this._triggerRefilter]); this._toDispose = lifecycle_1.dispose(this._toDispose); lifecycle_1.dispose(this._completionModel); this.cancel(); }; // --- handle configuration & precondition changes SuggestModel.prototype._updateQuickSuggest = function () { this._quickSuggestDelay = this._editor.getConfiguration().contribInfo.quickSuggestionsDelay; if (isNaN(this._quickSuggestDelay) || (!this._quickSuggestDelay && this._quickSuggestDelay !== 0) || this._quickSuggestDelay < 0) { this._quickSuggestDelay = 10; } }; SuggestModel.prototype._updateTriggerCharacters = function () { var _this = this; lifecycle_1.dispose(this._triggerCharacterListener); if (this._editor.getConfiguration().readOnly || !this._editor.hasModel() || !this._editor.getConfiguration().contribInfo.suggestOnTriggerCharacters) { return; } var supportsByTriggerCharacter = Object.create(null); 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[ch]; if (!set) { set = supportsByTriggerCharacter[ch] = new Set(); set.add(suggest_1.getSnippetSuggestSupport()); } set.add(support); } } this._triggerCharacterListener = this._editor.onDidType(function (text) { var lastChar = text.charAt(text.length - 1); var supports = supportsByTriggerCharacter[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); } }); }; 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._triggerRefilter.cancel(); this._triggerQuickSuggest.cancel(); if (this._requestToken) { this._requestToken.cancel(); this._requestToken = undefined; } this._state = 0 /* Idle */; lifecycle_1.dispose(this._completionModel); this._completionModel = undefined; this._context = undefined; this._onDidCancel.fire({ retrigger: retrigger }); } }; 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 ;) if (this._state !== 0 /* Idle */) { this.cancel(); } return; } if (!modes_1.CompletionProviderRegistry.has(model)) { return; } if (this._state === 0 /* Idle */) { if (this._editor.getConfiguration().contribInfo.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.getConfiguration().contribInfo.suggest.snippetsPreventQuickSuggestions && snippetController2_1.SnippetController2.get(this._editor).isInSnippet()) { // no quick suggestion when in snippet mode return; } this.cancel(); this._triggerQuickSuggest.cancelAndSet(function () { 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.getConfiguration().contribInfo.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; if (this._state === 0 /* Idle */) { return; } if (!this._editor.hasModel()) { return; } // refine active suggestion this._triggerRefilter.cancelAndSet(function () { 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); }, 0); }; 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 }); // 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 contribInfo = this._editor.getConfiguration().contribInfo; var itemKindFilter = new Set(); var snippetSortOrder = 1 /* Inline */; switch (contribInfo.suggest.snippets) { case 'top': snippetSortOrder = 0 /* Top */; break; // ↓ that's the default anyways... // case 'inline': // snippetSortOrder = SnippetSortOrder.Inline; // break; case 'bottom': snippetSortOrder = 2 /* Bottom */; break; case 'none': itemKindFilter.add(25 /* Snippet */); break; } // kind filter for (var key in contribInfo.suggest.filteredTypes) { var kind = modes_1.completionKindFromString(key, true); if (typeof kind !== 'undefined' && contribInfo.suggest.filteredTypes[key] === false) { itemKindFilter.add(kind); } } 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); lifecycle_1.dispose(_this._completionModel); _this._completionModel = new completionModel_1.CompletionModel(items, _this._context.column, { leadingLineContent: ctx.leadingLineContent, characterCountDelta: ctx.column - _this._context.column }, wordDistance, _this._editor.getConfiguration().contribInfo.suggest); _this._onNewContext(ctx); }).catch(errors_1.onUnexpectedError); }; 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. *--------------------------------------------------------------------------------------------*/ define(__m[526/*vs/editor/contrib/suggest/suggestController*/], __M([0/*require*/,1/*exports*/,47/*vs/base/browser/ui/aria/aria*/,19/*vs/base/common/arrays*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,11/*vs/editor/browser/editorExtensions*/,55/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/editorContextKeys*/,159/*vs/editor/contrib/snippet/snippetController2*/,145/*vs/editor/contrib/snippet/snippetParser*/,184/*vs/editor/contrib/suggest/suggestMemory*/,352/*vs/nls!vs/editor/contrib/suggest/suggestController*/,27/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/,13/*vs/platform/instantiation/common/instantiation*/,100/*vs/editor/contrib/suggest/suggest*/,414/*vs/editor/contrib/suggest/suggestAlternatives*/,582/*vs/editor/contrib/suggest/suggestModel*/,548/*vs/editor/contrib/suggest/suggestWidget*/,415/*vs/editor/contrib/suggest/wordContextKey*/,4/*vs/base/common/event*/,63/*vs/editor/common/services/editorWorkerService*/,15/*vs/base/common/async*/,76/*vs/editor/common/core/characterClassifier*/,20/*vs/base/common/types*/]), function (require, exports, aria_1, arrays_1, errors_1, lifecycle_1, editorExtensions_1, editOperation_1, range_1, editorContextKeys_1, snippetController2_1, snippetParser_1, suggestMemory_1, nls, commands_1, contextkey_1, instantiation_1, suggest_1, suggestAlternatives_1, suggestModel_1, suggestWidget_1, wordContextKey_1, event_1, editorWorkerService_1, async_1, characterClassifier_1, types_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var AcceptOnCharacterOracle = /** @class */ (function () { function AcceptOnCharacterOracle(editor, widget, accept) { var _this = this; this._disposables = []; this._disposables.push(widget.onDidShow(function () { return _this._onItem(widget.getFocusedItem()); })); this._disposables.push(widget.onDidFocus(this._onItem, this)); this._disposables.push(widget.onDidHide(this.reset, this)); this._disposables.push(editor.onWillType(function (text) { if (_this._active) { var ch = text.charCodeAt(text.length - 1); if (_this._active.acceptCharacters.has(ch) && editor.getConfiguration().contribInfo.acceptSuggestionOnCommitCharacter) { accept(_this._active.item); } } })); } AcceptOnCharacterOracle.prototype._onItem = function (selected) { if (!selected || !arrays_1.isNonEmptyArray(selected.item.completion.commitCharacters)) { this.reset(); return; } 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 }; }; AcceptOnCharacterOracle.prototype.reset = function () { this._active = undefined; }; AcceptOnCharacterOracle.prototype.dispose = function () { lifecycle_1.dispose(this._disposables); }; return AcceptOnCharacterOracle; }()); var SuggestController = /** @class */ (function () { function SuggestController(_editor, editorWorker, _memoryService, _commandService, _contextKeyService, _instantiationService) { var _this = this; this._editor = _editor; this._memoryService = _memoryService; this._commandService = _commandService; this._contextKeyService = _contextKeyService; this._instantiationService = _instantiationService; this._toDispose = []; this._sticky = false; // for development purposes only this._model = new suggestModel_1.SuggestModel(this._editor, editorWorker); this._widget = new async_1.IdleValue(function () { var widget = _this._instantiationService.createInstance(suggestWidget_1.SuggestWidget, _this._editor); _this._toDispose.push(widget); _this._toDispose.push(widget.onDidSelect(function (item) { return _this._onDidSelectItem(item, false, true); }, _this)); // Wire up logic to accept a suggestion on certain characters var autoAcceptOracle = new AcceptOnCharacterOracle(_this._editor, widget, function (item) { return _this._onDidSelectItem(item, false, true); }); _this._toDispose.push(autoAcceptOracle, _this._model.onDidSuggest(function (e) { if (e.completionModel.items.length === 0) { autoAcceptOracle.reset(); } })); // Wire up makes text edit context key var makesTextEdit = suggest_1.Context.MakesTextEdit.bindTo(_this._contextKeyService); _this._toDispose.push(widget.onDidFocus(function (_a) { var item = _a.item; var position = _this._editor.getPosition(); var startColumn = item.completion.range.startColumn; var endColumn = position.column; var value = true; if (_this._editor.getConfiguration().contribInfo.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.push({ dispose: function () { makesTextEdit.reset(); } }); return widget; }); this._alternatives = new async_1.IdleValue(function () { var res = new suggestAlternatives_1.SuggestAlternatives(_this._editor, _this._contextKeyService); _this._toDispose.push(res); return res; }); this._toDispose.push(_instantiationService.createInstance(wordContextKey_1.WordContextKey, _editor)); this._toDispose.push(this._model.onDidTrigger(function (e) { _this._widget.getValue().showTriggered(e.auto, e.shy ? 250 : 50); })); this._toDispose.push(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.push(this._model.onDidCancel(function (e) { if (_this._widget && !e.retrigger) { _this._widget.getValue().hideWidget(); } })); this._toDispose.push(this._editor.onDidBlurEditorWidget(function () { if (!_this._sticky) { _this._model.cancel(); } })); // Manage the acceptSuggestionsOnEnter context key var acceptSuggestionsOnEnter = suggest_1.Context.AcceptSuggestionsOnEnter.bindTo(_contextKeyService); var updateFromConfig = function () { var acceptSuggestionOnEnter = _this._editor.getConfiguration().contribInfo.acceptSuggestionOnEnter; acceptSuggestionsOnEnter.set(acceptSuggestionOnEnter === 'on' || acceptSuggestionOnEnter === 'smart'); }; this._toDispose.push(this._editor.onDidChangeConfiguration(function (e) { return updateFromConfig(); })); updateFromConfig(); } SuggestController.get = function (editor) { return editor.getContribution(SuggestController.ID); }; SuggestController.prototype.getId = function () { return SuggestController.ID; }; SuggestController.prototype.dispose = function () { this._toDispose = lifecycle_1.dispose(this._toDispose); this._widget.dispose(); if (this._model) { this._model.dispose(); } }; SuggestController.prototype._onDidSelectItem = function (event, keepAlternativeSuggestions, undoStops) { var _this = this; var _a; if (!event || !event.item) { this._alternatives.getValue().reset(); this._model.cancel(); return; } if (!this._editor.hasModel()) { return; } var model = this._editor.getModel(); var modelVersionNow = model.getAlternativeVersionId(); var _b = event.item, suggestion = _b.completion, position = _b.position; var editorColumn = this._editor.getPosition().column; var columnDelta = editorColumn - position.column; // pushing undo stops *before* additional text edits and // *after* the main edit if (undoStops) { this._editor.pushUndoStop(); } 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); })); } // keep item in memory this._memoryService.memorize(model, this._editor.getPosition(), event.item); var insertText = suggestion.insertText; if (!(suggestion.insertTextRules & 4 /* InsertAsSnippet */)) { insertText = snippetParser_1.SnippetParser.escape(insertText); } var overwriteBefore = position.column - suggestion.range.startColumn; var overwriteAfter = suggestion.range.endColumn - position.column; snippetController2_1.SnippetController2.get(this._editor).insert(insertText, overwriteBefore + columnDelta, overwriteAfter, false, false, !(suggestion.insertTextRules & 1 /* KeepWhitespace */)); if (undoStops) { this._editor.pushUndoStop(); } if (!suggestion.command) { // done this._model.cancel(); } 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, [suggestion.command.id].concat((suggestion.command.arguments ? suggestion.command.arguments.slice() : []))).catch(errors_1.onUnexpectedError); this._model.cancel(); } if (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._onDidSelectItem(next, false, false); break; } }); } this._alertCompletionItem(event.item); }; SuggestController.prototype._alertCompletionItem = function (_a) { var suggestion = _a.completion; if (arrays_1.isNonEmptyArray(suggestion.additionalTextEdits)) { var msg = nls.localize(0, null, suggestion.label, 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.completion.range.startColumn; 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._onDidSelectItem({ index: index, item: item, model: completionModel }, true, false); }, undefined, listener); }); this._model.trigger({ auto: false, shy: true }); this._editor.revealLine(positionNow.lineNumber, 0 /* Smooth */); this._editor.focus(); }; SuggestController.prototype.acceptSelectedSuggestion = function (keepAlternativeSuggestions) { if (this._widget) { var item = this._widget.getValue().getFocusedItem(); this._onDidSelectItem(item, !!keepAlternativeSuggestions, true); } }; SuggestController.prototype.acceptNextSuggestion = function () { this._alternatives.getValue().next(); }; SuggestController.prototype.acceptPrevSuggestion = function () { this._alternatives.getValue().prev(); }; SuggestController.prototype.cancelSuggestWidget = function () { if (this._widget) { this._model.cancel(); this._widget.getValue().hideWidget(); } }; SuggestController.prototype.selectNextSuggestion = function () { if (this._widget) { this._widget.getValue().selectNext(); } }; SuggestController.prototype.selectNextPageSuggestion = function () { if (this._widget) { this._widget.getValue().selectNextPage(); } }; SuggestController.prototype.selectLastSuggestion = function () { if (this._widget) { this._widget.getValue().selectLast(); } }; SuggestController.prototype.selectPrevSuggestion = function () { if (this._widget) { this._widget.getValue().selectPrevious(); } }; SuggestController.prototype.selectPrevPageSuggestion = function () { if (this._widget) { this._widget.getValue().selectPreviousPage(); } }; SuggestController.prototype.selectFirstSuggestion = function () { if (this._widget) { this._widget.getValue().selectFirst(); } }; SuggestController.prototype.toggleSuggestionDetails = function () { if (this._widget) { this._widget.getValue().toggleDetails(); } }; SuggestController.prototype.toggleSuggestionFocus = function () { if (this._widget) { 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 */ }, 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); 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) { return x.acceptSelectedSuggestion(true); }, kbOpts: { weight: weight, kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 2 /* Tab */ } })); editorExtensions_1.registerEditorCommand(new SuggestCommand({ id: 'acceptSelectedSuggestionOnEnter', precondition: suggest_1.Context.Visible, handler: function (x) { return x.acceptSelectedSuggestion(false); }, kbOpts: { weight: weight, kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, suggest_1.Context.AcceptSuggestionsOnEnter, suggest_1.Context.MakesTextEdit), primary: 3 /* Enter */ } })); 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: '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[251/*vs/editor/editor.all*/], __M([0/*require*/,1/*exports*/,132/*vs/editor/browser/controller/coreCommands*/,102/*vs/editor/browser/widget/codeEditorWidget*/,204/*vs/editor/browser/widget/diffEditorWidget*/,166/*vs/editor/browser/widget/diffNavigator*/,528/*vs/editor/contrib/bracketMatching/bracketMatching*/,465/*vs/editor/contrib/caretOperations/caretOperations*/,466/*vs/editor/contrib/caretOperations/transpose*/,467/*vs/editor/contrib/clipboard/clipboard*/,541/*vs/editor/contrib/codeAction/codeActionContributions*/,530/*vs/editor/contrib/codelens/codelensController*/,172/*vs/editor/contrib/colorPicker/colorDetector*/,474/*vs/editor/contrib/comment/comment*/,475/*vs/editor/contrib/contextmenu/contextmenu*/,476/*vs/editor/contrib/cursorUndo/cursorUndo*/,477/*vs/editor/contrib/dnd/dnd*/,222/*vs/editor/contrib/find/findController*/,478/*vs/editor/contrib/folding/folding*/,479/*vs/editor/contrib/fontZoom/fontZoom*/,481/*vs/editor/contrib/format/formatActions*/,224/*vs/editor/contrib/goToDefinition/goToDefinitionCommands*/,568/*vs/editor/contrib/goToDefinition/goToDefinitionMouse*/,197/*vs/editor/contrib/gotoError/gotoError*/,565/*vs/editor/contrib/hover/hover*/,537/*vs/editor/contrib/inPlaceReplace/inPlaceReplace*/,484/*vs/editor/contrib/linesOperations/linesOperations*/,538/*vs/editor/contrib/links/links*/,542/*vs/editor/contrib/multicursor/multicursor*/,544/*vs/editor/contrib/parameterHints/parameterHints*/,569/*vs/editor/contrib/referenceSearch/referenceSearch*/,547/*vs/editor/contrib/rename/rename*/,488/*vs/editor/contrib/smartSelect/smartSelect*/,159/*vs/editor/contrib/snippet/snippetController2*/,526/*vs/editor/contrib/suggest/suggestController*/,491/*vs/editor/contrib/tokenization/tokenization*/,164/*vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/,549/*vs/editor/contrib/wordHighlighter/wordHighlighter*/,162/*vs/editor/contrib/wordOperations/wordOperations*/,493/*vs/editor/contrib/wordPartOperations/wordPartOperations*/,50/*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[585/*vs/editor/editor.main*/], __M([0/*require*/,1/*exports*/,577/*vs/editor/editor.api*/,251/*vs/editor/editor.all*/,550/*vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/,494/*vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/,551/*vs/editor/standalone/browser/inspectTokens/inspectTokens*/,553/*vs/editor/standalone/browser/quickOpen/gotoLine*/,554/*vs/editor/standalone/browser/quickOpen/quickCommand*/,555/*vs/editor/standalone/browser/quickOpen/quickOutline*/,570/*vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch*/,495/*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","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; var LanguageServiceDefaultsImpl = /** @class */ (function () { function LanguageServiceDefaultsImpl(compilerOptions, diagnosticsOptions) { this._onDidChange = new Emitter(); this._onDidExtraLibsChange = new Emitter(); this._extraLibs = Object.create(null); this._workerMaxIdleTime = 2 * 60 * 1000; 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; if (typeof filePath === 'undefined') { filePath = "ts:extralib-" + Math.random().toString(36).substring(2, 15); } 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._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) { // doesn't fire an event since no // worker restart is required here this._workerMaxIdleTime = value; }; LanguageServiceDefaultsImpl.prototype.getWorkerMaxIdleTime = function () { return this._workerMaxIdleTime; }; 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"] = 6] = "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["ESNext"] = 6] = "ESNext"; ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 6] = "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, 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) { this._onDidChange = new Emitter(); this._languageId = languageId; this.setDiagnosticsOptions(diagnosticsOptions); } 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, "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); }; 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 cssDefaults = new LanguageServiceDefaultsImpl('css', diagnosticDefault); var scssDefaults = new LanguageServiceDefaultsImpl('scss', diagnosticDefault); var lessDefaults = new LanguageServiceDefaultsImpl('less', diagnosticDefault); // 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) { this._onDidChange = new Emitter(); this._languageId = languageId; this.setDiagnosticsOptions(diagnosticsOptions); } 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, "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); }; return LanguageServiceDefaultsImpl; }()); exports.LanguageServiceDefaultsImpl = LanguageServiceDefaultsImpl; var diagnosticDefault = { validate: true, allowComments: true, schemas: [], enableSchemaRequest: false }; var jsonDefaults = new LanguageServiceDefaultsImpl('json', diagnosticDefault); // 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'], 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) { this._onDidChange = new Emitter(); this._languageId = languageId; this.setOptions(options); } 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 }); LanguageServiceDefaultsImpl.prototype.setOptions = function (options) { this._options = options || 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 } }; var htmlLanguageId = 'html'; var handlebarsLanguageId = 'handlebars'; var razorLanguageId = 'razor'; var htmlDefaults = new LanguageServiceDefaultsImpl(htmlLanguageId, htmlOptionsDefault); var handlebarDefaults = new LanguageServiceDefaultsImpl(handlebarsLanguageId, handlebarOptionsDefault); var razorDefaults = new LanguageServiceDefaultsImpl(razorLanguageId, razorOptionsDefault); // 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", "./bat/bat.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", "./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", "./msdax/msdax.contribution", "./mysql/mysql.contribution", "./objective-c/objective-c.contribution", "./pascal/pascal.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", "./ruby/ruby.contribution", "./rust/rust.contribution", "./sb/sb.contribution", "./scss/scss.contribution", "./solidity/solidity.contribution", "./sql/sql.contribution", "./st/st.contribution", "./swift/swift.contribution", "./tcl/tcl.contribution", "./typescript/typescript.contribution", "./vb/vb.contribution", "./xml/xml.contribution", "./yaml/yaml.contribution", "./scheme/scheme.contribution", "./clojure/clojure.contribution", "./shell/shell.contribution", "./perl/perl.contribution", "./azcli/azcli.contribution", "./apex/apex.contribution", "./graphql/graphql.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