/*!-----------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.10.0(9b725bd7807ee959240b4af7906fae119b0fbf9e)
 * Released under the MIT license
 * https://github.com/Microsoft/vscode/blob/master/LICENSE.txt
 *-----------------------------------------------------------*/

(function() {
var __m = ["exports","require","vs/editor/common/core/range","vs/base/common/lifecycle","vs/base/browser/dom","vs/css!vs/editor/editor.main","vs/nls","vs/base/common/winjs.base","vs/nls!vs/editor/editor.main","vs/base/common/strings","vs/base/common/errors","vs/base/common/event","vs/editor/common/core/position","vs/editor/common/editorCommonExtensions","vs/platform/theme/common/themeService","vs/base/common/platform","vs/platform/instantiation/common/instantiation","vs/editor/common/modes","vs/base/common/async","vs/platform/contextkey/common/contextkey","vs/editor/common/editorCommon","vs/editor/common/editorContextKeys","vs/editor/common/core/selection","vs/platform/theme/common/colorRegistry","vs/base/common/uri","vs/editor/browser/editorBrowser","vs/base/common/objects","vs/base/browser/fastDomNode","vs/base/browser/browser","vs/base/common/types","vs/editor/browser/editorBrowserExtensions","vs/platform/commands/common/commands","vs/base/common/color","vs/base/common/arrays","vs/editor/common/model/textModelWithDecorations","vs/editor/browser/view/viewPart","vs/base/common/severity","vs/editor/common/view/editorColorRegistry","vs/base/common/eventEmitter","vs/editor/common/controller/cursorCommon","vs/base/common/keyCodes","vs/base/browser/ui/widget","vs/editor/common/services/codeEditorService","vs/editor/common/modes/languageConfigurationRegistry","vs/platform/registry/common/platform","vs/base/common/paths","vs/platform/keybinding/common/keybinding","vs/base/browser/mouseEvent","vs/base/common/scrollable","vs/editor/common/config/editorOptions","vs/platform/message/common/message","vs/base/browser/ui/aria/aria","vs/base/browser/builder","vs/base/common/actions","vs/editor/common/controller/cursorEvents","vs/editor/common/model/textModelEvents","vs/editor/common/services/modelService","vs/editor/common/view/viewEvents","vs/platform/telemetry/common/telemetry","vs/editor/common/core/editOperation","vs/editor/common/modes/languageConfiguration","vs/editor/common/services/editorWorkerService","vs/platform/configuration/common/configuration","vs/base/browser/ui/scrollbar/scrollableElement","vs/platform/editor/common/editor","vs/base/browser/keyboardEvent","vs/editor/browser/config/configuration","vs/editor/browser/view/dynamicViewOverlay","vs/editor/common/modes/nullMode","vs/platform/contextview/browser/contextView","vs/base/common/network","vs/platform/opener/common/opener","vs/base/common/assert","vs/editor/common/commands/replaceCommand","vs/base/browser/touch","vs/base/browser/ui/actionbar/actionbar","vs/platform/storage/common/storage","vs/editor/standalone/common/standaloneThemeService","vs/editor/common/view/renderingContext","vs/base/common/events","vs/base/common/map","vs/base/common/filters","vs/editor/common/viewModel/viewEventHandler","vs/base/browser/globalMouseMoveMonitor","vs/platform/instantiation/common/serviceCollection","vs/platform/actions/common/actions","vs/editor/common/viewModel/viewModel","vs/editor/common/services/resolverService","vs/editor/common/services/modeService","vs/editor/common/core/characterClassifier","vs/editor/common/core/viewLineToken","vs/editor/common/modes/supports","vs/editor/contrib/zoneWidget/browser/peekViewWidget","vs/editor/common/model/textModel","vs/editor/common/controller/wordCharacterClassifier","vs/editor/common/model/wordHelper","vs/editor/common/core/uint","vs/editor/common/core/token","vs/editor/common/modes/supports/richEditBrackets","vs/base/browser/ui/sash/sash","vs/base/parts/quickopen/common/quickOpen","vs/editor/common/model/textSource","vs/base/browser/htmlContentRenderer","vs/platform/markers/common/markers","vs/editor/common/viewModel/prefixSumComputer","vs/platform/keybinding/common/keybindingsRegistry","vs/editor/common/viewLayout/viewLineRenderer","vs/base/common/iterator","vs/base/common/idGenerator","vs/editor/contrib/suggest/browser/suggest","vs/base/browser/ui/highlightedlabel/highlightedLabel","vs/editor/common/view/minimapCharRenderer","vs/editor/browser/view/viewLayer","vs/editor/browser/viewParts/glyphMargin/glyphMargin","vs/editor/browser/editorDom","vs/base/browser/ui/inputbox/inputBox","vs/editor/common/model/tokensBinaryEncoding","vs/base/browser/ui/scrollbar/scrollbarArrow","vs/editor/common/model/modelLine","vs/editor/common/controller/cursorTypeOperations","vs/base/parts/quickopen/browser/quickOpenModel","vs/editor/contrib/find/common/findModel","vs/editor/common/modes/textToHtmlTokenizer","vs/base/common/cancellation","vs/base/browser/event","vs/editor/contrib/referenceSearch/browser/referencesModel","vs/editor/common/modes/modesRegistry","vs/platform/configuration/common/configurationRegistry","vs/base/parts/tree/browser/treeDefaults","vs/editor/standalone/browser/simpleServices","vs/editor/common/core/lineTokens","vs/editor/common/core/editorState","vs/editor/common/config/fontInfo","vs/base/common/htmlContent","vs/editor/common/controller/coreCommands","vs/editor/common/config/editorZoom","vs/base/common/functional","vs/platform/theme/common/styler","vs/editor/common/viewLayout/lineDecorations","vs/base/common/diff/diff","vs/editor/common/view/overviewZoneManager","vs/editor/browser/codeEditor","vs/editor/contrib/snippet/browser/snippetParser","vs/editor/standalone/browser/quickOpen/editorQuickOpen","vs/platform/workspace/common/workspace","vs/editor/standalone/common/monarch/monarchCommon","vs/editor/common/services/resourceConfiguration","vs/editor/common/services/editorWorkerServiceImpl","vs/base/browser/iframe","vs/editor/common/editorAction","vs/base/browser/ui/scrollbar/scrollbarState","vs/editor/browser/controller/textAreaState","vs/editor/common/standalone/standaloneBase","vs/base/browser/ui/findinput/findInputCheckboxes","vs/editor/browser/controller/textAreaInput","vs/base/common/keybindingLabels","vs/platform/environment/common/environment","vs/base/common/collections","vs/editor/common/model/textModelSearch","vs/platform/keybinding/common/keybindingResolver","vs/base/browser/ui/contextview/contextview","vs/base/parts/tree/browser/treeImpl","vs/base/browser/ui/iconLabel/iconLabel","vs/platform/progress/common/progress","vs/editor/browser/widget/diffNavigator","vs/base/common/glob","vs/base/common/mime","vs/editor/common/commands/shiftCommand","vs/editor/common/config/commonEditorConfig","vs/editor/common/controller/cursorMoveOperations","vs/editor/common/controller/cursorDeleteOperations","vs/css!vs/editor/contrib/goToDeclaration/browser/goToDeclarationMouse","vs/editor/common/controller/cursorWordOperations","vs/editor/common/controller/cursorMoveCommands","vs/base/common/labels","vs/editor/common/model/model","vs/editor/contrib/find/common/findController","vs/editor/contrib/goToDeclaration/browser/goToDeclaration","vs/editor/contrib/parameterHints/common/parameterHints","vs/editor/common/viewModel/splitLinesCollection","vs/editor/contrib/snippet/browser/snippetController2","vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode","vs/editor/browser/viewParts/margin/margin","vs/editor/contrib/zoneWidget/browser/zoneWidget","vs/base/browser/ui/scrollbar/abstractScrollbar","vs/editor/browser/viewParts/lines/viewLine","vs/editor/browser/controller/mouseTarget","vs/platform/instantiation/common/descriptors","vs/editor/browser/viewParts/lineNumbers/lineNumbers","vs/editor/contrib/comment/common/blockCommentCommand","vs/editor/browser/viewParts/overviewRuler/overviewRulerImpl","vs/editor/browser/widget/codeEditorWidget","vs/editor/contrib/goToDeclaration/browser/clickLinkGesture","vs/editor/browser/widget/diffEditorWidget","vs/editor/browser/widget/embeddedCodeEditorWidget","vs/editor/contrib/hover/browser/hoverOperation","vs/editor/contrib/hover/browser/hoverWidgets","vs/base/common/worker/simpleWorker","vs/editor/contrib/referenceSearch/browser/referencesController","vs/editor/contrib/goToDeclaration/browser/goToDeclarationCommands","vs/editor/standalone/browser/standaloneServices","vs/css!vs/base/browser/ui/countBadge/countBadge","vs/editor/common/modes/supports/tokenization","vs/editor/common/modes/tokenizationRegistry","vs/base/browser/ui/countBadge/countBadge","vs/css!vs/base/browser/ui/findinput/findInput","vs/css!vs/base/browser/ui/findinput/findInputCheckboxes","vs/editor/common/modes/supports/electricCharacter","vs/css!vs/base/browser/ui/iconLabel/iconlabel","vs/base/common/marked/marked","vs/editor/common/services/abstractCodeEditorService","vs/css!vs/base/browser/ui/inputbox/inputBox","vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel","vs/css!vs/base/browser/ui/list/list","vs/editor/browser/viewParts/lines/rangeUtil","vs/editor/common/view/runtimeMinimapCharRenderer","vs/editor/common/view/viewContext","vs/editor/common/view/viewEventDispatcher","vs/css!vs/base/browser/ui/menu/menu","vs/css!vs/base/browser/ui/progressbar/progressbar","vs/base/browser/ui/progressbar/progressbar","vs/editor/common/viewLayout/viewLinesViewportData","vs/editor/common/viewLayout/whitespaceComputer","vs/editor/common/viewLayout/linesLayout","vs/css!vs/base/browser/ui/sash/sash","vs/editor/common/model/mirrorModel","vs/editor/common/services/editorSimpleWorker","vs/editor/standalone/browser/standaloneLanguages","vs/css!vs/base/browser/ui/scrollbar/media/scrollbars","vs/base/common/comparers","vs/editor/browser/viewParts/contentWidgets/contentWidgets","vs/editor/browser/viewParts/decorations/decorations","vs/base/browser/ui/list/listView","vs/editor/browser/viewParts/linesDecorations/linesDecorations","vs/base/browser/ui/list/listWidget","vs/editor/browser/viewParts/marginDecorations/marginDecorations","vs/editor/browser/viewParts/overlayWidgets/overlayWidgets","vs/editor/browser/viewParts/viewZones/viewZones","vs/base/parts/tree/browser/treeView","vs/editor/common/viewLayout/viewLayout","vs/editor/common/viewModel/viewModelDecorations","vs/editor/contrib/caretOperations/common/moveCaretCommand","vs/editor/contrib/colorPicker/browser/colorPickerModel","vs/editor/contrib/colorPicker/browser/elements/colorPickerBody","vs/editor/contrib/colorPicker/browser/elements/colorPickerHeader","vs/editor/contrib/colorPicker/browser/colorPickerWidget","vs/editor/contrib/colorPicker/common/color","vs/editor/contrib/colorPicker/common/colorFormatter","vs/editor/contrib/colorPicker/common/colorPicker","vs/css!vs/base/browser/ui/selectBox/selectBox","vs/editor/contrib/comment/common/lineCommentCommand","vs/editor/contrib/dnd/common/dragAndDropCommand","vs/editor/contrib/find/common/find","vs/editor/contrib/find/common/findState","vs/editor/contrib/find/common/replaceAllCommand","vs/editor/contrib/find/common/replacePattern","vs/editor/contrib/folding/common/folding","vs/editor/contrib/folding/common/indentFoldStrategy","vs/editor/contrib/format/common/formatCommand","vs/base/browser/ui/selectBox/selectBox","vs/css!vs/base/parts/quickopen/browser/quickopen","vs/css!vs/base/parts/tree/browser/tree","vs/editor/contrib/inPlaceReplace/common/inPlaceReplaceCommand","vs/editor/contrib/indentation/common/indentUtils","vs/editor/contrib/linesOperations/common/copyLinesCommand","vs/editor/contrib/linesOperations/common/deleteLinesCommand","vs/editor/contrib/linesOperations/common/sortLinesCommand","vs/editor/contrib/quickFix/browser/lightBulbWidget","vs/editor/contrib/quickFix/browser/quickFixWidget","vs/editor/contrib/smartSelect/common/tokenTree","vs/css!vs/editor/browser/controller/textAreaHandler","vs/editor/contrib/snippet/browser/snippetVariables","vs/editor/contrib/suggest/browser/completionModel","vs/editor/standalone/browser/colorizer","vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight","vs/editor/standalone/common/monarch/monarchCompile","vs/editor/standalone/common/monarch/monarchLexer","vs/css!vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight","vs/css!vs/editor/browser/viewParts/decorations/decorations","vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin","vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides","vs/base/browser/ui/menu/menu","vs/nls!vs/base/browser/ui/aria/aria","vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers","vs/nls!vs/base/browser/ui/findinput/findInput","vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes","vs/css!vs/editor/browser/viewParts/lines/viewLines","vs/nls!vs/base/browser/ui/inputbox/inputBox","vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations","vs/base/browser/ui/findinput/findInput","vs/nls!vs/base/common/keybindingLabels","vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations","vs/base/browser/ui/keybindingLabel/keybindingLabel","vs/nls!vs/base/common/severity","vs/css!vs/editor/browser/viewParts/minimap/minimap","vs/nls!vs/base/parts/quickopen/browser/quickOpenModel","vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets","vs/nls!vs/base/parts/quickopen/browser/quickOpenWidget","vs/nls!vs/base/parts/tree/browser/treeDefaults","vs/css!vs/editor/browser/viewParts/rulers/rulers","vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration","vs/base/parts/quickopen/browser/quickOpenWidget","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/css!vs/editor/browser/viewParts/selections/selections","vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors","vs/css!vs/editor/browser/widget/media/diffEditor","vs/css!vs/editor/browser/widget/media/diffReview","vs/css!vs/editor/browser/widget/media/editor","vs/editor/common/controller/cursorColumnSelection","vs/css!vs/editor/browser/widget/media/tokens","vs/css!vs/editor/contrib/bracketMatching/browser/bracketMatching","vs/css!vs/editor/contrib/clipboard/browser/clipboard","vs/css!vs/editor/contrib/codelens/browser/codelensWidget","vs/css!vs/editor/contrib/colorPicker/browser/colorPicker","vs/editor/common/controller/oneCursor","vs/editor/common/controller/cursorCollection","vs/editor/contrib/linesOperations/common/moveLinesCommand","vs/nls!vs/editor/common/controller/cursor","vs/editor/common/controller/cursor","vs/nls!vs/editor/common/model/textModelWithTokens","vs/editor/common/model/textModelWithTokens","vs/editor/common/model/textModelWithMarkers","vs/css!vs/editor/contrib/dnd/browser/dnd","vs/editor/common/model/editableTextModel","vs/css!vs/editor/contrib/find/browser/findWidget","vs/css!vs/editor/contrib/folding/browser/folding","vs/editor/common/viewModel/characterHardWrappingLineMapper","vs/editor/common/viewModel/viewModelImpl","vs/editor/contrib/find/common/findDecorations","vs/base/common/diff/diffChange","vs/editor/contrib/folding/common/foldingModel","vs/editor/contrib/snippet/browser/snippetSession","vs/css!vs/editor/contrib/goToDeclaration/browser/messageController","vs/nls!vs/editor/common/modes/modesRegistry","vs/nls!vs/editor/common/services/bulkEdit","vs/editor/common/services/bulkEdit","vs/nls!vs/editor/common/services/modelServiceImpl","vs/nls!vs/editor/common/view/editorColorRegistry","vs/nls!vs/editor/contrib/bracketMatching/common/bracketMatching","vs/nls!vs/editor/contrib/caretOperations/common/caretOperations","vs/nls!vs/editor/contrib/caretOperations/common/transpose","vs/nls!vs/editor/contrib/clipboard/browser/clipboard","vs/nls!vs/editor/contrib/comment/common/comment","vs/nls!vs/editor/contrib/contextmenu/browser/contextmenu","vs/nls!vs/editor/contrib/find/browser/findWidget","vs/nls!vs/editor/contrib/find/common/findController","vs/nls!vs/editor/contrib/folding/browser/folding","vs/nls!vs/editor/contrib/format/browser/formatActions","vs/nls!vs/editor/contrib/goToDeclaration/browser/goToDeclarationCommands","vs/nls!vs/editor/contrib/goToDeclaration/browser/goToDeclarationMouse","vs/nls!vs/editor/contrib/gotoError/browser/gotoError","vs/nls!vs/editor/contrib/hover/browser/hover","vs/nls!vs/editor/contrib/hover/browser/modesContentHover","vs/nls!vs/editor/contrib/inPlaceReplace/common/inPlaceReplace","vs/nls!vs/editor/contrib/linesOperations/common/linesOperations","vs/nls!vs/editor/contrib/links/browser/links","vs/nls!vs/editor/contrib/multicursor/common/multicursor","vs/nls!vs/editor/contrib/parameterHints/browser/parameterHints","vs/nls!vs/editor/contrib/parameterHints/browser/parameterHintsWidget","vs/nls!vs/editor/contrib/quickFix/browser/quickFixCommands","vs/nls!vs/editor/contrib/referenceSearch/browser/referenceSearch","vs/nls!vs/editor/contrib/referenceSearch/browser/referencesController","vs/nls!vs/editor/contrib/referenceSearch/browser/referencesModel","vs/css!vs/editor/contrib/gotoError/browser/gotoError","vs/nls!vs/editor/contrib/referenceSearch/browser/referencesWidget","vs/nls!vs/editor/contrib/rename/browser/rename","vs/nls!vs/editor/contrib/rename/browser/renameInputField","vs/nls!vs/editor/contrib/smartSelect/common/smartSelect","vs/nls!vs/editor/contrib/suggest/browser/suggestController","vs/nls!vs/editor/contrib/suggest/browser/suggestWidget","vs/nls!vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode","vs/nls!vs/editor/contrib/wordHighlighter/common/wordHighlighter","vs/nls!vs/editor/contrib/zoneWidget/browser/peekViewWidget","vs/nls!vs/editor/standalone/browser/inspectTokens/inspectTokens","vs/nls!vs/editor/standalone/browser/quickOpen/gotoLine","vs/nls!vs/editor/standalone/browser/quickOpen/quickCommand","vs/nls!vs/editor/standalone/browser/quickOpen/quickOutline","vs/nls!vs/editor/standalone/browser/standaloneCodeEditor","vs/nls!vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast","vs/nls!vs/platform/configuration/common/configurationRegistry","vs/nls!vs/platform/keybinding/common/abstractKeybindingService","vs/nls!vs/platform/message/common/message","vs/nls!vs/platform/theme/common/colorRegistry","vs/platform/contextview/browser/contextMenuHandler","vs/platform/contextview/browser/contextMenuService","vs/css!vs/editor/contrib/hover/browser/hover","vs/css!vs/editor/contrib/links/browser/links","vs/css!vs/editor/contrib/parameterHints/browser/parameterHints","vs/css!vs/editor/contrib/quickFix/browser/lightBulbWidget","vs/css!vs/editor/contrib/referenceSearch/browser/referencesWidget","vs/css!vs/editor/contrib/rename/browser/renameInputField","vs/css!vs/editor/contrib/snippet/browser/snippetSession","vs/css!vs/editor/contrib/suggest/browser/media/suggest","vs/css!vs/editor/contrib/zoneWidget/browser/peekViewWidget","vs/editor/common/services/webWorker","vs/editor/contrib/smartSelect/common/tokenSelectionSupport","vs/css!vs/editor/contrib/zoneWidget/browser/zoneWidget","vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp","vs/editor/contrib/links/common/links","vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard","vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens","vs/css!vs/editor/standalone/browser/quickOpen/gotoLine","vs/css!vs/editor/standalone/browser/quickOpen/quickOutline","vs/editor/common/modes/editorModeContext","vs/platform/actions/common/menu","vs/css!vs/editor/standalone/browser/standalone-tokens","vs/css!vs/platform/contextview/browser/contextMenuHandler","vs/editor/browser/config/charWidthReader","vs/platform/files/common/files","vs/editor/browser/config/elementSizeObserver","vs/platform/instantiation/common/instantiationService","vs/platform/keybinding/common/abstractKeybindingService","vs/base/browser/ui/list/rangeMap","vs/base/browser/ui/list/rowCache","vs/platform/contextkey/browser/contextKeyService","vs/platform/keybinding/common/resolvedKeybindingItem","vs/platform/keybinding/common/usLayoutResolvedKeybinding","vs/platform/lifecycle/common/lifecycle","vs/platform/markers/common/markerService","vs/editor/standalone/browser/standaloneEditor","vs/base/common/scorer","vs/base/common/callbackList","vs/editor/contrib/hover/browser/modesGlyphHover","vs/base/common/stopwatch","vs/nls!vs/base/browser/ui/actionbar/actionbar","vs/base/common/graph","vs/base/browser/ui/scrollbar/scrollbarVisibilityController","vs/editor/common/services/modelServiceImpl","vs/editor/contrib/dnd/browser/dnd","vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard","vs/platform/jsonschemas/common/jsonContributionRegistry","vs/base/common/history","vs/editor/common/commands/trimTrailingWhitespaceCommand","vs/editor/common/services/languagesRegistry","vs/editor/common/services/modeServiceImpl","vs/platform/configuration/common/model","vs/base/browser/ui/scrollbar/horizontalScrollbar","vs/base/browser/ui/scrollbar/verticalScrollbar","vs/editor/common/commands/surroundSelectionCommand","vs/base/common/json","vs/editor/browser/view/viewOverlays","vs/editor/browser/viewParts/viewCursors/viewCursor","vs/base/parts/quickopen/browser/quickOpenViewer","vs/base/common/decorators","vs/editor/common/commonCodeEditor","vs/base/parts/tree/browser/tree","vs/editor/browser/view/viewController","vs/editor/contrib/caretOperations/common/caretOperations","vs/editor/contrib/caretOperations/common/transpose","vs/editor/contrib/clipboard/browser/clipboard","vs/editor/contrib/codelens/browser/codelens","vs/editor/contrib/comment/common/comment","vs/editor/contrib/contextmenu/browser/contextmenu","vs/editor/contrib/cursorUndo/browser/cursorUndo","vs/editor/common/diff/diffComputer","vs/editor/contrib/folding/browser/folding","vs/editor/contrib/format/common/format","vs/editor/contrib/format/browser/formatActions","vs/base/parts/tree/browser/treeDnd","vs/editor/contrib/hover/common/hover","vs/editor/contrib/hover/browser/modesContentHover","vs/editor/contrib/linesOperations/common/linesOperations","vs/editor/contrib/multicursor/common/multicursor","vs/base/parts/tree/browser/treeModel","vs/editor/contrib/quickFix/browser/quickFix","vs/editor/contrib/quickFix/browser/quickFixModel","vs/editor/contrib/quickFix/browser/quickFixCommands","vs/editor/contrib/quickOpen/common/quickOpen","vs/editor/contrib/smartSelect/common/smartSelect","vs/base/parts/tree/browser/treeViewModel","vs/base/worker/defaultWorkerFactory","vs/editor/contrib/suggest/browser/suggestModel","vs/editor/common/model/editStack","vs/editor/contrib/wordOperations/common/wordOperations","vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast","vs/platform/contextview/browser/contextViewService","vs/platform/telemetry/common/telemetryUtils","vs/platform/opener/browser/openerService","vs/editor/common/model/indentRanges","vs/editor/common/model/indentationGuesser","vs/editor/standalone/browser/quickOpen/quickOpenEditorWidget","vs/css!vs/base/browser/builder","vs/editor/browser/services/codeEditorServiceImpl","vs/editor/browser/viewParts/editorScrollbar/editorScrollbar","vs/base/common/marshalling","vs/base/common/hash","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/css!vs/base/browser/ui/actionbar/actionbar","vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight","vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight","vs/editor/browser/viewParts/indentGuides/indentGuides","vs/css!vs/base/browser/ui/aria/aria","vs/editor/browser/controller/textAreaHandler","vs/editor/browser/viewParts/rulers/rulers","vs/editor/browser/viewParts/viewCursors/viewCursors","vs/editor/browser/widget/diffReview","vs/css!vs/base/browser/ui/checkbox/checkbox","vs/base/browser/ui/checkbox/checkbox","vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler","vs/editor/browser/viewParts/overviewRuler/overviewRuler","vs/editor/browser/view/viewImpl","vs/css!vs/base/browser/ui/contextview/contextview","vs/editor/common/modes/abstractMode","vs/base/browser/ui/octiconLabel/octiconLabel","vs/editor/common/modes/languageSelector","vs/editor/contrib/bracketMatching/common/bracketMatching","vs/editor/contrib/codelens/browser/codelensWidget","vs/editor/contrib/codelens/browser/codelensController","vs/editor/contrib/colorPicker/browser/colorPicker","vs/editor/contrib/find/browser/findOptionsWidget","vs/editor/contrib/find/browser/findWidget","vs/editor/contrib/find/browser/find","vs/editor/contrib/goToDeclaration/browser/messageController","vs/editor/contrib/gotoError/browser/gotoError","vs/editor/contrib/hover/browser/hover","vs/editor/contrib/inPlaceReplace/common/inPlaceReplace","vs/editor/contrib/links/browser/links","vs/editor/contrib/parameterHints/browser/parameterHintsWidget","vs/editor/contrib/parameterHints/browser/parameterHints","vs/editor/contrib/rename/browser/renameInputField","vs/editor/contrib/rename/browser/rename","vs/editor/contrib/suggest/browser/suggestWidget","vs/editor/contrib/suggest/browser/suggestController","vs/editor/contrib/wordHighlighter/common/wordHighlighter","vs/editor/common/modes/languageFeatureRegistry","vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp","vs/editor/standalone/browser/inspectTokens/inspectTokens","vs/editor/common/modes/linkComputer","vs/editor/standalone/browser/quickOpen/gotoLine","vs/editor/standalone/browser/quickOpen/quickCommand","vs/editor/standalone/browser/quickOpen/quickOutline","vs/editor/standalone/browser/standaloneCodeEditor","vs/editor/standalone/common/themes","vs/editor/standalone/browser/standaloneThemeServiceImpl","vs/editor/common/modes/supports/characterPair","vs/editor/contrib/referenceSearch/browser/referencesWidget","vs/editor/common/modes/supports/indentRules","vs/editor/common/modes/supports/inplaceReplaceSupport","vs/editor/contrib/goToDeclaration/browser/goToDeclarationMouse","vs/editor/contrib/referenceSearch/browser/referenceSearch","vs/editor/editor.all","vs/editor/common/modes/supports/onEnter","vs/base/common/winjs.base.raw","vs/base/common/marked/raw.marked","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 = (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 = (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;
    function init() {
        define('vs/css', new CSSPlugin());
    }
    CSSLoaderPlugin.init = init;
    ;
    if (typeof doNotInitLoader === 'undefined') {
        init();
    }
})(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 = (function () {
       function Environment(isPseudo) {
           this.isPseudo = isPseudo;
           //
       }
       Environment.detect = function () {
           var isPseudo = (typeof document !== 'undefined' && document.location && document.location.hash.indexOf('pseudo=true') >= 0);
           return new Environment(isPseudo);
       };
       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];
               return typeof args[index] !== 'undefined' ? args[index] : match;
           });
       }
       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 = (function () {
       function NLSPlugin(env) {
           var _this = this;
           this._env = env;
           this.localize = function (data, message) {
               var args = [];
               for (var _i = 2; _i < arguments.length; _i++) {
                   args[_i - 2] = arguments[_i];
               }
               return localize.apply(void 0, [_this._env, data, message].concat(args));
           };
       }
       NLSPlugin.prototype.setPseudoTranslation = function (value) {
           this._env = new Environment(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;
               }
               req([name + suffix], function (messages) {
                   if (Array.isArray(messages)) {
                       messages.localize = createScopedLocalize(messages, _this._env);
                   }
                   else {
                       messages.localize = createScopedLocalize(messages[name], _this._env);
                   }
                   load(messages);
               });
           }
       };
       return NLSPlugin;
   }());
   NLSPlugin.DEFAULT_TAG = 'i-default';
   NLSLoaderPlugin.NLSPlugin = NLSPlugin;
   function init() {
       define('vs/nls', new NLSPlugin(Environment.detect()));
   }
   NLSLoaderPlugin.init = init;
   if (typeof doNotInitLoader === 'undefined') {
       init();
   }
})(NLSLoaderPlugin || (NLSLoaderPlugin = {}));

define(__m[148/*vs/base/browser/iframe*/], __M([1/*require*/,0/*exports*/]), 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 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 = (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, 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; i < windowChain.length; i++) {
                var windowChainEl = windowChain[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[415/*vs/base/browser/ui/list/rangeMap*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * Returns the intersection between two ranges as a range itself.
     * Returns `null` if the intersection is empty.
     */
    function intersect(one, other) {
        if (one.start >= other.end || other.start >= one.end) {
            return null;
        }
        var start = Math.max(one.start, other.start);
        var end = Math.min(one.end, other.end);
        if (end - start <= 0) {
            return null;
        }
        return { start: start, end: end };
    }
    exports.intersect = intersect;
    function isEmpty(range) {
        return range.end - range.start <= 0;
    }
    exports.isEmpty = isEmpty;
    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;
    }
    exports.relativeComplement = relativeComplement;
    function each(range, fn) {
        for (var i = range.start; i < range.end; i++) {
            fn(i);
        }
    }
    exports.each = each;
    /**
     * 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 = intersect(range, r.range);
            if (!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 };
    }
    /**
     * 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 = (function () {
        function RangeMap() {
            this.groups = [];
            this._size = 0;
        }
        RangeMap.prototype.splice = function (index, deleteCount) {
            var items = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                items[_i - 2] = arguments[_i];
            }
            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;
        };
        return RangeMap;
    }());
    exports.RangeMap = RangeMap;
});

define(__m[150/*vs/base/browser/ui/scrollbar/scrollbarState*/], __M([1/*require*/,0/*exports*/]), 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 });
    /**
     * The minimal size of the slider (such that it can still be clickable) -- it is artificially enlarged.
     */
    var MINIMUM_SLIDER_SIZE = 20;
    var ScrollbarState = (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;
        };
        ScrollbarState.prototype.getSliderCenter = function () {
            return (this._computedSliderPosition + this._computedSliderSize / 2);
        };
        /**
         * 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[33/*vs/base/common/arrays*/], __M([1/*require*/,0/*exports*/]), 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 });
    /**
     * 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 equals(one, other, itemEquals) {
        if (itemEquals === void 0) { itemEquals = function (a, b) { return a === b; }; }
        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 findFirst(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.findFirst = findFirst;
    /**
     * 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) {
        _divideAndMerge(data, compare);
        return data;
    }
    exports.mergeSort = mergeSort;
    function _divideAndMerge(data, compare) {
        if (data.length <= 1) {
            // sorted
            return;
        }
        var p = (data.length / 2) | 0;
        var left = data.slice(0, p);
        var right = data.slice(p);
        _divideAndMerge(left, compare);
        _divideAndMerge(right, compare);
        var leftIdx = 0;
        var rightIdx = 0;
        var i = 0;
        while (leftIdx < left.length && rightIdx < right.length) {
            var ret = compare(left[leftIdx], right[rightIdx]);
            if (ret <= 0) {
                // smaller_equal -> take left to preserve order
                data[i++] = left[leftIdx++];
            }
            else {
                // greater -> take right
                data[i++] = right[rightIdx++];
            }
        }
        while (leftIdx < left.length) {
            data[i++] = left[leftIdx++];
        }
        while (rightIdx < right.length) {
            data[i++] = right[rightIdx++];
        }
    }
    function groupBy(data, compare) {
        var result = [];
        var currentGroup;
        for (var _i = 0, _a = data.slice(0).sort(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;
    /**
     * Takes two *sorted* arrays and computes their delta (removed, added elements).
     * Finishes in `Math.min(before.length, after.length)` steps.
     * @param before
     * @param after
     * @param compare
     */
    function delta(before, after, compare) {
        var removed = [];
        var added = [];
        var beforeIdx = 0;
        var afterIdx = 0;
        while (true) {
            if (beforeIdx === before.length) {
                added.push.apply(added, after.slice(afterIdx));
                break;
            }
            if (afterIdx === after.length) {
                removed.push.apply(removed, before.slice(beforeIdx));
                break;
            }
            var beforeElement = before[beforeIdx];
            var afterElement = after[afterIdx];
            var n = compare(beforeElement, afterElement);
            if (n === 0) {
                // equal
                beforeIdx += 1;
                afterIdx += 1;
            }
            else if (n < 0) {
                // beforeElement is smaller -> before element removed
                removed.push(beforeElement);
                beforeIdx += 1;
            }
            else if (n > 0) {
                // beforeElement is greater -> after element added
                added.push(afterElement);
                afterIdx += 1;
            }
        }
        return { removed: removed, added: added };
    }
    exports.delta = delta;
    /**
     * Returns the top N elements from the array.
     *
     * Faster than sorting the entire array when the array is a lot larger than N.
     *
     * @param array The unsorted array.
     * @param compare A sort function for the elements.
     * @param n The number of elements to return.
     * @return The first n elemnts from array when sorted with compare.
     */
    function top(array, compare, n) {
        if (n === 0) {
            return [];
        }
        var result = array.slice(0, n).sort(compare);
        var _loop_1 = function (i, m) {
            var element = array[i];
            if (compare(element, result[n - 1]) < 0) {
                result.pop();
                var j = findFirst(result, function (e) { return compare(element, e) < 0; });
                result.splice(j, 0, element);
            }
        };
        for (var i = n, m = array.length; i < m; i++) {
            _loop_1(i, m);
        }
        return result;
    }
    exports.top = top;
    /**
     * @returns a new array with all undefined or null values removed. The original array is not modified at all.
     */
    function coalesce(array) {
        if (!array) {
            return array;
        }
        return array.filter(function (e) { return !!e; });
    }
    exports.coalesce = coalesce;
    /**
     * Moves the element in the array for the provided positions.
     */
    function move(array, from, to) {
        array.splice(to, 0, array.splice(from, 1)[0]);
    }
    exports.move = move;
    /**
     * @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;
    /**
     * 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 uniqueFilter(keyFn) {
        var seen = Object.create(null);
        return function (element) {
            var key = keyFn(element);
            if (seen[key]) {
                return false;
            }
            seen[key] = true;
            return true;
        };
    }
    exports.uniqueFilter = uniqueFilter;
    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 = null; }
        var index = firstIndex(array, fn);
        return index < 0 ? notFoundValue : array[index];
    }
    exports.first = first;
    function commonPrefixLength(one, other, equals) {
        if (equals === void 0) { equals = function (a, b) { return a === b; }; }
        var result = 0;
        for (var i = 0, len = Math.min(one.length, other.length); i < len && equals(one[i], other[i]); i++) {
            result++;
        }
        return result;
    }
    exports.commonPrefixLength = commonPrefixLength;
    function flatten(arr) {
        return arr.reduce(function (r, v) { return r.concat(v); }, []);
    }
    exports.flatten = flatten;
    function range(to, from) {
        if (from === void 0) { from = 0; }
        var result = [];
        for (var i = from; i < to; i++) {
            result.push(i);
        }
        return result;
    }
    exports.range = range;
    function fill(num, valueFn, arr) {
        if (arr === void 0) { arr = []; }
        for (var i = 0; i < num; i++) {
            arr[i] = valueFn();
        }
        return arr;
    }
    exports.fill = fill;
    function index(array, indexer, merger) {
        if (merger === void 0) { merger = function (t) { return t; }; }
        return array.reduce(function (r, t) {
            var key = indexer(t);
            r[key] = merger(t, r[key]);
            return r;
        }, Object.create(null));
    }
    exports.index = index;
    /**
     * Inserts an element into an array. Returns a function which, when
     * called, will remove that element from the array.
     */
    function insert(array, element) {
        array.push(element);
        return function () {
            var index = array.indexOf(element);
            if (index > -1) {
                array.splice(index, 1);
            }
        };
    }
    exports.insert = insert;
    /**
     * 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;
});

define(__m[72/*vs/base/common/assert*/], __M([1/*require*/,0/*exports*/]), 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 });
    /**
     * 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 || value === null) {
            throw new Error(message ? 'Assertion failed (' + message + ')' : 'Assertion Failed');
        }
    }
    exports.ok = ok;
});

define(__m[157/*vs/base/common/collections*/], __M([1/*require*/,0/*exports*/]), 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 hasOwnProperty = Object.prototype.hasOwnProperty;
    /**
     * Returns an array which contains all values that reside
     * in the given set.
     */
    function values(from) {
        var result = [];
        for (var key in from) {
            if (hasOwnProperty.call(from, key)) {
                result.push(from[key]);
            }
        }
        return result;
    }
    exports.values = values;
    function size(from) {
        var count = 0;
        for (var key in from) {
            if (hasOwnProperty.call(from, key)) {
                count += 1;
            }
        }
        return count;
    }
    exports.size = size;
    /**
     * 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;
    /**
     * Removes an element from the dictionary. Returns {{false}} if the property
     * does not exists.
     */
    function remove(from, key) {
        if (!hasOwnProperty.call(from, key)) {
            return false;
        }
        delete from[key];
        return true;
    }
    exports.remove = remove;
    /**
     * Groups the collection into a dictionary based on the provided
     * group function.
     */
    function groupBy(data, groupFn) {
        var result = Object.create(null);
        for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
            var element = data_1[_i];
            var key = groupFn(element);
            var target = result[key];
            if (!target) {
                target = result[key] = [];
            }
            target.push(element);
        }
        return result;
    }
    exports.groupBy = groupBy;
});

/*---------------------------------------------------------------------------------------------
 *  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/base/common/color*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var RGBA = (function () {
        function RGBA(r, g, b, a) {
            if (a === void 0) { a = 255; }
            this.r = RGBA._clampInt_0_255(r);
            this.g = RGBA._clampInt_0_255(g);
            this.b = RGBA._clampInt_0_255(b);
            this.a = RGBA._clampInt_0_255(a);
        }
        RGBA.equals = function (a, b) {
            return (a.r === b.r
                && a.g === b.g
                && a.b === b.b
                && a.a === b.a);
        };
        RGBA._clampInt_0_255 = function (c) {
            if (c < 0) {
                return 0;
            }
            if (c > 255) {
                return 255;
            }
            return c | 0;
        };
        RGBA.prototype.toString = function () {
            if (this.a === 255) {
                return "rgb(" + this.r + ", " + this.g + ", " + this.b + ")";
            }
            return "rgba(" + this.r + ", " + this.g + ", " + this.b + ", " + (this.a / 255).toFixed(2) + ")";
        };
        return RGBA;
    }());
    exports.RGBA = RGBA;
    /**
     * http://en.wikipedia.org/wiki/HSL_color_space
     */
    var HSLA = (function () {
        function HSLA(h, s, l, a) {
            this.h = HSLA._clampFloat_0_360(h);
            this.s = HSLA._clampFloat_0_1(s);
            this.l = HSLA._clampFloat_0_1(l);
            this.a = HSLA._clampFloat_0_1(a);
        }
        HSLA._clampFloat_0_360 = function (hue) {
            if (hue < 0) {
                return 0.0;
            }
            if (hue > 360) {
                return 360.0;
            }
            return hue;
        };
        HSLA._clampFloat_0_1 = function (n) {
            if (n < 0) {
                return 0.0;
            }
            if (n > 1) {
                return 1.0;
            }
            return n;
        };
        HSLA.prototype.toString = function () {
            var s = (this.s * 100).toFixed(2);
            var l = (this.l * 100).toFixed(2);
            if (this.a === 1) {
                return "hsl(" + this.h + ", " + s + "%, " + l + "%)";
            }
            return "hsla(" + this.h + ", " + s + "%, " + l + "%, " + this.a.toFixed(2) + ")";
        };
        return HSLA;
    }());
    exports.HSLA = HSLA;
    /**
     * Converts an Hex color value to RGB.
     * returns r, g, and b are contained in the set [0, 255]
     * @param hex string (#RGB, #RGBA, #RRGGBB or #RRGGBBAA).
     */
    function hex2rgba(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 RGBA(r, g, b, 255);
        }
        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 RGBA(r, g, b, a);
        }
        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 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 RGBA(16 * r + r, 16 * g + g, 16 * b + b, 16 * a + a);
        }
        // Invalid color
        return null;
    }
    var colorPattern = /^#[0-9A-Fa-f]{3,8}$/i;
    function isValidHexColor(hex) {
        return colorPattern.test(hex) && hex.length !== 6 && hex.length !== 8;
    }
    exports.isValidHexColor = isValidHexColor;
    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;
    }
    /**
     * 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].
     */
    function rgba2hsla(rgba) {
        var r = rgba.r / 255;
        var g = rgba.g / 255;
        var b = rgba.b / 255;
        var a = rgba.a / 255;
        var max = Math.max(r, g, b);
        var min = Math.min(r, g, b);
        var h = 0;
        var s = 0;
        var l = Math.round(((min + max) / 2) * 1000) / 1000;
        var chroma = max - min;
        if (chroma > 0) {
            s = Math.min(Math.round((l <= 0.5 ? chroma / (2 * l) : chroma / (2 - (2 * l))) * 1000) / 1000, 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);
    }
    /**
     * 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].
     */
    function hsla2rgba(hsla) {
        var h = hsla.h / 360;
        var s = Math.min(hsla.s, 1);
        var l = Math.min(hsla.l, 1);
        var 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 = _hue2rgb(p, q, h + 1 / 3);
            g = _hue2rgb(p, q, h);
            b = _hue2rgb(p, q, h - 1 / 3);
        }
        return new RGBA(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), Math.round(a * 255));
    }
    function _hue2rgb(p, q, t) {
        if (t < 0) {
            t += 1;
        }
        if (t > 1) {
            t -= 1;
        }
        if (t < 1 / 6) {
            return p + (q - p) * 6 * t;
        }
        if (t < 1 / 2) {
            return q;
        }
        if (t < 2 / 3) {
            return p + (q - p) * (2 / 3 - t) * 6;
        }
        return p;
    }
    var Color = (function () {
        function Color(arg) {
            this.rgba = arg;
        }
        Color.fromRGBA = function (rgba) {
            return new Color(rgba);
        };
        /**
         * Creates a color from a hex string (#RRGGBB or #RRGGBBAA).
         */
        Color.fromHex = function (hex, parseErrorColor) {
            if (parseErrorColor === void 0) { parseErrorColor = Color.red; }
            var rgba = hex2rgba(hex);
            if (rgba) {
                return new Color(rgba);
            }
            return parseErrorColor;
        };
        Color.fromHSLA = function (hsla) {
            return new Color(hsla2rgba(hsla));
        };
        /**
         *	Creates a color from HSV values
         *	hue [0..360)
         *	saturation [0..1]
         *	value [0..1]
         */
        Color.fromHSV = function (hue, saturation, value, opacity, parseErrorColor) {
            if (opacity === void 0) { opacity = 255; }
            if (parseErrorColor === void 0) { parseErrorColor = Color.red; }
            if (hue < 0 || hue >= 360 || saturation < 0 || saturation > 1 || value < 0 || value > 1) {
                return parseErrorColor;
            }
            var c = value * saturation;
            var x = c * (1 - Math.abs((hue / 60) % 2 - 1));
            var m = value - c;
            var _a = [0, 0, 0], red = _a[0], green = _a[1], blue = _a[2];
            if (hue < 60) {
                red = c;
                green = x;
            }
            else if (hue < 120) {
                red = x;
                green = c;
            }
            else if (hue < 180) {
                green = c;
                blue = x;
            }
            else if (hue < 240) {
                green = x;
                blue = c;
            }
            else if (hue < 300) {
                red = x;
                blue = c;
            }
            else if (hue < 360) {
                red = c;
                blue = x;
            }
            red = (red + m) * 255;
            green = (green + m) * 255;
            blue = (blue + m) * 255;
            return Color.fromRGBA(new RGBA(red, green, blue, opacity));
        };
        Color.prototype.equals = function (other) {
            if (!other) {
                return false;
            }
            return RGBA.equals(this.rgba, other.rgba);
        };
        /**
         * http://www.w3.org/TR/WCAG20/#relativeluminancedef
         * Returns the number in the set [0, 1]. O => Darkest Black. 1 => Lightest white.
         */
        Color.prototype.getLuminosity = function () {
            var R = Color._luminosityFor(this.rgba.r);
            var G = Color._luminosityFor(this.rgba.g);
            var B = Color._luminosityFor(this.rgba.b);
            var luminosity = 0.2126 * R + 0.7152 * G + 0.0722 * B;
            return Math.round(luminosity * 10000) / 10000;
        };
        Color._luminosityFor = function (color) {
            var c = color / 255;
            return (c <= 0.03928) ? c / 12.92 : Math.pow(((c + 0.055) / 1.055), 2.4);
        };
        /**
         * http://www.w3.org/TR/WCAG20/#contrast-ratiodef
         * Returns the contrast ration number in the set [1, 21].
         */
        Color.prototype.getContrast = function (another) {
            var lum1 = this.getLuminosity();
            var lum2 = another.getLuminosity();
            return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05);
        };
        Color.prototype.getHue = function () {
            var _a = [this.rgba.r / 255, this.rgba.g / 255, this.rgba.b / 255], r = _a[0], g = _a[1], b = _a[2];
            var cmax = Math.max(r, g, b);
            var cmin = Math.min(r, g, b);
            var delta = cmax - cmin;
            var hue;
            if (delta === 0) {
                hue = 0;
            }
            else if (cmax === r) {
                hue = 60 * (((g - b) / delta) % 6);
            }
            else if (cmax === g) {
                hue = 60 * (((b - r) / delta) + 2);
            }
            else {
                hue = 60 * (((r - g) / delta) + 4);
            }
            if (hue < 0) {
                hue += 360;
            }
            return hue;
        };
        Color.prototype.getSaturation = function () {
            var _a = [this.rgba.r / 255, this.rgba.g / 255, this.rgba.b / 255], r = _a[0], g = _a[1], b = _a[2];
            var cmax = Math.max(r, g, b);
            var cmin = Math.min(r, g, b);
            if (cmax === 0) {
                return 0;
            }
            return (cmax - cmin) / cmax;
        };
        Color.prototype.getValue = function () {
            return Math.max(this.rgba.r / 255, this.rgba.g / 255, this.rgba.b / 255);
        };
        /**
         *	http://24ways.org/2010/calculating-color-contrast
         *  Return 'true' if darker color otherwise 'false'
         */
        Color.prototype.isDarker = function () {
            var yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1000;
            return yiq < 128;
        };
        /**
         *	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.getLuminosity();
            var lum2 = another.getLuminosity();
            return lum1 > lum2;
        };
        Color.prototype.isDarkerThan = function (another) {
            var lum1 = this.getLuminosity();
            var lum2 = another.getLuminosity();
            return lum1 < lum2;
        };
        Color.prototype.lighten = function (factor) {
            var hsl = this.toHSLA();
            var result = new HSLA(hsl.h, hsl.s, hsl.l + hsl.l * factor, hsl.a);
            return new Color(hsla2rgba(result));
        };
        Color.prototype.darken = function (factor) {
            var hsl = this.toHSLA();
            var result = new HSLA(hsl.h, hsl.s, hsl.l - hsl.l * factor, hsl.a);
            return new Color(hsla2rgba(result));
        };
        Color.prototype.transparent = function (factor) {
            var p = this.rgba;
            return new Color(new RGBA(p.r, p.g, p.b, Math.round(p.a * factor)));
        };
        Color.prototype.isTransparent = function () {
            return this.rgba.a === 0;
        };
        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.blend = function (c) {
            var color = c.toRGBA();
            // Convert to 0..1 opacity
            var thisA = this.rgba.a / 255;
            var colorA = color.a / 255;
            var a = thisA + colorA * (1 - thisA);
            if (a < 1.0e-6) {
                return Color.transparent;
            }
            var r = this.rgba.r * thisA / a + color.r * colorA * (1 - thisA) / a;
            var g = this.rgba.g * thisA / a + color.g * colorA * (1 - thisA) / a;
            var b = this.rgba.b * thisA / a + color.b * colorA * (1 - thisA) / a;
            a *= 255;
            return new Color(new RGBA(r, g, b, a));
        };
        Color.prototype.toString = function () {
            var rgba = this.rgba;
            if (rgba.a === 255) {
                return this.toRGBHex();
            }
            return "rgba(" + rgba.r + ", " + rgba.g + ", " + rgba.b + ", " + +(rgba.a / 255).toFixed(2) + ")";
        };
        /**
         * Prins the color as #RRGGBB
         */
        Color.prototype.toRGBHex = function () {
            var rgba = this.rgba;
            return "#" + Color._toTwoDigitHex(rgba.r) + Color._toTwoDigitHex(rgba.g) + Color._toTwoDigitHex(rgba.b);
        };
        /**
         * Prins the color as #RRGGBBAA
         * If 'compact' is set, colors without transparancy will be printed as #RRGGBB
         */
        Color.prototype.toRGBAHex = function (compact) {
            if (compact === void 0) { compact = false; }
            var rgba = this.rgba;
            if (compact && rgba.a === 0xFF) {
                return this.toRGBHex();
            }
            return "#" + Color._toTwoDigitHex(rgba.r) + Color._toTwoDigitHex(rgba.g) + Color._toTwoDigitHex(rgba.b) + Color._toTwoDigitHex(rgba.a);
        };
        Color._toTwoDigitHex = function (n) {
            var r = n.toString(16);
            if (r.length !== 2) {
                return '0' + r;
            }
            return r;
        };
        Color.prototype.toHSLA = function () {
            return rgba2hsla(this.rgba);
        };
        Color.prototype.toRGBA = function () {
            return this.rgba;
        };
        Color.getLighterColor = function (of, relative, factor) {
            if (of.isLighterThan(relative)) {
                return of;
            }
            factor = factor ? factor : 0.5;
            var lum1 = of.getLuminosity();
            var lum2 = relative.getLuminosity();
            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.getLuminosity();
            var lum2 = relative.getLuminosity();
            factor = factor * (lum1 - lum2) / lum1;
            return of.darken(factor);
        };
        Color.white = new Color(new RGBA(255, 255, 255, 255));
        Color.black = new Color(new RGBA(0, 0, 0, 255));
        Color.red = new Color(new RGBA(255, 0, 0, 255));
        Color.blue = new Color(new RGBA(0, 0, 255, 255));
        Color.green = new Color(new RGBA(0, 255, 0, 255));
        Color.cyan = new Color(new RGBA(0, 255, 255, 255));
        Color.lightgrey = new Color(new RGBA(211, 211, 211, 255));
        Color.transparent = new Color(new RGBA(0, 0, 0, 0));
        return Color;
    }());
    exports.Color = Color;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[446/*vs/base/common/decorators*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function createDecorator(mapFn) {
        return function (target, key, descriptor) {
            var fnKey = null;
            var fn = null;
            if (typeof descriptor.value === 'function') {
                fnKey = 'value';
                fn = descriptor.value;
            }
            else if (typeof descriptor.get === 'function') {
                fnKey = 'get';
                fn = descriptor.get;
            }
            if (!fn) {
                throw new Error('not supported');
            }
            descriptor[fnKey] = mapFn(fn);
        };
    }
    exports.createDecorator = createDecorator;
    function memoize(target, key, descriptor) {
        var fnKey = null;
        var fn = null;
        if (typeof descriptor.value === 'function') {
            fnKey = 'value';
            fn = descriptor.value;
        }
        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;
});

define(__m[332/*vs/base/common/diff/diffChange*/], __M([1/*require*/,0/*exports*/]), 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 });
    exports.DifferenceType = {
        Add: 0,
        Remove: 1,
        Change: 2
    };
    /**
     * Represents information about a specific difference between two sequences.
     */
    var DiffChange = (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 type of difference.
         */
        DiffChange.prototype.getChangeType = function () {
            if (this.originalLength === 0) {
                return exports.DifferenceType.Add;
            }
            else if (this.modifiedLength === 0) {
                return exports.DifferenceType.Remove;
            }
            else {
                return exports.DifferenceType.Change;
            }
        };
        /**
         * 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;
});

define(__m[139/*vs/base/common/diff/diff*/], __M([1/*require*/,0/*exports*/,332/*vs/base/common/diff/diffChange*/]), function (require, exports, diffChange_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function createStringSequence(a) {
        return {
            getLength: function () { return a.length; },
            getElementHash: function (pos) { return a[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 = (function () {
        function Debug() {
        }
        Debug.Assert = function (condition, message) {
            if (!condition) {
                throw new Error(message);
            }
        };
        return Debug;
    }());
    exports.Debug = Debug;
    var MyArray = (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 letiations" 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 = (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;
    }());
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    /**
     * An implementation of the difference algorithm described in
     * "An O(ND) Difference Algorithm and its letiations" by Eugene W. Myers
     */
    var LcsDiff = (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_originalIds = [];
            this.m_modifiedIds = [];
            this.m_forwardHistory = [];
            this.m_reverseHistory = [];
            this.ComputeUniqueIdentifiers();
        }
        LcsDiff.prototype.ComputeUniqueIdentifiers = function () {
            var originalSequenceLength = this.OriginalSequence.getLength();
            var modifiedSequenceLength = this.ModifiedSequence.getLength();
            this.m_originalIds = new Array(originalSequenceLength);
            this.m_modifiedIds = new Array(modifiedSequenceLength);
            // Create a new hash table for unique elements from the original
            // sequence.
            var hashTable = {};
            var currentUniqueId = 1;
            var i;
            // Fill up the hash table for unique elements
            for (i = 0; i < originalSequenceLength; i++) {
                var originalElementHash = this.OriginalSequence.getElementHash(i);
                if (!hasOwnProperty.call(hashTable, originalElementHash)) {
                    // No entry in the hashtable so this is a new unique element.
                    // Assign the element a new unique identifier and add it to the
                    // hash table
                    this.m_originalIds[i] = currentUniqueId++;
                    hashTable[originalElementHash] = this.m_originalIds[i];
                }
                else {
                    this.m_originalIds[i] = hashTable[originalElementHash];
                }
            }
            // Now match up modified elements
            for (i = 0; i < modifiedSequenceLength; i++) {
                var modifiedElementHash = this.ModifiedSequence.getElementHash(i);
                if (!hasOwnProperty.call(hashTable, modifiedElementHash)) {
                    this.m_modifiedIds[i] = currentUniqueId++;
                    hashTable[modifiedElementHash] = this.m_modifiedIds[i];
                }
                else {
                    this.m_modifiedIds[i] = hashTable[modifiedElementHash];
                }
            }
        };
        LcsDiff.prototype.ElementsAreEqual = function (originalIndex, newIndex) {
            return this.m_originalIds[originalIndex] === this.m_modifiedIds[newIndex];
        };
        LcsDiff.prototype.OriginalElementsAreEqual = function (index1, index2) {
            return this.m_originalIds[index1] === this.m_originalIds[index2];
        };
        LcsDiff.prototype.ModifiedElementsAreEqual = function (index1, index2) {
            return this.m_modifiedIds[index1] === this.m_modifiedIds[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.ShiftChanges(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, modifiedIndex;
            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.ShiftChanges = function (changes) {
            var mergedDiffs;
            do {
                mergedDiffs = false;
                // 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++;
                    }
                }
                // Build up the new list (we have to build a new list because we
                // might have changes we can merge together now)
                var result = new Array();
                var mergedChangeArr = [null];
                for (var i = 0; i < changes.length; i++) {
                    if (i < changes.length - 1 && this.ChangesOverlap(changes[i], changes[i + 1], mergedChangeArr)) {
                        mergedDiffs = true;
                        result.push(mergedChangeArr[0]);
                        i++;
                    }
                    else {
                        result.push(changes[i]);
                    }
                }
                changes = result;
            } while (mergedDiffs);
            // 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 < modifiedStart) {
                        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;
            }
            return /^\s*$/.test(this.OriginalSequence.getElementHash(index));
        };
        LcsDiff.prototype._OriginalRegionIsBoundary = function (originalStart, originalLength) {
            if (this._OriginalIsBoundary(originalStart) || this._OriginalIsBoundary(originalStart - 1)) {
                return true;
            }
            if (originalLength > 0) {
                var originalEnd = originalStart + originalLength;
                if (this._OriginalIsBoundary(originalEnd - 1) || this._OriginalIsBoundary(originalEnd)) {
                    return true;
                }
            }
            return false;
        };
        LcsDiff.prototype._ModifiedIsBoundary = function (index) {
            if (index <= 0 || index >= this.ModifiedSequence.getLength() - 1) {
                return true;
            }
            return /^\s*$/.test(this.ModifiedSequence.getElementHash(index));
        };
        LcsDiff.prototype._ModifiedRegionIsBoundary = function (modifiedStart, modifiedLength) {
            if (this._ModifiedIsBoundary(modifiedStart) || this._ModifiedIsBoundary(modifiedStart - 1)) {
                return true;
            }
            if (modifiedLength > 0) {
                var modifiedEnd = modifiedStart + modifiedLength;
                if (this._ModifiedIsBoundary(modifiedEnd - 1) || this._ModifiedIsBoundary(modifiedEnd)) {
                    return true;
                }
            }
            return false;
        };
        LcsDiff.prototype._boundaryScore = function (originalStart, originalLength, modifiedStart, modifiedLength) {
            var originalScore = (this._OriginalRegionIsBoundary(originalStart, originalLength) ? 1 : 0);
            var modifiedScore = (this._ModifiedRegionIsBoundary(modifiedStart, modifiedLength) ? 1 : 0);
            return (originalScore + modifiedScore);
        };
        /**
         * Concatenates the two input DiffChange lists and returns the resulting
         * list.
         * @param The left changes
         * @param The right changes
         * @returns The concatenated list
         */
        LcsDiff.prototype.ConcatenateChanges = function (left, right) {
            var mergedChangeArr = [];
            var result = null;
            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
                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 {
                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;
});

var __extends = (this && this.__extends) || (function () {
    var 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 function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
define(__m[79/*vs/base/common/events*/], __M([1/*require*/,0/*exports*/]), 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 Event = (function () {
        function Event(originalEvent) {
            this.time = (new Date()).getTime();
            this.originalEvent = originalEvent;
            this.source = null;
        }
        return Event;
    }());
    exports.Event = Event;
    var PropertyChangeEvent = (function (_super) {
        __extends(PropertyChangeEvent, _super);
        function PropertyChangeEvent(key, oldValue, newValue, originalEvent) {
            var _this = _super.call(this, originalEvent) || this;
            _this.key = key;
            _this.oldValue = oldValue;
            _this.newValue = newValue;
            return _this;
        }
        return PropertyChangeEvent;
    }(Event));
    exports.PropertyChangeEvent = PropertyChangeEvent;
    var ViewerEvent = (function (_super) {
        __extends(ViewerEvent, _super);
        function ViewerEvent(element, originalEvent) {
            var _this = _super.call(this, originalEvent) || this;
            _this.element = element;
            return _this;
        }
        return ViewerEvent;
    }(Event));
    exports.ViewerEvent = ViewerEvent;
    exports.EventType = {
        PROPERTY_CHANGED: 'propertyChanged',
        SELECTION: 'selection',
        FOCUS: 'focus',
        BLUR: 'blur',
        HIGHLIGHT: 'highlight',
        EXPAND: 'expand',
        COLLAPSE: 'collapse',
        TOGGLE: 'toggle',
        BEFORE_RUN: 'beforeRun',
        RUN: 'run',
        EDIT: 'edit',
        SAVE: 'save',
        CANCEL: 'cancel',
        CHANGE: 'change',
        DISPOSE: '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[136/*vs/base/common/functional*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function not(fn) {
        return function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return !fn.apply(void 0, args);
        };
    }
    exports.not = not;
    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;
});

define(__m[488/*vs/base/common/hash*/], __M([1/*require*/,0/*exports*/]), 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 });
    /**
     * 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(obj, 937);
            default:
                return numberHash(obj, 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[133/*vs/base/common/htmlContent*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function markedStringsEquals(a, b) {
        if (!a && !b) {
            return true;
        }
        if (!a || !b) {
            return false;
        }
        if (Array.isArray(a)) {
            if (!Array.isArray(b)) {
                return false;
            }
            return markedStringArrEquals(a, b);
        }
        return markedStringEqual(a, b);
    }
    exports.markedStringsEquals = markedStringsEquals;
    function markedStringArrEquals(a, b) {
        var aLen = a.length, bLen = b.length;
        if (aLen !== bLen) {
            return false;
        }
        for (var i = 0; i < aLen; i++) {
            if (!markedStringEqual(a[i], b[i])) {
                return false;
            }
        }
        return true;
    }
    function markedStringEqual(a, b) {
        if (!a && !b) {
            return true;
        }
        if (!a || !b) {
            return false;
        }
        if (typeof a === 'string' || typeof b === 'string') {
            return typeof a === 'string' && typeof b === 'string' && a === b;
        }
        return (a.language === b.language
            && a.value === b.value);
    }
    function textToMarkedString(text) {
        return text.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
    }
    exports.textToMarkedString = textToMarkedString;
    function removeMarkdownEscapes(text) {
        if (!text) {
            return text;
        }
        return text.replace(/\\([\\`*_{}[\]()#+\-.!])/g, '$1');
    }
    exports.removeMarkdownEscapes = removeMarkdownEscapes;
});

define(__m[108/*vs/base/common/idGenerator*/], __M([1/*require*/,0/*exports*/]), 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 IdGenerator = (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.
 *--------------------------------------------------------------------------------------------*/










define(__m[107/*vs/base/common/iterator*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ArrayIterator = (function () {
        function ArrayIterator(items, start, end) {
            if (start === void 0) { start = 0; }
            if (end === void 0) { end = items.length; }
            this.items = items;
            this.start = start;
            this.end = end;
            this.index = start - 1;
        }
        ArrayIterator.prototype.first = function () {
            this.index = this.start;
            return this.current();
        };
        ArrayIterator.prototype.next = function () {
            this.index = Math.min(this.index + 1, this.end);
            return this.current();
        };
        ArrayIterator.prototype.current = function () {
            if (this.index === this.start - 1 || this.index === this.end) {
                return null;
            }
            return this.items[this.index];
        };
        return ArrayIterator;
    }());
    exports.ArrayIterator = ArrayIterator;
    var ArrayNavigator = (function (_super) {
        __extends(ArrayNavigator, _super);
        function ArrayNavigator(items, start, end) {
            if (start === void 0) { start = 0; }
            if (end === void 0) { end = items.length; }
            return _super.call(this, items, start, end) || 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 = (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;
    var MappedNavigator = (function (_super) {
        __extends(MappedNavigator, _super);
        function MappedNavigator(navigator, fn) {
            var _this = _super.call(this, navigator, fn) || this;
            _this.navigator = navigator;
            return _this;
        }
        MappedNavigator.prototype.current = function () { return this.fn(this.navigator.current()); };
        MappedNavigator.prototype.previous = function () { return this.fn(this.navigator.previous()); };
        MappedNavigator.prototype.parent = function () { return this.fn(this.navigator.parent()); };
        MappedNavigator.prototype.first = function () { return this.fn(this.navigator.first()); };
        MappedNavigator.prototype.last = function () { return this.fn(this.navigator.last()); };
        MappedNavigator.prototype.next = function () { return this.fn(this.navigator.next()); };
        return MappedNavigator;
    }(MappedIterator));
    exports.MappedNavigator = MappedNavigator;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[434/*vs/base/common/history*/], __M([1/*require*/,0/*exports*/,107/*vs/base/common/iterator*/]), function (require, exports, iterator_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var HistoryNavigator = (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.getHistory = function () {
            return this._elements;
        };
        HistoryNavigator.prototype.add = function (t) {
            this._history.add(t);
            this._onChange();
        };
        HistoryNavigator.prototype.addIfNotPresent = function (t) {
            if (!this._history.has(t)) {
                this.add(t);
            }
        };
        HistoryNavigator.prototype.next = function () {
            if (this._navigator.next()) {
                return this._navigator.current();
            }
            this.last();
            return null;
        };
        HistoryNavigator.prototype.previous = function () {
            if (this._navigator.previous()) {
                return this._navigator.current();
            }
            this.first();
            return null;
        };
        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._onChange = function () {
            this._reduceToLimit();
            this._navigator = new iterator_1.ArrayNavigator(this._elements);
            this._navigator.last();
        };
        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;
});

define(__m[442/*vs/base/common/json*/], __M([1/*require*/,0/*exports*/]), 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 ScanError;
    (function (ScanError) {
        ScanError[ScanError["None"] = 0] = "None";
        ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
        ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
        ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
        ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode";
        ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
        ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter";
    })(ScanError = exports.ScanError || (exports.ScanError = {}));
    var SyntaxKind;
    (function (SyntaxKind) {
        SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
        SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken";
        SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken";
        SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken";
        SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken";
        SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken";
        SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken";
        SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword";
        SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword";
        SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword";
        SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
        SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral";
        SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia";
        SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
        SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia";
        SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia";
        SyntaxKind[SyntaxKind["EOF"] = 16] = "EOF";
    })(SyntaxKind = exports.SyntaxKind || (exports.SyntaxKind = {}));
    /**
     * Creates a JSON scanner on the given text.
     * If ignoreTrivia is set, whitespaces or comments are ignored.
     */
    function createScanner(text, ignoreTrivia) {
        if (ignoreTrivia === void 0) { ignoreTrivia = false; }
        var pos = 0, len = text.length, value = '', tokenOffset = 0, token = SyntaxKind.Unknown, scanError = ScanError.None;
        function scanHexDigits(count, exact) {
            var digits = 0;
            var value = 0;
            while (digits < count || !exact) {
                var ch = text.charCodeAt(pos);
                if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
                    value = value * 16 + ch - 48 /* _0 */;
                }
                else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
                    value = value * 16 + ch - 65 /* A */ + 10;
                }
                else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
                    value = value * 16 + ch - 97 /* a */ + 10;
                }
                else {
                    break;
                }
                pos++;
                digits++;
            }
            if (digits < count) {
                value = -1;
            }
            return value;
        }
        function setPosition(newPosition) {
            pos = newPosition;
            value = '';
            tokenOffset = 0;
            token = SyntaxKind.Unknown;
            scanError = ScanError.None;
        }
        function scanNumber() {
            var start = pos;
            if (text.charCodeAt(pos) === 48 /* _0 */) {
                pos++;
            }
            else {
                pos++;
                while (pos < text.length && isDigit(text.charCodeAt(pos))) {
                    pos++;
                }
            }
            if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
                pos++;
                if (pos < text.length && isDigit(text.charCodeAt(pos))) {
                    pos++;
                    while (pos < text.length && isDigit(text.charCodeAt(pos))) {
                        pos++;
                    }
                }
                else {
                    scanError = ScanError.UnexpectedEndOfNumber;
                    return text.substring(start, pos);
                }
            }
            var end = pos;
            if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
                pos++;
                if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
                    pos++;
                }
                if (pos < text.length && isDigit(text.charCodeAt(pos))) {
                    pos++;
                    while (pos < text.length && isDigit(text.charCodeAt(pos))) {
                        pos++;
                    }
                    end = pos;
                }
                else {
                    scanError = ScanError.UnexpectedEndOfNumber;
                }
            }
            return text.substring(start, end);
        }
        function scanString() {
            var result = '', start = pos;
            while (true) {
                if (pos >= len) {
                    result += text.substring(start, pos);
                    scanError = ScanError.UnexpectedEndOfString;
                    break;
                }
                var ch = text.charCodeAt(pos);
                if (ch === 34 /* doubleQuote */) {
                    result += text.substring(start, pos);
                    pos++;
                    break;
                }
                if (ch === 92 /* backslash */) {
                    result += text.substring(start, pos);
                    pos++;
                    if (pos >= len) {
                        scanError = ScanError.UnexpectedEndOfString;
                        break;
                    }
                    ch = text.charCodeAt(pos++);
                    switch (ch) {
                        case 34 /* doubleQuote */:
                            result += '\"';
                            break;
                        case 92 /* backslash */:
                            result += '\\';
                            break;
                        case 47 /* slash */:
                            result += '/';
                            break;
                        case 98 /* b */:
                            result += '\b';
                            break;
                        case 102 /* f */:
                            result += '\f';
                            break;
                        case 110 /* n */:
                            result += '\n';
                            break;
                        case 114 /* r */:
                            result += '\r';
                            break;
                        case 116 /* t */:
                            result += '\t';
                            break;
                        case 117 /* u */:
                            var ch_1 = scanHexDigits(4, true);
                            if (ch_1 >= 0) {
                                result += String.fromCharCode(ch_1);
                            }
                            else {
                                scanError = ScanError.InvalidUnicode;
                            }
                            break;
                        default:
                            scanError = ScanError.InvalidEscapeCharacter;
                    }
                    start = pos;
                    continue;
                }
                if (ch >= 0 && ch <= 0x1f) {
                    if (isLineBreak(ch)) {
                        result += text.substring(start, pos);
                        scanError = ScanError.UnexpectedEndOfString;
                        break;
                    }
                    else {
                        scanError = ScanError.InvalidCharacter;
                        // mark as error but continue with string
                    }
                }
                pos++;
            }
            return result;
        }
        function scanNext() {
            value = '';
            scanError = ScanError.None;
            tokenOffset = pos;
            if (pos >= len) {
                // at the end
                tokenOffset = len;
                return token = SyntaxKind.EOF;
            }
            var code = text.charCodeAt(pos);
            // trivia: whitespace
            if (isWhiteSpace(code)) {
                do {
                    pos++;
                    value += String.fromCharCode(code);
                    code = text.charCodeAt(pos);
                } while (isWhiteSpace(code));
                return token = SyntaxKind.Trivia;
            }
            // trivia: newlines
            if (isLineBreak(code)) {
                pos++;
                value += String.fromCharCode(code);
                if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
                    pos++;
                    value += '\n';
                }
                return token = SyntaxKind.LineBreakTrivia;
            }
            switch (code) {
                // tokens: []{}:,
                case 123 /* openBrace */:
                    pos++;
                    return token = SyntaxKind.OpenBraceToken;
                case 125 /* closeBrace */:
                    pos++;
                    return token = SyntaxKind.CloseBraceToken;
                case 91 /* openBracket */:
                    pos++;
                    return token = SyntaxKind.OpenBracketToken;
                case 93 /* closeBracket */:
                    pos++;
                    return token = SyntaxKind.CloseBracketToken;
                case 58 /* colon */:
                    pos++;
                    return token = SyntaxKind.ColonToken;
                case 44 /* comma */:
                    pos++;
                    return token = SyntaxKind.CommaToken;
                // strings
                case 34 /* doubleQuote */:
                    pos++;
                    value = scanString();
                    return token = SyntaxKind.StringLiteral;
                // comments
                case 47 /* slash */:
                    var start = pos - 1;
                    // Single-line comment
                    if (text.charCodeAt(pos + 1) === 47 /* slash */) {
                        pos += 2;
                        while (pos < len) {
                            if (isLineBreak(text.charCodeAt(pos))) {
                                break;
                            }
                            pos++;
                        }
                        value = text.substring(start, pos);
                        return token = SyntaxKind.LineCommentTrivia;
                    }
                    // Multi-line comment
                    if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
                        pos += 2;
                        var safeLength = len - 1; // For lookahead.
                        var commentClosed = false;
                        while (pos < safeLength) {
                            var ch = text.charCodeAt(pos);
                            if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
                                pos += 2;
                                commentClosed = true;
                                break;
                            }
                            pos++;
                        }
                        if (!commentClosed) {
                            pos++;
                            scanError = ScanError.UnexpectedEndOfComment;
                        }
                        value = text.substring(start, pos);
                        return token = SyntaxKind.BlockCommentTrivia;
                    }
                    // just a single slash
                    value += String.fromCharCode(code);
                    pos++;
                    return token = SyntaxKind.Unknown;
                // numbers
                case 45 /* minus */:
                    value += String.fromCharCode(code);
                    pos++;
                    if (pos === len || !isDigit(text.charCodeAt(pos))) {
                        return token = SyntaxKind.Unknown;
                    }
                // found a minus, followed by a number so
                // we fall through to proceed with scanning
                // numbers
                case 48 /* _0 */:
                case 49 /* _1 */:
                case 50 /* _2 */:
                case 51 /* _3 */:
                case 52 /* _4 */:
                case 53 /* _5 */:
                case 54 /* _6 */:
                case 55 /* _7 */:
                case 56 /* _8 */:
                case 57 /* _9 */:
                    value += scanNumber();
                    return token = SyntaxKind.NumericLiteral;
                // literals and unknown symbols
                default:
                    // is a literal? Read the full word.
                    while (pos < len && isUnknownContentCharacter(code)) {
                        pos++;
                        code = text.charCodeAt(pos);
                    }
                    if (tokenOffset !== pos) {
                        value = text.substring(tokenOffset, pos);
                        // keywords: true, false, null
                        switch (value) {
                            case 'true': return token = SyntaxKind.TrueKeyword;
                            case 'false': return token = SyntaxKind.FalseKeyword;
                            case 'null': return token = SyntaxKind.NullKeyword;
                        }
                        return token = SyntaxKind.Unknown;
                    }
                    // some
                    value += String.fromCharCode(code);
                    pos++;
                    return token = SyntaxKind.Unknown;
            }
        }
        function isUnknownContentCharacter(code) {
            if (isWhiteSpace(code) || isLineBreak(code)) {
                return false;
            }
            switch (code) {
                case 125 /* closeBrace */:
                case 93 /* closeBracket */:
                case 123 /* openBrace */:
                case 91 /* openBracket */:
                case 34 /* doubleQuote */:
                case 58 /* colon */:
                case 44 /* comma */:
                    return false;
            }
            return true;
        }
        function scanNextNonTrivia() {
            var result;
            do {
                result = scanNext();
            } while (result >= SyntaxKind.LineCommentTrivia && result <= SyntaxKind.Trivia);
            return result;
        }
        return {
            setPosition: setPosition,
            getPosition: function () { return pos; },
            scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
            getToken: function () { return token; },
            getTokenValue: function () { return value; },
            getTokenOffset: function () { return tokenOffset; },
            getTokenLength: function () { return pos - tokenOffset; },
            getTokenError: function () { return scanError; }
        };
    }
    exports.createScanner = createScanner;
    function isWhiteSpace(ch) {
        return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
            ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
            ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
    }
    function isLineBreak(ch) {
        return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
    }
    function isDigit(ch) {
        return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
    }
    var CharacterCodes;
    (function (CharacterCodes) {
        CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
        CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
        CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
        CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
        CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
        CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
        // REVIEW: do we need to support this?  The scanner doesn't, but our IText does.  This seems
        // like an odd disparity?  (Or maybe it's completely fine for them to be different).
        CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
        // Unicode 3.0 space characters
        CharacterCodes[CharacterCodes["space"] = 32] = "space";
        CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
        CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
        CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
        CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
        CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
        CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
        CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
        CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
        CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
        CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
        CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
        CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
        CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
        CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
        CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
        CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
        CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
        CharacterCodes[CharacterCodes["_"] = 95] = "_";
        CharacterCodes[CharacterCodes["$"] = 36] = "$";
        CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
        CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
        CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
        CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
        CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
        CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
        CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
        CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
        CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
        CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
        CharacterCodes[CharacterCodes["a"] = 97] = "a";
        CharacterCodes[CharacterCodes["b"] = 98] = "b";
        CharacterCodes[CharacterCodes["c"] = 99] = "c";
        CharacterCodes[CharacterCodes["d"] = 100] = "d";
        CharacterCodes[CharacterCodes["e"] = 101] = "e";
        CharacterCodes[CharacterCodes["f"] = 102] = "f";
        CharacterCodes[CharacterCodes["g"] = 103] = "g";
        CharacterCodes[CharacterCodes["h"] = 104] = "h";
        CharacterCodes[CharacterCodes["i"] = 105] = "i";
        CharacterCodes[CharacterCodes["j"] = 106] = "j";
        CharacterCodes[CharacterCodes["k"] = 107] = "k";
        CharacterCodes[CharacterCodes["l"] = 108] = "l";
        CharacterCodes[CharacterCodes["m"] = 109] = "m";
        CharacterCodes[CharacterCodes["n"] = 110] = "n";
        CharacterCodes[CharacterCodes["o"] = 111] = "o";
        CharacterCodes[CharacterCodes["p"] = 112] = "p";
        CharacterCodes[CharacterCodes["q"] = 113] = "q";
        CharacterCodes[CharacterCodes["r"] = 114] = "r";
        CharacterCodes[CharacterCodes["s"] = 115] = "s";
        CharacterCodes[CharacterCodes["t"] = 116] = "t";
        CharacterCodes[CharacterCodes["u"] = 117] = "u";
        CharacterCodes[CharacterCodes["v"] = 118] = "v";
        CharacterCodes[CharacterCodes["w"] = 119] = "w";
        CharacterCodes[CharacterCodes["x"] = 120] = "x";
        CharacterCodes[CharacterCodes["y"] = 121] = "y";
        CharacterCodes[CharacterCodes["z"] = 122] = "z";
        CharacterCodes[CharacterCodes["A"] = 65] = "A";
        CharacterCodes[CharacterCodes["B"] = 66] = "B";
        CharacterCodes[CharacterCodes["C"] = 67] = "C";
        CharacterCodes[CharacterCodes["D"] = 68] = "D";
        CharacterCodes[CharacterCodes["E"] = 69] = "E";
        CharacterCodes[CharacterCodes["F"] = 70] = "F";
        CharacterCodes[CharacterCodes["G"] = 71] = "G";
        CharacterCodes[CharacterCodes["H"] = 72] = "H";
        CharacterCodes[CharacterCodes["I"] = 73] = "I";
        CharacterCodes[CharacterCodes["J"] = 74] = "J";
        CharacterCodes[CharacterCodes["K"] = 75] = "K";
        CharacterCodes[CharacterCodes["L"] = 76] = "L";
        CharacterCodes[CharacterCodes["M"] = 77] = "M";
        CharacterCodes[CharacterCodes["N"] = 78] = "N";
        CharacterCodes[CharacterCodes["O"] = 79] = "O";
        CharacterCodes[CharacterCodes["P"] = 80] = "P";
        CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
        CharacterCodes[CharacterCodes["R"] = 82] = "R";
        CharacterCodes[CharacterCodes["S"] = 83] = "S";
        CharacterCodes[CharacterCodes["T"] = 84] = "T";
        CharacterCodes[CharacterCodes["U"] = 85] = "U";
        CharacterCodes[CharacterCodes["V"] = 86] = "V";
        CharacterCodes[CharacterCodes["W"] = 87] = "W";
        CharacterCodes[CharacterCodes["X"] = 88] = "X";
        CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
        CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
        CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
        CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
        CharacterCodes[CharacterCodes["at"] = 64] = "at";
        CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
        CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
        CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
        CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
        CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
        CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
        CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
        CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
        CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
        CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
        CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
        CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
        CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
        CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
        CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
        CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
        CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
        CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
        CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
        CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
        CharacterCodes[CharacterCodes["question"] = 63] = "question";
        CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
        CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
        CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
        CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
        CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
        CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
        CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
        CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
        CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
    })(CharacterCodes || (CharacterCodes = {}));
    /**
     * Takes JSON with JavaScript-style comments and remove
     * them. Optionally replaces every none-newline character
     * of comments with a replaceCharacter
     */
    function stripComments(text, replaceCh) {
        var _scanner = createScanner(text), parts = [], kind, offset = 0, pos;
        do {
            pos = _scanner.getPosition();
            kind = _scanner.scan();
            switch (kind) {
                case SyntaxKind.LineCommentTrivia:
                case SyntaxKind.BlockCommentTrivia:
                case SyntaxKind.EOF:
                    if (offset !== pos) {
                        parts.push(text.substring(offset, pos));
                    }
                    if (replaceCh !== void 0) {
                        parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
                    }
                    offset = _scanner.getPosition();
                    break;
            }
        } while (kind !== SyntaxKind.EOF);
        return parts.join('');
    }
    exports.stripComments = stripComments;
    var ParseErrorCode;
    (function (ParseErrorCode) {
        ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 0] = "InvalidSymbol";
        ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 1] = "InvalidNumberFormat";
        ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 2] = "PropertyNameExpected";
        ParseErrorCode[ParseErrorCode["ValueExpected"] = 3] = "ValueExpected";
        ParseErrorCode[ParseErrorCode["ColonExpected"] = 4] = "ColonExpected";
        ParseErrorCode[ParseErrorCode["CommaExpected"] = 5] = "CommaExpected";
        ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 6] = "CloseBraceExpected";
        ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 7] = "CloseBracketExpected";
        ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 8] = "EndOfFileExpected";
    })(ParseErrorCode = exports.ParseErrorCode || (exports.ParseErrorCode = {}));
    function getLiteralNodeType(value) {
        switch (typeof value) {
            case 'boolean': return 'boolean';
            case 'number': return 'number';
            case 'string': return 'string';
            default: return 'null';
        }
    }
    /**
     * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
     */
    function getLocation(text, position) {
        var segments = []; // strings or numbers
        var earlyReturnException = new Object();
        var previousNode = void 0;
        var previousNodeInst = {
            value: void 0,
            offset: void 0,
            length: void 0,
            type: void 0
        };
        var isAtPropertyKey = false;
        function setPreviousNode(value, offset, length, type) {
            previousNodeInst.value = value;
            previousNodeInst.offset = offset;
            previousNodeInst.length = length;
            previousNodeInst.type = type;
            previousNodeInst.columnOffset = void 0;
            previousNode = previousNodeInst;
        }
        try {
            visit(text, {
                onObjectBegin: function (offset, length) {
                    if (position <= offset) {
                        throw earlyReturnException;
                    }
                    previousNode = void 0;
                    isAtPropertyKey = position > offset;
                    segments.push(''); // push a placeholder (will be replaced)
                },
                onObjectProperty: function (name, offset, length) {
                    if (position < offset) {
                        throw earlyReturnException;
                    }
                    setPreviousNode(name, offset, length, 'property');
                    segments[segments.length - 1] = name;
                    if (position <= offset + length) {
                        throw earlyReturnException;
                    }
                },
                onObjectEnd: function (offset, length) {
                    if (position <= offset) {
                        throw earlyReturnException;
                    }
                    previousNode = void 0;
                    segments.pop();
                },
                onArrayBegin: function (offset, length) {
                    if (position <= offset) {
                        throw earlyReturnException;
                    }
                    previousNode = void 0;
                    segments.push(0);
                },
                onArrayEnd: function (offset, length) {
                    if (position <= offset) {
                        throw earlyReturnException;
                    }
                    previousNode = void 0;
                    segments.pop();
                },
                onLiteralValue: function (value, offset, length) {
                    if (position < offset) {
                        throw earlyReturnException;
                    }
                    setPreviousNode(value, offset, length, getLiteralNodeType(value));
                    if (position <= offset + length) {
                        throw earlyReturnException;
                    }
                },
                onSeparator: function (sep, offset, length) {
                    if (position <= offset) {
                        throw earlyReturnException;
                    }
                    if (sep === ':' && previousNode.type === 'property') {
                        previousNode.columnOffset = offset;
                        isAtPropertyKey = false;
                        previousNode = void 0;
                    }
                    else if (sep === ',') {
                        var last = segments[segments.length - 1];
                        if (typeof last === 'number') {
                            segments[segments.length - 1] = last + 1;
                        }
                        else {
                            isAtPropertyKey = true;
                            segments[segments.length - 1] = '';
                        }
                        previousNode = void 0;
                    }
                }
            });
        }
        catch (e) {
            if (e !== earlyReturnException) {
                throw e;
            }
        }
        return {
            path: segments,
            previousNode: previousNode,
            isAtPropertyKey: isAtPropertyKey,
            matches: function (pattern) {
                var k = 0;
                for (var i = 0; k < pattern.length && i < segments.length; i++) {
                    if (pattern[k] === segments[i] || pattern[k] === '*') {
                        k++;
                    }
                    else if (pattern[k] !== '**') {
                        return false;
                    }
                }
                return k === pattern.length;
            }
        };
    }
    exports.getLocation = getLocation;
    /**
     * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
     * Therefore always check the errors list to find out if the input was valid.
     */
    function parse(text, errors, options) {
        if (errors === void 0) { errors = []; }
        var currentProperty = null;
        var currentParent = [];
        var previousParents = [];
        function onValue(value) {
            if (Array.isArray(currentParent)) {
                currentParent.push(value);
            }
            else if (currentProperty) {
                currentParent[currentProperty] = value;
            }
        }
        var visitor = {
            onObjectBegin: function () {
                var object = {};
                onValue(object);
                previousParents.push(currentParent);
                currentParent = object;
                currentProperty = null;
            },
            onObjectProperty: function (name) {
                currentProperty = name;
            },
            onObjectEnd: function () {
                currentParent = previousParents.pop();
            },
            onArrayBegin: function () {
                var array = [];
                onValue(array);
                previousParents.push(currentParent);
                currentParent = array;
                currentProperty = null;
            },
            onArrayEnd: function () {
                currentParent = previousParents.pop();
            },
            onLiteralValue: onValue,
            onError: function (error) {
                errors.push({ error: error });
            }
        };
        visit(text, visitor, options);
        return currentParent[0];
    }
    exports.parse = parse;
    /**
     * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
     */
    function parseTree(text, errors, options) {
        if (errors === void 0) { errors = []; }
        var currentParent = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root
        function ensurePropertyComplete(endOffset) {
            if (currentParent.type === 'property') {
                currentParent.length = endOffset - currentParent.offset;
                currentParent = currentParent.parent;
            }
        }
        function onValue(valueNode) {
            currentParent.children.push(valueNode);
            return valueNode;
        }
        var visitor = {
            onObjectBegin: function (offset) {
                currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });
            },
            onObjectProperty: function (name, offset, length) {
                currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });
                currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });
            },
            onObjectEnd: function (offset, length) {
                currentParent.length = offset + length - currentParent.offset;
                currentParent = currentParent.parent;
                ensurePropertyComplete(offset + length);
            },
            onArrayBegin: function (offset, length) {
                currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });
            },
            onArrayEnd: function (offset, length) {
                currentParent.length = offset + length - currentParent.offset;
                currentParent = currentParent.parent;
                ensurePropertyComplete(offset + length);
            },
            onLiteralValue: function (value, offset, length) {
                onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });
                ensurePropertyComplete(offset + length);
            },
            onSeparator: function (sep, offset, length) {
                if (currentParent.type === 'property') {
                    if (sep === ':') {
                        currentParent.columnOffset = offset;
                    }
                    else if (sep === ',') {
                        ensurePropertyComplete(offset);
                    }
                }
            },
            onError: function (error) {
                errors.push({ error: error });
            }
        };
        visit(text, visitor, options);
        var result = currentParent.children[0];
        if (result) {
            delete result.parent;
        }
        return result;
    }
    exports.parseTree = parseTree;
    function findNodeAtLocation(root, path) {
        if (!root) {
            return void 0;
        }
        var node = root;
        for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
            var segment = path_1[_i];
            if (typeof segment === 'string') {
                if (node.type !== 'object') {
                    return void 0;
                }
                var found = false;
                for (var _a = 0, _b = node.children; _a < _b.length; _a++) {
                    var propertyNode = _b[_a];
                    if (propertyNode.children[0].value === segment) {
                        node = propertyNode.children[1];
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    return void 0;
                }
            }
            else {
                var index = segment;
                if (node.type !== 'array' || index < 0 || index >= node.children.length) {
                    return void 0;
                }
                node = node.children[index];
            }
        }
        return node;
    }
    exports.findNodeAtLocation = findNodeAtLocation;
    function getNodeValue(node) {
        if (node.type === 'array') {
            return node.children.map(getNodeValue);
        }
        else if (node.type === 'object') {
            var obj = {};
            for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
                var prop = _a[_i];
                obj[prop.children[0].value] = getNodeValue(prop.children[1]);
            }
            return obj;
        }
        return node.value;
    }
    exports.getNodeValue = getNodeValue;
    /**
     * Parses the given text and invokes the visitor functions for each object, array and literal reached.
     */
    function visit(text, visitor, options) {
        var _scanner = createScanner(text, false);
        function toNoArgVisit(visitFunction) {
            return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength()); } : function () { return true; };
        }
        function toOneArgVisit(visitFunction) {
            return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength()); } : function () { return true; };
        }
        var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onError = toOneArgVisit(visitor.onError);
        var disallowComments = options && options.disallowComments;
        var allowTrailingComma = options && options.allowTrailingComma;
        function scanNext() {
            while (true) {
                var token = _scanner.scan();
                switch (token) {
                    case SyntaxKind.LineCommentTrivia:
                    case SyntaxKind.BlockCommentTrivia:
                        if (disallowComments) {
                            handleError(ParseErrorCode.InvalidSymbol);
                        }
                        break;
                    case SyntaxKind.Unknown:
                        handleError(ParseErrorCode.InvalidSymbol);
                        break;
                    case SyntaxKind.Trivia:
                    case SyntaxKind.LineBreakTrivia:
                        break;
                    default:
                        return token;
                }
            }
        }
        function handleError(error, skipUntilAfter, skipUntil) {
            if (skipUntilAfter === void 0) { skipUntilAfter = []; }
            if (skipUntil === void 0) { skipUntil = []; }
            onError(error);
            if (skipUntilAfter.length + skipUntil.length > 0) {
                var token = _scanner.getToken();
                while (token !== SyntaxKind.EOF) {
                    if (skipUntilAfter.indexOf(token) !== -1) {
                        scanNext();
                        break;
                    }
                    else if (skipUntil.indexOf(token) !== -1) {
                        break;
                    }
                    token = scanNext();
                }
            }
        }
        function parseString(isValue) {
            var value = _scanner.getTokenValue();
            if (isValue) {
                onLiteralValue(value);
            }
            else {
                onObjectProperty(value);
            }
            scanNext();
            return true;
        }
        function parseLiteral() {
            switch (_scanner.getToken()) {
                case SyntaxKind.NumericLiteral:
                    var value = 0;
                    try {
                        value = JSON.parse(_scanner.getTokenValue());
                        if (typeof value !== 'number') {
                            handleError(ParseErrorCode.InvalidNumberFormat);
                            value = 0;
                        }
                    }
                    catch (e) {
                        handleError(ParseErrorCode.InvalidNumberFormat);
                    }
                    onLiteralValue(value);
                    break;
                case SyntaxKind.NullKeyword:
                    onLiteralValue(null);
                    break;
                case SyntaxKind.TrueKeyword:
                    onLiteralValue(true);
                    break;
                case SyntaxKind.FalseKeyword:
                    onLiteralValue(false);
                    break;
                default:
                    return false;
            }
            scanNext();
            return true;
        }
        function parseProperty() {
            if (_scanner.getToken() !== SyntaxKind.StringLiteral) {
                handleError(ParseErrorCode.PropertyNameExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
                return false;
            }
            parseString(false);
            if (_scanner.getToken() === SyntaxKind.ColonToken) {
                onSeparator(':');
                scanNext(); // consume colon
                if (!parseValue()) {
                    handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
                }
            }
            else {
                handleError(ParseErrorCode.ColonExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
            }
            return true;
        }
        function parseObject() {
            onObjectBegin();
            scanNext(); // consume open brace
            var needsComma = false;
            while (_scanner.getToken() !== SyntaxKind.CloseBraceToken && _scanner.getToken() !== SyntaxKind.EOF) {
                if (_scanner.getToken() === SyntaxKind.CommaToken) {
                    if (!needsComma) {
                        handleError(ParseErrorCode.ValueExpected, [], []);
                    }
                    onSeparator(',');
                    scanNext(); // consume comma
                    if (_scanner.getToken() === SyntaxKind.CloseBraceToken && allowTrailingComma) {
                        break;
                    }
                }
                else if (needsComma) {
                    handleError(ParseErrorCode.CommaExpected, [], []);
                }
                if (!parseProperty()) {
                    handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
                }
                needsComma = true;
            }
            onObjectEnd();
            if (_scanner.getToken() !== SyntaxKind.CloseBraceToken) {
                handleError(ParseErrorCode.CloseBraceExpected, [SyntaxKind.CloseBraceToken], []);
            }
            else {
                scanNext(); // consume close brace
            }
            return true;
        }
        function parseArray() {
            onArrayBegin();
            scanNext(); // consume open bracket
            var needsComma = false;
            while (_scanner.getToken() !== SyntaxKind.CloseBracketToken && _scanner.getToken() !== SyntaxKind.EOF) {
                if (_scanner.getToken() === SyntaxKind.CommaToken) {
                    if (!needsComma) {
                        handleError(ParseErrorCode.ValueExpected, [], []);
                    }
                    onSeparator(',');
                    scanNext(); // consume comma
                }
                else if (needsComma) {
                    handleError(ParseErrorCode.CommaExpected, [], []);
                }
                if (!parseValue()) {
                    handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken]);
                }
                needsComma = true;
            }
            onArrayEnd();
            if (_scanner.getToken() !== SyntaxKind.CloseBracketToken) {
                handleError(ParseErrorCode.CloseBracketExpected, [SyntaxKind.CloseBracketToken], []);
            }
            else {
                scanNext(); // consume close bracket
            }
            return true;
        }
        function parseValue() {
            switch (_scanner.getToken()) {
                case SyntaxKind.OpenBracketToken:
                    return parseArray();
                case SyntaxKind.OpenBraceToken:
                    return parseObject();
                case SyntaxKind.StringLiteral:
                    return parseString(true);
                default:
                    return parseLiteral();
            }
        }
        scanNext();
        if (_scanner.getToken() === SyntaxKind.EOF) {
            return true;
        }
        if (!parseValue()) {
            handleError(ParseErrorCode.ValueExpected, [], []);
            return false;
        }
        if (_scanner.getToken() !== SyntaxKind.EOF) {
            handleError(ParseErrorCode.EndOfFileExpected, [], []);
        }
        return true;
    }
    exports.visit = visit;
});

/*---------------------------------------------------------------------------------------------
 *  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/base/common/keyCodes*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * Virtual Key Codes, the value does not hold any inherent meaning.
     * Inspired somewhat from https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
     * But these are "more general", as they should work across browsers & OS`s.
     */
    var KeyCode;
    (function (KeyCode) {
        /**
         * Placed first to cover the 0 value of the enum.
         */
        KeyCode[KeyCode["Unknown"] = 0] = "Unknown";
        KeyCode[KeyCode["Backspace"] = 1] = "Backspace";
        KeyCode[KeyCode["Tab"] = 2] = "Tab";
        KeyCode[KeyCode["Enter"] = 3] = "Enter";
        KeyCode[KeyCode["Shift"] = 4] = "Shift";
        KeyCode[KeyCode["Ctrl"] = 5] = "Ctrl";
        KeyCode[KeyCode["Alt"] = 6] = "Alt";
        KeyCode[KeyCode["PauseBreak"] = 7] = "PauseBreak";
        KeyCode[KeyCode["CapsLock"] = 8] = "CapsLock";
        KeyCode[KeyCode["Escape"] = 9] = "Escape";
        KeyCode[KeyCode["Space"] = 10] = "Space";
        KeyCode[KeyCode["PageUp"] = 11] = "PageUp";
        KeyCode[KeyCode["PageDown"] = 12] = "PageDown";
        KeyCode[KeyCode["End"] = 13] = "End";
        KeyCode[KeyCode["Home"] = 14] = "Home";
        KeyCode[KeyCode["LeftArrow"] = 15] = "LeftArrow";
        KeyCode[KeyCode["UpArrow"] = 16] = "UpArrow";
        KeyCode[KeyCode["RightArrow"] = 17] = "RightArrow";
        KeyCode[KeyCode["DownArrow"] = 18] = "DownArrow";
        KeyCode[KeyCode["Insert"] = 19] = "Insert";
        KeyCode[KeyCode["Delete"] = 20] = "Delete";
        KeyCode[KeyCode["KEY_0"] = 21] = "KEY_0";
        KeyCode[KeyCode["KEY_1"] = 22] = "KEY_1";
        KeyCode[KeyCode["KEY_2"] = 23] = "KEY_2";
        KeyCode[KeyCode["KEY_3"] = 24] = "KEY_3";
        KeyCode[KeyCode["KEY_4"] = 25] = "KEY_4";
        KeyCode[KeyCode["KEY_5"] = 26] = "KEY_5";
        KeyCode[KeyCode["KEY_6"] = 27] = "KEY_6";
        KeyCode[KeyCode["KEY_7"] = 28] = "KEY_7";
        KeyCode[KeyCode["KEY_8"] = 29] = "KEY_8";
        KeyCode[KeyCode["KEY_9"] = 30] = "KEY_9";
        KeyCode[KeyCode["KEY_A"] = 31] = "KEY_A";
        KeyCode[KeyCode["KEY_B"] = 32] = "KEY_B";
        KeyCode[KeyCode["KEY_C"] = 33] = "KEY_C";
        KeyCode[KeyCode["KEY_D"] = 34] = "KEY_D";
        KeyCode[KeyCode["KEY_E"] = 35] = "KEY_E";
        KeyCode[KeyCode["KEY_F"] = 36] = "KEY_F";
        KeyCode[KeyCode["KEY_G"] = 37] = "KEY_G";
        KeyCode[KeyCode["KEY_H"] = 38] = "KEY_H";
        KeyCode[KeyCode["KEY_I"] = 39] = "KEY_I";
        KeyCode[KeyCode["KEY_J"] = 40] = "KEY_J";
        KeyCode[KeyCode["KEY_K"] = 41] = "KEY_K";
        KeyCode[KeyCode["KEY_L"] = 42] = "KEY_L";
        KeyCode[KeyCode["KEY_M"] = 43] = "KEY_M";
        KeyCode[KeyCode["KEY_N"] = 44] = "KEY_N";
        KeyCode[KeyCode["KEY_O"] = 45] = "KEY_O";
        KeyCode[KeyCode["KEY_P"] = 46] = "KEY_P";
        KeyCode[KeyCode["KEY_Q"] = 47] = "KEY_Q";
        KeyCode[KeyCode["KEY_R"] = 48] = "KEY_R";
        KeyCode[KeyCode["KEY_S"] = 49] = "KEY_S";
        KeyCode[KeyCode["KEY_T"] = 50] = "KEY_T";
        KeyCode[KeyCode["KEY_U"] = 51] = "KEY_U";
        KeyCode[KeyCode["KEY_V"] = 52] = "KEY_V";
        KeyCode[KeyCode["KEY_W"] = 53] = "KEY_W";
        KeyCode[KeyCode["KEY_X"] = 54] = "KEY_X";
        KeyCode[KeyCode["KEY_Y"] = 55] = "KEY_Y";
        KeyCode[KeyCode["KEY_Z"] = 56] = "KEY_Z";
        KeyCode[KeyCode["Meta"] = 57] = "Meta";
        KeyCode[KeyCode["ContextMenu"] = 58] = "ContextMenu";
        KeyCode[KeyCode["F1"] = 59] = "F1";
        KeyCode[KeyCode["F2"] = 60] = "F2";
        KeyCode[KeyCode["F3"] = 61] = "F3";
        KeyCode[KeyCode["F4"] = 62] = "F4";
        KeyCode[KeyCode["F5"] = 63] = "F5";
        KeyCode[KeyCode["F6"] = 64] = "F6";
        KeyCode[KeyCode["F7"] = 65] = "F7";
        KeyCode[KeyCode["F8"] = 66] = "F8";
        KeyCode[KeyCode["F9"] = 67] = "F9";
        KeyCode[KeyCode["F10"] = 68] = "F10";
        KeyCode[KeyCode["F11"] = 69] = "F11";
        KeyCode[KeyCode["F12"] = 70] = "F12";
        KeyCode[KeyCode["F13"] = 71] = "F13";
        KeyCode[KeyCode["F14"] = 72] = "F14";
        KeyCode[KeyCode["F15"] = 73] = "F15";
        KeyCode[KeyCode["F16"] = 74] = "F16";
        KeyCode[KeyCode["F17"] = 75] = "F17";
        KeyCode[KeyCode["F18"] = 76] = "F18";
        KeyCode[KeyCode["F19"] = 77] = "F19";
        KeyCode[KeyCode["NumLock"] = 78] = "NumLock";
        KeyCode[KeyCode["ScrollLock"] = 79] = "ScrollLock";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the ';:' key
         */
        KeyCode[KeyCode["US_SEMICOLON"] = 80] = "US_SEMICOLON";
        /**
         * For any country/region, the '+' key
         * For the US standard keyboard, the '=+' key
         */
        KeyCode[KeyCode["US_EQUAL"] = 81] = "US_EQUAL";
        /**
         * For any country/region, the ',' key
         * For the US standard keyboard, the ',<' key
         */
        KeyCode[KeyCode["US_COMMA"] = 82] = "US_COMMA";
        /**
         * For any country/region, the '-' key
         * For the US standard keyboard, the '-_' key
         */
        KeyCode[KeyCode["US_MINUS"] = 83] = "US_MINUS";
        /**
         * For any country/region, the '.' key
         * For the US standard keyboard, the '.>' key
         */
        KeyCode[KeyCode["US_DOT"] = 84] = "US_DOT";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the '/?' key
         */
        KeyCode[KeyCode["US_SLASH"] = 85] = "US_SLASH";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the '`~' key
         */
        KeyCode[KeyCode["US_BACKTICK"] = 86] = "US_BACKTICK";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the '[{' key
         */
        KeyCode[KeyCode["US_OPEN_SQUARE_BRACKET"] = 87] = "US_OPEN_SQUARE_BRACKET";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the '\|' key
         */
        KeyCode[KeyCode["US_BACKSLASH"] = 88] = "US_BACKSLASH";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the ']}' key
         */
        KeyCode[KeyCode["US_CLOSE_SQUARE_BRACKET"] = 89] = "US_CLOSE_SQUARE_BRACKET";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the ''"' key
         */
        KeyCode[KeyCode["US_QUOTE"] = 90] = "US_QUOTE";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         */
        KeyCode[KeyCode["OEM_8"] = 91] = "OEM_8";
        /**
         * Either the angle bracket key or the backslash key on the RT 102-key keyboard.
         */
        KeyCode[KeyCode["OEM_102"] = 92] = "OEM_102";
        KeyCode[KeyCode["NUMPAD_0"] = 93] = "NUMPAD_0";
        KeyCode[KeyCode["NUMPAD_1"] = 94] = "NUMPAD_1";
        KeyCode[KeyCode["NUMPAD_2"] = 95] = "NUMPAD_2";
        KeyCode[KeyCode["NUMPAD_3"] = 96] = "NUMPAD_3";
        KeyCode[KeyCode["NUMPAD_4"] = 97] = "NUMPAD_4";
        KeyCode[KeyCode["NUMPAD_5"] = 98] = "NUMPAD_5";
        KeyCode[KeyCode["NUMPAD_6"] = 99] = "NUMPAD_6";
        KeyCode[KeyCode["NUMPAD_7"] = 100] = "NUMPAD_7";
        KeyCode[KeyCode["NUMPAD_8"] = 101] = "NUMPAD_8";
        KeyCode[KeyCode["NUMPAD_9"] = 102] = "NUMPAD_9";
        KeyCode[KeyCode["NUMPAD_MULTIPLY"] = 103] = "NUMPAD_MULTIPLY";
        KeyCode[KeyCode["NUMPAD_ADD"] = 104] = "NUMPAD_ADD";
        KeyCode[KeyCode["NUMPAD_SEPARATOR"] = 105] = "NUMPAD_SEPARATOR";
        KeyCode[KeyCode["NUMPAD_SUBTRACT"] = 106] = "NUMPAD_SUBTRACT";
        KeyCode[KeyCode["NUMPAD_DECIMAL"] = 107] = "NUMPAD_DECIMAL";
        KeyCode[KeyCode["NUMPAD_DIVIDE"] = 108] = "NUMPAD_DIVIDE";
        /**
         * Cover all key codes when IME is processing input.
         */
        KeyCode[KeyCode["KEY_IN_COMPOSITION"] = 109] = "KEY_IN_COMPOSITION";
        KeyCode[KeyCode["ABNT_C1"] = 110] = "ABNT_C1";
        KeyCode[KeyCode["ABNT_C2"] = 111] = "ABNT_C2";
        /**
         * Placed last to cover the length of the enum.
         * Please do not depend on this value!
         */
        KeyCode[KeyCode["MAX_VALUE"] = 112] = "MAX_VALUE";
    })(KeyCode = exports.KeyCode || (exports.KeyCode = {}));
    var KeyCodeStrMap = (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 = {}));
    /**
     * Binary encoding strategy:
     * ```
     *    1111 11
     *    5432 1098 7654 3210
     *    ---- CSAW KKKK KKKK
     *  C = bit 11 = ctrlCmd flag
     *  S = bit 10 = shift flag
     *  A = bit 9 = alt flag
     *  W = bit 8 = winCtrl flag
     *  K = bits 0-7 = key code
     * ```
     */
    var BinaryKeybindingsMask;
    (function (BinaryKeybindingsMask) {
        BinaryKeybindingsMask[BinaryKeybindingsMask["CtrlCmd"] = 2048] = "CtrlCmd";
        BinaryKeybindingsMask[BinaryKeybindingsMask["Shift"] = 1024] = "Shift";
        BinaryKeybindingsMask[BinaryKeybindingsMask["Alt"] = 512] = "Alt";
        BinaryKeybindingsMask[BinaryKeybindingsMask["WinCtrl"] = 256] = "WinCtrl";
        BinaryKeybindingsMask[BinaryKeybindingsMask["KeyCode"] = 255] = "KeyCode";
    })(BinaryKeybindingsMask || (BinaryKeybindingsMask = {}));
    var KeyMod;
    (function (KeyMod) {
        KeyMod[KeyMod["CtrlCmd"] = 2048] = "CtrlCmd";
        KeyMod[KeyMod["Shift"] = 1024] = "Shift";
        KeyMod[KeyMod["Alt"] = 512] = "Alt";
        KeyMod[KeyMod["WinCtrl"] = 256] = "WinCtrl";
    })(KeyMod = exports.KeyMod || (exports.KeyMod = {}));
    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 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 KeybindingType;
    (function (KeybindingType) {
        KeybindingType[KeybindingType["Simple"] = 1] = "Simple";
        KeybindingType[KeybindingType["Chord"] = 2] = "Chord";
    })(KeybindingType = exports.KeybindingType || (exports.KeybindingType = {}));
    var SimpleKeybinding = (function () {
        function SimpleKeybinding(ctrlKey, shiftKey, altKey, metaKey, keyCode) {
            this.type = 1 /* Simple */;
            this.ctrlKey = ctrlKey;
            this.shiftKey = shiftKey;
            this.altKey = altKey;
            this.metaKey = metaKey;
            this.keyCode = keyCode;
        }
        SimpleKeybinding.prototype.equals = function (other) {
            if (other.type !== 1 /* Simple */) {
                return false;
            }
            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 */);
        };
        /**
         * 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 = (function () {
        function ChordKeybinding(firstPart, chordPart) {
            this.type = 2 /* Chord */;
            this.firstPart = firstPart;
            this.chordPart = chordPart;
        }
        return ChordKeybinding;
    }());
    exports.ChordKeybinding = ChordKeybinding;
    var ResolvedKeybindingPart = (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 = (function () {
        function ResolvedKeybinding() {
        }
        return ResolvedKeybinding;
    }());
    exports.ResolvedKeybinding = ResolvedKeybinding;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[3/*vs/base/common/lifecycle*/], __M([1/*require*/,0/*exports*/,136/*vs/base/common/functional*/]), function (require, exports, functional_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.empty = Object.freeze({
        dispose: function () { }
    });
    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() {
        var fns = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            fns[_i] = arguments[_i];
        }
        return {
            dispose: function () {
                for (var _i = 0, fns_1 = fns; _i < fns_1.length; _i++) {
                    var fn = fns_1[_i];
                    fn();
                }
            }
        };
    }
    exports.toDisposable = toDisposable;
    var Disposable = (function () {
        function Disposable() {
            this._toDispose = [];
        }
        Disposable.prototype.dispose = function () {
            this._toDispose = dispose(this._toDispose);
        };
        Disposable.prototype._register = function (t) {
            this._toDispose.push(t);
            return t;
        };
        return Disposable;
    }());
    exports.Disposable = Disposable;
    var OneDisposable = (function () {
        function OneDisposable() {
        }
        Object.defineProperty(OneDisposable.prototype, "value", {
            set: function (value) {
                if (this._value) {
                    this._value.dispose();
                }
                this._value = value;
            },
            enumerable: true,
            configurable: true
        });
        OneDisposable.prototype.dispose = function () {
            this.value = null;
        };
        return OneDisposable;
    }());
    exports.OneDisposable = OneDisposable;
    var ReferenceCollection = (function () {
        function ReferenceCollection() {
            this.references = Object.create(null);
        }
        ReferenceCollection.prototype.acquire = function (key) {
            var _this = this;
            var reference = this.references[key];
            if (!reference) {
                reference = this.references[key] = { counter: 0, object: this.createReferencedObject(key) };
            }
            var object = reference.object;
            var dispose = functional_1.once(function () {
                if (--reference.counter === 0) {
                    _this.destroyReferencedObject(reference.object);
                    delete _this.references[key];
                }
            });
            reference.counter++;
            return { object: object, dispose: dispose };
        };
        return ReferenceCollection;
    }());
    exports.ReferenceCollection = ReferenceCollection;
    var ImmortalReference = (function () {
        function ImmortalReference(object) {
            this.object = object;
        }
        ImmortalReference.prototype.dispose = function () { };
        return ImmortalReference;
    }());
    exports.ImmortalReference = ImmortalReference;
});

/**
 * marked - a markdown parser
 * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
 * https://github.com/chjj/marked
 */

// TODO MonacoChange: we have our own way of defining modules
// ;(function() {
// END MonacoChange

/**
 * Block-Level Grammar
 */

var block = {
  newline: /^\n+/,
  code: /^( {4}[^\n]+\n*)+/,
  fences: noop,
  hr: /^( *[-*_]){3,} *(?:\n+|$)/,
  heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
  nptable: noop,
  lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
  blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
  list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
  html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
  table: noop,
  paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
  text: /^[^\n]+/
};

block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, 'gm')
  (/bull/g, block.bullet)
  ();

block.list = replace(block.list)
  (/bull/g, block.bullet)
  ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
  ('def', '\\n+(?=' + block.def.source + ')')
  ();

block.blockquote = replace(block.blockquote)
  ('def', block.def)
  ();

block._tag = '(?!(?:'
  + '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';

block.html = replace(block.html)
  ('comment', /<!--[\s\S]*?-->/)
  ('closed', /<(tag)[\s\S]+?<\/\1>/)
  ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
  (/tag/g, block._tag)
  ();

block.paragraph = replace(block.paragraph)
  ('hr', block.hr)
  ('heading', block.heading)
  ('lheading', block.lheading)
  ('blockquote', block.blockquote)
  ('tag', '<' + block._tag)
  ('def', block.def)
  ();

/**
 * Normal Block Grammar
 */

block.normal = merge({}, block);

/**
 * GFM Block Grammar
 */

block.gfm = merge({}, block.normal, {
  fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
  paragraph: /^/,
  heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
});

block.gfm.paragraph = replace(block.paragraph)
  ('(?!', '(?!'
    + block.gfm.fences.source.replace('\\1', '\\2') + '|'
    + block.list.source.replace('\\1', '\\3') + '|')
  ();

/**
 * GFM + Tables Block Grammar
 */

block.tables = merge({}, block.gfm, {
  nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
  table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
});

/**
 * Block Lexer
 */

function Lexer(options) {
  this.tokens = [];
  this.tokens.links = {};
  this.options = options || marked.defaults;
  this.rules = block.normal;

  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, bq) {
  var src = src.replace(/^ +$/gm, '')
    , next
    , loose
    , cap
    , bull
    , b
    , item
    , space
    , i
    , l;

  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
          ? cap.replace(/\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],
        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 (top && (cap = this.rules.nptable.exec(src))) {
      src = src.substring(cap[0].length);

      item = {
        type: 'table',
        header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
        align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
        cells: cap[3].replace(/\n$/, '').split('\n')
      };

      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] = item.cells[i].split(/ *\| */);
      }

      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;
    }

    // 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, true);

      this.tokens.push({
        type: 'blockquote_end'
      });

      continue;
    }

    // list
    if (cap = this.rules.list.exec(src)) {
      src = src.substring(cap[0].length);
      bull = cap[2];

      this.tokens.push({
        type: 'list_start',
        ordered: bull.length > 1
      });

      // Get each top-level item.
      cap = cap[0].match(this.rules.item);

      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 (this.options.smartLists && i !== l - 1) {
          b = block.bullet.exec(cap[i + 1])[0];
          if (bull !== b && !(bull.length > 1 && b.length > 1)) {
            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;
        }

        this.tokens.push({
          type: loose
            ? 'loose_item_start'
            : 'list_item_start'
        });

        // Recurse.
        this.token(item, false, bq);

        this.tokens.push({
          type: 'list_item_end'
        });
      }

      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 ((!bq && top) && (cap = this.rules.def.exec(src))) {
      src = src.substring(cap[0].length);
      this.tokens.links[cap[1].toLowerCase()] = {
        href: cap[2],
        title: cap[3]
      };
      continue;
    }

    // table (gfm)
    if (top && (cap = this.rules.table.exec(src))) {
      src = src.substring(cap[0].length);

      item = {
        type: 'table',
        header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
        align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
        cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
      };

      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] = item.cells[i]
          .replace(/^ *\| *| *\| *$/g, '')
          .split(/ *\| */);
      }

      this.tokens.push(item);

      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: /^<([^ >]+(@|:\/)[^ >]+)>/,
  url: noop,
  tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
  link: /^!?\[(inside)\]\(href\)/,
  reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
  nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
  strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
  em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
  code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
  br: /^ {2,}\n(?!\s*$)/,
  del: noop,
  text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
};

inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;

inline.link = replace(inline.link)
  ('inside', inline._inside)
  ('href', inline._href)
  ();

inline.reflink = replace(inline.reflink)
  ('inside', inline._inside)
  ();

/**
 * 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)\*(?!\*)/
});

/**
 * GFM Inline Grammar
 */

inline.gfm = merge({}, inline.normal, {
  escape: replace(inline.escape)('])', '~|])')(),
  url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
  del: /^~~(?=\S)([\s\S]*?\S)~~/,
  text: replace(inline.text)
    (']|', '~]|')
    ('|', '|https?://|')
    ()
});

/**
 * GFM + Line Breaks Inline Grammar
 */

inline.breaks = merge({}, inline.gfm, {
  br: replace(inline.br)('{2,}', '*')(),
  text: replace(inline.gfm.text)('{2,}', '*')()
});

/**
 * Inline Lexer & Compiler
 */

function InlineLexer(links, options) {
  this.options = options || marked.defaults;
  this.links = links;
  this.rules = inline.normal;
  this.renderer = this.options.renderer || new Renderer;
  this.renderer.options = this.options;

  if (!this.links) {
    throw new
      Error('Tokens array requires a `links` property.');
  }

  if (this.options.gfm) {
    if (this.options.breaks) {
      this.rules = inline.breaks;
    } else {
      this.rules = inline.gfm;
    }
  } else if (this.options.pedantic) {
    this.rules = inline.pedantic;
  }
}

/**
 * Expose Inline Rules
 */

InlineLexer.rules = inline;

/**
 * Static Lexing/Compiling Method
 */

InlineLexer.output = function(src, links, options) {
  var inline = new InlineLexer(links, options);
  return inline.output(src);
};

/**
 * Lexing/Compiling
 */

InlineLexer.prototype.output = function(src) {
  var out = ''
    , link
    , text
    , href
    , cap;

  while (src) {
    // escape
    if (cap = this.rules.escape.exec(src)) {
      src = src.substring(cap[0].length);
      out += cap[1];
      continue;
    }

    // autolink
    if (cap = this.rules.autolink.exec(src)) {
      src = src.substring(cap[0].length);
      if (cap[2] === '@') {
        text = cap[1].charAt(6) === ':'
          ? this.mangle(cap[1].substring(7))
          : this.mangle(cap[1]);
        href = this.mangle('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))) {
      src = src.substring(cap[0].length);
      text = escape(cap[1]);
      href = text;
      out += this.renderer.link(href, null, text);
      continue;
    }

    // tag
    if (cap = this.rules.tag.exec(src)) {
      if (!this.inLink && /^<a /i.test(cap[0])) {
        this.inLink = true;
      } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
        this.inLink = 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)) {
      src = src.substring(cap[0].length);
      this.inLink = true;
      out += this.outputLink(cap, {
        href: cap[2],
        title: cap[3]
      });
      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[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[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], 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;
    }

    // text
    if (cap = this.rules.text.exec(src)) {
      src = src.substring(cap[0].length);
      out += this.renderer.text(escape(this.smartypants(cap[0])));
      continue;
    }

    if (src) {
      throw new
        Error('Infinite loop on byte: ' + src.charCodeAt(0));
    }
  }

  return out;
};

/**
 * Compile Link
 */

InlineLexer.prototype.outputLink = function(cap, link) {
  var href = escape(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 || {};
}

Renderer.prototype.code = function(code, lang, escaped) {
  if (this.options.highlight) {
    var out = this.options.highlight(code, lang);
    if (out != null && out !== code) {
      escaped = true;
      code = out;
    }
  }

  if (!lang) {
    return '<pre><code>'
      + (escaped ? code : escape(code, true))
      + '\n</code></pre>';
  }

  return '<pre><code class="'
    + this.options.langPrefix
    + escape(lang, true)
    + '">'
    + (escaped ? code : escape(code, true))
    + '\n</code></pre>\n';
};

Renderer.prototype.blockquote = function(quote) {
  return '<blockquote>\n' + quote + '</blockquote>\n';
};

Renderer.prototype.html = function(html) {
  return html;
};

Renderer.prototype.heading = function(text, level, raw) {
  return '<h'
    + level
    + ' id="'
    + this.options.headerPrefix
    + raw.toLowerCase().replace(/[^\w]+/g, '-')
    + '">'
    + text
    + '</h'
    + level
    + '>\n';
};

Renderer.prototype.hr = function() {
  return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
};

Renderer.prototype.list = function(body, ordered) {
  var type = ordered ? 'ol' : 'ul';
  return '<' + type + '>\n' + body + '</' + type + '>\n';
};

Renderer.prototype.listitem = function(text) {
  return '<li>' + text + '</li>\n';
};

Renderer.prototype.paragraph = function(text) {
  return '<p>' + text + '</p>\n';
};

Renderer.prototype.table = function(header, body) {
  return '<table>\n'
    + '<thead>\n'
    + header
    + '</thead>\n'
    + '<tbody>\n'
    + body
    + '</tbody>\n'
    + '</table>\n';
};

Renderer.prototype.tablerow = function(content) {
  return '<tr>\n' + content + '</tr>\n';
};

Renderer.prototype.tablecell = function(content, flags) {
  var type = flags.header ? 'th' : 'td';
  var tag = flags.align
    ? '<' + type + ' style="text-align:' + flags.align + '">'
    : '<' + type + '>';
  return tag + content + '</' + type + '>\n';
};

// span level renderer
Renderer.prototype.strong = function(text) {
  return '<strong>' + text + '</strong>';
};

Renderer.prototype.em = function(text) {
  return '<em>' + text + '</em>';
};

Renderer.prototype.codespan = function(text) {
  return '<code>' + text + '</code>';
};

Renderer.prototype.br = function() {
  return this.options.xhtml ? '<br/>' : '<br>';
};

Renderer.prototype.del = function(text) {
  return '<del>' + text + '</del>';
};

Renderer.prototype.link = function(href, title, text) {
  if (this.options.sanitize) {
    try {
      var prot = decodeURIComponent(unescape(href))
        .replace(/[^\w:]/g, '')
        .toLowerCase();
    } catch (e) {
      return '';
    }
    if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
      return '';
    }
  }
  var out = '<a href="' + href + '"';
  if (title) {
    out += ' title="' + title + '"';
  }
  out += '>' + text + '</a>';
  return out;
};

Renderer.prototype.image = function(href, title, text) {
  var out = '<img src="' + href + '" alt="' + text + '"';
  if (title) {
    out += ' title="' + title + '"';
  }
  out += this.options.xhtml ? '/>' : '>';
  return out;
};

Renderer.prototype.text = function(text) {
  return text;
};

/**
 * 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;
}

/**
 * Static Parse Method
 */

Parser.parse = function(src, options, renderer) {
  var parser = new Parser(options, renderer);
  return parser.parse(src);
};

/**
 * Parse Loop
 */

Parser.prototype.parse = function(src) {
  this.inline = new InlineLexer(src.links, this.options, this.renderer);
  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,
        this.token.text);
    }
    case 'code': {
      return this.renderer.code(this.token.text,
        this.token.lang,
        this.token.escaped);
    }
    case 'table': {
      var header = ''
        , body = ''
        , i
        , row
        , cell
        , flags
        , j;

      // header
      cell = '';
      for (i = 0; i < this.token.header.length; i++) {
        flags = { header: true, align: this.token.align[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': {
      var body = '';

      while (this.next().type !== 'blockquote_end') {
        body += this.tok();
      }

      return this.renderer.blockquote(body);
    }
    case 'list_start': {
      var body = ''
        , ordered = this.token.ordered;

      while (this.next().type !== 'list_end') {
        body += this.tok();
      }

      return this.renderer.list(body, ordered);
    }
    case 'list_item_start': {
      var body = '';

      while (this.next().type !== 'list_item_end') {
        body += this.token.type === 'text'
          ? this.parseText()
          : this.tok();
      }

      return this.renderer.listitem(body);
    }
    case 'loose_item_start': {
      var body = '';

      while (this.next().type !== 'list_item_end') {
        body += this.tok();
      }

      return this.renderer.listitem(body);
    }
    case 'html': {
      var html = !this.token.pre && !this.options.pedantic
        ? this.inline.output(this.token.text)
        : this.token.text;
      return this.renderer.html(html);
    }
    case 'paragraph': {
      return this.renderer.paragraph(this.inline.output(this.token.text));
    }
    case 'text': {
      return this.renderer.paragraph(this.parseText());
    }
  }
};

/**
 * Helpers
 */

function escape(html, encode) {
  return html
    .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

function unescape(html) {
	// explicitly match decimal, hex, and named HTML entities
  return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, 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 replace(regex, opt) {
  regex = regex.source;
  opt = opt || '';
  return function self(name, val) {
    if (!name) return new RegExp(regex, opt);
    val = val.source || val;
    val = val.replace(/(^|[^\[])\^/g, '$1');
    regex = regex.replace(name, val);
    return self;
  };
}

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;
}


/**
 * Marked
 */

function marked(src, opt, callback) {
  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/chjj/marked.';
    if ((opt || marked.defaults).silent) {
      return '<p>An error occurred:</p><pre>'
        + escape(e.message + '', true)
        + '</pre>';
    }
    throw e;
  }
}

/**
 * Options
 */

marked.options =
marked.setOptions = function(opt) {
  merge(marked.defaults, opt);
  return marked;
};

marked.defaults = {
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: false,
  sanitizer: null,
  mangle: true,
  smartLists: false,
  silent: false,
  highlight: null,
  langPrefix: 'lang-',
  smartypants: false,
  headerPrefix: '',
  renderer: new Renderer,
  xhtml: false
};

/**
 * Expose
 */

marked.Parser = Parser;
marked.parser = Parser.parse;

marked.Renderer = Renderer;

marked.Lexer = Lexer;
marked.lexer = Lexer.lex;

marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;

marked.parse = marked;

// TODO MonacoChange: we have our own way of defining modules
define("vs/base/common/marked/raw.marked", [], function() {
  return marked;
});
//if (typeof module !== 'undefined' && typeof exports === 'object') {
//  module.exports = marked;
//} else if (typeof define === 'function' && define.amd) {
//  define(function() { return marked; });
//} else {
//  this.marked = marked;
//}
//
//}).call(function() {
//  return this || (typeof window !== 'undefined' ? window : global);
//}());
// 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[209/*vs/base/common/marked/marked*/], __M([552/*vs/base/common/marked/raw.marked*/]), function (marked) {
	return {
		marked: marked
	};
});
define(__m[70/*vs/base/common/network*/], __M([1/*require*/,0/*exports*/]), 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 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.untitled = 'untitled';
    })(Schemas = exports.Schemas || (exports.Schemas = {}));
});

define(__m[15/*vs/base/common/platform*/], __M([1/*require*/,0/*exports*/]), 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 });
    // --- THIS FILE IS TEMPORARY UNTIL ENV.TS IS CLEANED UP. IT CAN SAFELY BE USED IN ALL TARGET EXECUTION ENVIRONMENTS (node & dom) ---
    var _isWindows = false;
    var _isMacintosh = false;
    var _isLinux = false;
    var _isRootUser = false;
    var _isNative = false;
    var _isWeb = false;
    var _locale = undefined;
    var _language = undefined;
    exports.LANGUAGE_DEFAULT = 'en';
    // OS detection
    if (typeof process === 'object') {
        _isWindows = (process.platform === 'win32');
        _isMacintosh = (process.platform === 'darwin');
        _isLinux = (process.platform === 'linux');
        _isRootUser = !_isWindows && (process.getuid() === 0);
        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 : exports.LANGUAGE_DEFAULT;
            }
            catch (e) {
            }
        }
        _isNative = true;
    }
    else if (typeof navigator === 'object') {
        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;
    }
    var Platform;
    (function (Platform) {
        Platform[Platform["Web"] = 0] = "Web";
        Platform[Platform["Mac"] = 1] = "Mac";
        Platform[Platform["Linux"] = 2] = "Linux";
        Platform[Platform["Windows"] = 3] = "Windows";
    })(Platform = exports.Platform || (exports.Platform = {}));
    var _platform = Platform.Web;
    if (_isNative) {
        if (_isMacintosh) {
            _platform = Platform.Mac;
        }
        else if (_isWindows) {
            _platform = Platform.Windows;
        }
        else if (_isLinux) {
            _platform = Platform.Linux;
        }
    }
    exports.isWindows = _isWindows;
    exports.isMacintosh = _isMacintosh;
    exports.isLinux = _isLinux;
    exports.isRootUser = _isRootUser;
    exports.isNative = _isNative;
    exports.isWeb = _isWeb;
    exports.platform = _platform;
    /**
     * The language used for the user interface. The format of
     * the string is all lower case (e.g. zh-tw for Traditional
     * Chinese)
     */
    exports.language = _language;
    /**
     * The OS locale or the locale specified by --locale. The format of
     * the string is all lower case (e.g. zh-tw for Traditional
     * Chinese). The UI is not necessarily shown in the provided locale.
     */
    exports.locale = _locale;
    var _globals = (typeof self === 'object' ? self : global);
    exports.globals = _globals;
    function hasWebWorkerSupport() {
        return typeof _globals.Worker !== 'undefined';
    }
    exports.hasWebWorkerSupport = hasWebWorkerSupport;
    exports.setTimeout = _globals.setTimeout.bind(_globals);
    exports.clearTimeout = _globals.clearTimeout.bind(_globals);
    exports.setInterval = _globals.setInterval.bind(_globals);
    exports.clearInterval = _globals.clearInterval.bind(_globals);
    var OperatingSystem;
    (function (OperatingSystem) {
        OperatingSystem[OperatingSystem["Windows"] = 1] = "Windows";
        OperatingSystem[OperatingSystem["Macintosh"] = 2] = "Macintosh";
        OperatingSystem[OperatingSystem["Linux"] = 3] = "Linux";
    })(OperatingSystem = exports.OperatingSystem || (exports.OperatingSystem = {}));
    exports.OS = (_isMacintosh ? 2 /* Macintosh */ : (_isWindows ? 1 /* Windows */ : 3 /* Linux */));
    var AccessibilitySupport;
    (function (AccessibilitySupport) {
        /**
         * This should be the browser case where it is not known if a screen reader is attached or no.
         */
        AccessibilitySupport[AccessibilitySupport["Unknown"] = 0] = "Unknown";
        AccessibilitySupport[AccessibilitySupport["Disabled"] = 1] = "Disabled";
        AccessibilitySupport[AccessibilitySupport["Enabled"] = 2] = "Enabled";
    })(AccessibilitySupport = exports.AccessibilitySupport || (exports.AccessibilitySupport = {}));
});

/*---------------------------------------------------------------------------------------------
 *  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/base/common/scorer*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    // Based on material from:
    /*!
    BEGIN THIRD PARTY
    */
    /*!
    * string_score.js: String Scoring Algorithm 0.1.22
    *
    * http://joshaven.com/string_score
    * https://github.com/joshaven/string_score
    *
    * Copyright (C) 2009-2014 Joshaven Potter <yourtech@gmail.com>
    * Special thanks to all of the contributors listed here https://github.com/joshaven/string_score
    * MIT License: http://opensource.org/licenses/MIT
    *
    * Date: Tue Mar 1 2011
    * Updated: Tue Mar 10 2015
    */
    /**
     * Compute a score for the given string and the given query.
     *
     * Rules:
     * Character score: 1
     * Same case bonus: 1
     * Upper case bonus: 1
     * Consecutive match bonus: 5
     * Start of word/path bonus: 7
     * Start of string bonus: 8
     */
    var wordPathBoundary = ['-', '_', ' ', '/', '\\', '.'];
    function score(target, query, cache) {
        if (!target || !query) {
            return 0; // return early if target or query are undefined
        }
        var hash = target + query;
        var cached = cache && cache[hash];
        if (typeof cached === 'number') {
            return cached;
        }
        var queryLen = query.length;
        var targetLower = target.toLowerCase();
        var queryLower = query.toLowerCase();
        var index = 0;
        var startAt = 0;
        var score = 0;
        var _loop_1 = function () {
            var indexOf = targetLower.indexOf(queryLower[index], startAt);
            if (indexOf < 0) {
                score = 0; // This makes sure that the query is contained in the target
                return "break";
            }
            // Character match bonus
            score += 1;
            // Consecutive match bonus
            if (startAt === indexOf) {
                score += 5;
            }
            // Same case bonus
            if (target[indexOf] === query[indexOf]) {
                score += 1;
            }
            // Start of word bonus
            if (indexOf === 0) {
                score += 8;
            }
            else if (wordPathBoundary.some(function (w) { return w === target[indexOf - 1]; })) {
                score += 7;
            }
            else if (isUpper(target.charCodeAt(indexOf))) {
                score += 1;
            }
            startAt = indexOf + 1;
            index++;
        };
        while (index < queryLen) {
            var state_1 = _loop_1();
            if (state_1 === "break")
                break;
        }
        if (cache) {
            cache[hash] = score;
        }
        return score;
    }
    exports.score = score;
    function isUpper(code) {
        return 65 <= code && code <= 90;
    }
    /**
     * A fast method to check if a given string would produce a score > 0 for the given query.
     */
    function matches(target, queryLower) {
        if (!target || !queryLower) {
            return false; // return early if target or query are undefined
        }
        var queryLen = queryLower.length;
        var targetLower = target.toLowerCase();
        var index = 0;
        var lastIndexOf = -1;
        while (index < queryLen) {
            var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf + 1);
            if (indexOf < 0) {
                return false;
            }
            lastIndexOf = indexOf;
            index++;
        }
        return true;
    }
    exports.matches = matches;
});
/*!
END THIRD PARTY
*/ 

define(__m[426/*vs/base/common/stopwatch*/], __M([1/*require*/,0/*exports*/,15/*vs/base/common/platform*/]), function (require, exports, platform_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var hasPerformanceNow = (platform_1.globals.performance && typeof platform_1.globals.performance.now === 'function');
    var StopWatch = (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;
});

define(__m[29/*vs/base/common/types*/], __M([1/*require*/,0/*exports*/]), 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 _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 a JavaScript Array and each element in the array is a string.
     */
    function isStringArray(value) {
        return isArray(value) && value.every(function (elem) { return isString(elem); });
    }
    exports.isStringArray = isStringArray;
    /**
     *
     * @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;
    /**
     * @returns whether the provided parameters is are JavaScript Function or not.
     */
    function areFunctions() {
        var objects = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            objects[_i] = arguments[_i];
        }
        return objects && objects.length > 0 && objects.every(isFunction);
    }
    exports.areFunctions = areFunctions;
    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)) {
            if (arg instanceof constraint) {
                return;
            }
            if (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;
    /**
     * Creates a new object of the provided class and will call the constructor with
     * any additional argument supplied.
     */
    function create(ctor) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        var obj = Object.create(ctor.prototype);
        ctor.apply(obj, args);
        return obj;
    }
    exports.create = create;
});

define(__m[428/*vs/base/common/graph*/], __M([1/*require*/,0/*exports*/,29/*vs/base/common/types*/,157/*vs/base/common/collections*/]), function (require, exports, types_1, collections_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function newNode(data) {
        return {
            data: data,
            incoming: Object.create(null),
            outgoing: Object.create(null)
        };
    }
    var Graph = (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.traverse = function (start, inwards, callback) {
            var startNode = this.lookup(start);
            if (!startNode) {
                return;
            }
            this._traverse(startNode, inwards, Object.create(null), callback);
        };
        Graph.prototype._traverse = function (node, inwards, seen, callback) {
            var _this = this;
            var key = this._hashFn(node.data);
            if (seen[key]) {
                return;
            }
            seen[key] = true;
            callback(node.data);
            var nodes = inwards ? node.outgoing : node.incoming;
            collections_1.forEach(nodes, function (entry) { return _this._traverse(entry.value, inwards, seen, callback); });
        };
        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.lookup = function (data) {
            return this._nodes[this._hashFn(data)];
        };
        Object.defineProperty(Graph.prototype, "length", {
            get: function () {
                return Object.keys(this._nodes).length;
            },
            enumerable: true,
            configurable: 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[26/*vs/base/common/objects*/], __M([1/*require*/,0/*exports*/,29/*vs/base/common/types*/]), function (require, exports, types_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function clone(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] = clone(obj[key]);
            }
            else {
                result[key] = obj[key];
            }
        });
        return result;
    }
    exports.clone = clone;
    function deepClone(obj) {
        if (!obj || typeof obj !== 'object') {
            return obj;
        }
        var result = (Array.isArray(obj)) ? [] : {};
        Object.getOwnPropertyNames(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;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    function cloneAndChange(obj, changer) {
        return _cloneAndChange(obj, changer, []);
    }
    exports.cloneAndChange = cloneAndChange;
    function _cloneAndChange(obj, changer, encounteredObjects) {
        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 i1 = 0; i1 < obj.length; i1++) {
                r1.push(_cloneAndChange(obj[i1], changer, encounteredObjects));
            }
            return r1;
        }
        if (types_1.isObject(obj)) {
            if (encounteredObjects.indexOf(obj) >= 0) {
                throw new Error('Cannot clone recursive data-structure');
            }
            encounteredObjects.push(obj);
            var r2 = {};
            for (var i2 in obj) {
                if (hasOwnProperty.call(obj, i2)) {
                    r2[i2] = _cloneAndChange(obj[i2], changer, encounteredObjects);
                }
            }
            encounteredObjects.pop();
            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 toObject(arr, keyMap) {
        return arr.reduce(function (o, d) {
            return assign(o, (_a = {}, _a[keyMap(d)] = d, _a));
            var _a;
        }, Object.create(null));
    }
    exports.toObject = toObject;
    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 ensureProperty(obj, property, defaultValue) {
        if (typeof obj[property] === 'undefined') {
            obj[property] = defaultValue;
        }
    }
    exports.ensureProperty = ensureProperty;
    function arrayToHash(array) {
        var result = {};
        for (var i = 0; i < array.length; ++i) {
            result[array[i]] = true;
        }
        return result;
    }
    exports.arrayToHash = arrayToHash;
    /**
     * Given an array of strings, returns a function which, given a string
     * returns true or false whether the string is in that array.
     */
    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);
            };
        }
    }
    exports.createKeywordMatcher = createKeywordMatcher;
    /**
     * Started from TypeScript's __extends function to make a type a subclass of a specific class.
     * Modified to work with properties already defined on the derivedClass, since we can't get TS
     * to call this method before the constructor definition.
     */
    function derive(baseClass, derivedClass) {
        for (var prop in baseClass) {
            if (baseClass.hasOwnProperty(prop)) {
                derivedClass[prop] = baseClass[prop];
            }
        }
        derivedClass = derivedClass || function () { };
        var basePrototype = baseClass.prototype;
        var derivedPrototype = derivedClass.prototype;
        derivedClass.prototype = Object.create(basePrototype);
        for (var prop in derivedPrototype) {
            if (derivedPrototype.hasOwnProperty(prop)) {
                // handle getters and setters properly
                Object.defineProperty(derivedClass.prototype, prop, Object.getOwnPropertyDescriptor(derivedPrototype, prop));
            }
        }
        // Cast to any due to Bug 16188:PropertyDescriptor set and get function should be optional.
        Object.defineProperty(derivedClass.prototype, 'constructor', { value: derivedClass, writable: true, configurable: true, enumerable: true });
    }
    exports.derive = derive;
    /**
     * Calls JSON.Stringify with a replacer to break apart any circular references.
     * This prevents JSON.stringify from throwing the exception
     *  "Uncaught TypeError: Converting circular structure to JSON"
     */
    function safeStringify(obj) {
        var seen = [];
        return JSON.stringify(obj, function (key, value) {
            if (types_1.isObject(value) || Array.isArray(value)) {
                if (seen.indexOf(value) !== -1) {
                    return '[Circular]';
                }
                else {
                    seen.push(value);
                }
            }
            return value;
        });
    }
    exports.safeStringify = safeStringify;
    function getOrDefault(obj, fn, defaultValue) {
        if (defaultValue === void 0) { defaultValue = null; }
        var result = fn(obj);
        return typeof result === 'undefined' ? defaultValue : result;
    }
    exports.getOrDefault = getOrDefault;
    function distinct(base, target) {
        var result = Object.create(null);
        if (!base || !target) {
            return result;
        }
        var targetKeys = Object.keys(target);
        targetKeys.forEach(function (k) {
            var baseValue = base[k];
            var targetValue = target[k];
            if (!equals(baseValue, targetValue)) {
                result[k] = targetValue;
            }
        });
        return result;
    }
    exports.distinct = distinct;
});

define(__m[24/*vs/base/common/uri*/], __M([1/*require*/,0/*exports*/,15/*vs/base/common/platform*/]), function (require, exports, platform) {
    /*---------------------------------------------------------------------------------------------
     *  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 });
    function _encode(ch) {
        return '%' + ch.charCodeAt(0).toString(16).toUpperCase();
    }
    // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
    function encodeURIComponent2(str) {
        return encodeURIComponent(str).replace(/[!'()*]/g, _encode);
    }
    function encodeNoop(str) {
        return str.replace(/[#?]/, _encode);
    }
    /**
     * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
     * This class is a simple parser which creates the basic component paths
     * (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 = (function () {
        /**
         * @internal
         */
        function URI(scheme, authority, path, query, fragment) {
            this._formatted = null;
            this._fsPath = null;
            this.scheme = scheme || URI._empty;
            this.authority = authority || URI._empty;
            this.path = path || URI._empty;
            this.query = query || URI._empty;
            this.fragment = fragment || URI._empty;
            this._validate(this);
        }
        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';
        };
        Object.defineProperty(URI.prototype, "fsPath", {
            // ---- filesystem path -----------------------
            /**
             * Returns a string representing the corresponding file system path of this URI.
             * Will handle UNC paths and normalize windows drive letters to lower-case. Also
             * 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.
             */
            get: function () {
                if (!this._fsPath) {
                    var value = void 0;
                    if (this.authority && this.path && this.scheme === 'file') {
                        // unc path: file://shares/c$/far/boo
                        value = "//" + this.authority + this.path;
                    }
                    else if (URI._driveLetterPath.test(this.path)) {
                        // windows drive letter: file:///c:/far/boo
                        value = this.path[1].toLowerCase() + this.path.substr(2);
                    }
                    else {
                        // other path
                        value = this.path;
                    }
                    if (platform.isWindows) {
                        value = value.replace(/\//g, '\\');
                    }
                    this._fsPath = value;
                }
                return this._fsPath;
            },
            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 === void 0) {
                scheme = this.scheme;
            }
            else if (scheme === null) {
                scheme = '';
            }
            if (authority === void 0) {
                authority = this.authority;
            }
            else if (authority === null) {
                authority = '';
            }
            if (path === void 0) {
                path = this.path;
            }
            else if (path === null) {
                path = '';
            }
            if (query === void 0) {
                query = this.query;
            }
            else if (query === null) {
                query = '';
            }
            if (fragment === void 0) {
                fragment = this.fragment;
            }
            else if (fragment === null) {
                fragment = '';
            }
            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 ------------------------
        URI.parse = function (value) {
            var match = URI._regexp.exec(value);
            if (!match) {
                return new URI(URI._empty, URI._empty, URI._empty, URI._empty, URI._empty);
            }
            return new URI(match[2] || URI._empty, decodeURIComponent(match[4] || URI._empty), decodeURIComponent(match[5] || URI._empty), decodeURIComponent(match[7] || URI._empty), decodeURIComponent(match[9] || URI._empty));
        };
        URI.file = function (path) {
            var authority = URI._empty;
            // normalize to fwd-slashes on windows,
            // on other systems bwd-slashes are valid
            // filename character, eg /f\oo/ba\r.txt
            if (platform.isWindows) {
                path = path.replace(/\\/g, URI._slash);
            }
            // check for authority as used in UNC shares
            // or use the path as given
            if (path[0] === URI._slash && path[0] === path[1]) {
                var idx = path.indexOf(URI._slash, 2);
                if (idx === -1) {
                    authority = path.substring(2);
                    path = URI._empty;
                }
                else {
                    authority = path.substring(2, idx);
                    path = path.substring(idx);
                }
            }
            // Ensure that path starts with a slash
            // or that it is at least a slash
            if (path[0] !== URI._slash) {
                path = URI._slash + path;
            }
            return new URI('file', authority, path, URI._empty, URI._empty);
        };
        URI.from = function (components) {
            return new URI(components.scheme, components.authority, components.path, components.query, components.fragment);
        };
        URI.prototype._validate = function (ret) {
            // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
            // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
            if (ret.scheme && !URI._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 (!URI._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 (URI._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 ("//")');
                    }
                }
            }
        };
        // ---- printing/externalize ---------------------------
        /**
         *
         * @param skipEncoding Do not encode the result, default is `false`
         */
        URI.prototype.toString = function (skipEncoding) {
            if (skipEncoding === void 0) { skipEncoding = false; }
            if (!skipEncoding) {
                if (!this._formatted) {
                    this._formatted = URI._asFormatted(this, false);
                }
                return this._formatted;
            }
            else {
                // we don't cache that
                return URI._asFormatted(this, true);
            }
        };
        URI._asFormatted = function (uri, skipEncoding) {
            var encoder = !skipEncoding
                ? encodeURIComponent2
                : encodeNoop;
            var parts = [];
            var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment;
            if (scheme) {
                parts.push(scheme, ':');
            }
            if (authority || scheme === 'file') {
                parts.push('//');
            }
            if (authority) {
                authority = authority.toLowerCase();
                var idx = authority.indexOf(':');
                if (idx === -1) {
                    parts.push(encoder(authority));
                }
                else {
                    parts.push(encoder(authority.substr(0, idx)), authority.substr(idx));
                }
            }
            if (path) {
                // lower-case windows drive letters in /C:/fff or C:/fff
                var m = URI._upperCaseDrive.exec(path);
                if (m) {
                    if (m[1]) {
                        path = '/' + m[2].toLowerCase() + path.substr(3); // "/c:".length === 3
                    }
                    else {
                        path = m[2].toLowerCase() + path.substr(2); // // "c:".length === 2
                    }
                }
                // encode every segement but not slashes
                // make sure that # and ? are always encoded
                // when occurring in paths - otherwise the result
                // cannot be parsed back again
                var lastIdx = 0;
                while (true) {
                    var idx = path.indexOf(URI._slash, lastIdx);
                    if (idx === -1) {
                        parts.push(encoder(path.substring(lastIdx)));
                        break;
                    }
                    parts.push(encoder(path.substring(lastIdx, idx)), URI._slash);
                    lastIdx = idx + 1;
                }
                ;
            }
            if (query) {
                parts.push('?', encoder(query));
            }
            if (fragment) {
                parts.push('#', encoder(fragment));
            }
            return parts.join(URI._empty);
        };
        URI.prototype.toJSON = function () {
            var res = {
                fsPath: this.fsPath,
                external: this.toString(),
                $mid: 1
            };
            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;
        };
        URI.revive = function (data) {
            var result = new URI(data.scheme, data.authority, data.path, data.query, data.fragment);
            result._fsPath = data.fsPath;
            result._formatted = data.external;
            return result;
        };
        URI._empty = '';
        URI._slash = '/';
        URI._regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
        URI._driveLetterPath = /^\/[a-zA-z]:/;
        URI._upperCaseDrive = /^(\/)?([A-Z]:)/;
        URI._schemePattern = /^\w[\w\d+.-]*$/;
        URI._singleSlashStart = /^\//;
        URI._doubleSlashStart = /^\/\//;
        return URI;
    }());
    exports.default = URI;
});

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










define(__m[80/*vs/base/common/map*/], __M([1/*require*/,0/*exports*/,24/*vs/base/common/uri*/]), function (require, exports, uri_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function values(map) {
        var result = [];
        map.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;
    function getOrSet(map, key, value) {
        var result = map.get(key);
        if (result === void 0) {
            result = value;
            map.set(key, result);
        }
        return result;
    }
    exports.getOrSet = getOrSet;
    /**
     * A simple Map<T> that optionally allows to set a limit of entries to store. Once the limit is hit,
     * the cache will remove the entry that was last recently added. Or, if a ratio is provided below 1,
     * all elements will be removed until the ratio is full filled (e.g. 0.75 to remove 25% of old elements).
     */
    var BoundedMap = (function () {
        function BoundedMap(limit, ratio, value) {
            if (limit === void 0) { limit = Number.MAX_VALUE; }
            if (ratio === void 0) { ratio = 1; }
            var _this = this;
            this.limit = limit;
            this.map = new Map();
            this.ratio = limit * ratio;
            if (value) {
                value.entries.forEach(function (entry) {
                    _this.set(entry.key, entry.value);
                });
            }
        }
        BoundedMap.prototype.setLimit = function (limit) {
            if (limit < 0) {
                return; // invalid limit
            }
            this.limit = limit;
            while (this.map.size > this.limit) {
                this.trim();
            }
        };
        BoundedMap.prototype.serialize = function () {
            var serialized = { entries: [] };
            this.map.forEach(function (entry) {
                serialized.entries.push({ key: entry.key, value: entry.value });
            });
            return serialized;
        };
        Object.defineProperty(BoundedMap.prototype, "size", {
            get: function () {
                return this.map.size;
            },
            enumerable: true,
            configurable: true
        });
        BoundedMap.prototype.set = function (key, value) {
            if (this.map.has(key)) {
                return false; // already present!
            }
            var entry = { key: key, value: value };
            this.push(entry);
            if (this.size > this.limit) {
                this.trim();
            }
            return true;
        };
        BoundedMap.prototype.get = function (key) {
            var entry = this.map.get(key);
            return entry ? entry.value : null;
        };
        BoundedMap.prototype.getOrSet = function (k, t) {
            var res = this.get(k);
            if (res) {
                return res;
            }
            this.set(k, t);
            return t;
        };
        BoundedMap.prototype.delete = function (key) {
            var entry = this.map.get(key);
            if (entry) {
                this.map.delete(key);
                if (entry.next) {
                    entry.next.prev = entry.prev; // [A]<-[x]<-[C] = [A]<-[C]
                }
                else {
                    this.head = entry.prev; // [A]-[x] = [A]
                }
                if (entry.prev) {
                    entry.prev.next = entry.next; // [A]->[x]->[C] = [A]->[C]
                }
                else {
                    this.tail = entry.next; // [x]-[A] = [A]
                }
                return entry.value;
            }
            return null;
        };
        BoundedMap.prototype.has = function (key) {
            return this.map.has(key);
        };
        BoundedMap.prototype.clear = function () {
            this.map.clear();
            this.head = null;
            this.tail = null;
        };
        BoundedMap.prototype.push = function (entry) {
            if (this.head) {
                // [A]-[B] = [A]-[B]->[X]
                entry.prev = this.head;
                this.head.next = entry;
            }
            if (!this.tail) {
                this.tail = entry;
            }
            this.head = entry;
            this.map.set(entry.key, entry);
        };
        BoundedMap.prototype.trim = function () {
            if (this.tail) {
                // Remove all elements until ratio is reached
                if (this.ratio < this.limit) {
                    var index = 0;
                    var current = this.tail;
                    while (current.next) {
                        // Remove the entry
                        this.map.delete(current.key);
                        // if we reached the element that overflows our ratio condition
                        // make its next element the new tail of the Map and adjust the size
                        if (index === this.ratio) {
                            this.tail = current.next;
                            this.tail.prev = null;
                            break;
                        }
                        // Move on
                        current = current.next;
                        index++;
                    }
                }
                else {
                    this.map.delete(this.tail.key);
                    // [x]-[B] = [B]
                    this.tail = this.tail.next;
                    if (this.tail) {
                        this.tail.prev = null;
                    }
                }
            }
        };
        return BoundedMap;
    }());
    exports.BoundedMap = BoundedMap;
    // --- trie'ish datastructure
    var Node = (function () {
        function Node() {
            this.children = new Map();
        }
        return Node;
    }());
    /**
     * A trie map that allows for fast look up when keys are substrings
     * to the actual search keys (dir/subdir-problem).
     */
    var TrieMap = (function () {
        function TrieMap(splitter) {
            this._root = new Node();
            this._splitter = function (s) { return splitter(s).filter(function (s) { return Boolean(s); }); };
        }
        TrieMap.prototype.insert = function (path, element) {
            var parts = this._splitter(path);
            var i = 0;
            // find insertion node
            var node = this._root;
            for (; i < parts.length; i++) {
                var child = node.children.get(parts[i]);
                if (child) {
                    node = child;
                    continue;
                }
                break;
            }
            // create new nodes
            var newNode;
            for (; i < parts.length; i++) {
                newNode = new Node();
                node.children.set(parts[i], newNode);
                node = newNode;
            }
            node.element = element;
        };
        TrieMap.prototype.lookUp = function (path) {
            var parts = this._splitter(path);
            var children = this._root.children;
            var node;
            for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
                var part = parts_1[_i];
                node = children.get(part);
                if (!node) {
                    return undefined;
                }
                children = node.children;
            }
            return node.element;
        };
        TrieMap.prototype.findSubstr = function (path) {
            var parts = this._splitter(path);
            var lastNode;
            var children = this._root.children;
            for (var _i = 0, parts_2 = parts; _i < parts_2.length; _i++) {
                var part = parts_2[_i];
                var node = children.get(part);
                if (!node) {
                    break;
                }
                if (node.element) {
                    lastNode = node;
                }
                children = node.children;
            }
            // return the last matching node
            // that had an element
            if (lastNode) {
                return lastNode.element;
            }
            return undefined;
        };
        TrieMap.prototype.findSuperstr = function (path) {
            var parts = this._splitter(path);
            var children = this._root.children;
            var node;
            for (var _i = 0, parts_3 = parts; _i < parts_3.length; _i++) {
                var part = parts_3[_i];
                node = children.get(part);
                if (!node) {
                    return undefined;
                }
                children = node.children;
            }
            var result = new TrieMap(this._splitter);
            result._root = node;
            return result;
        };
        TrieMap.PathSplitter = function (s) { return s.split(/[\\/]/).filter(function (s) { return !!s; }); };
        return TrieMap;
    }());
    exports.TrieMap = TrieMap;
    var ResourceMap = (function () {
        function ResourceMap(ignoreCase) {
            this.ignoreCase = ignoreCase;
            this.map = new Map();
        }
        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.has = function (resource) {
            return this.map.has(this.toKey(resource));
        };
        Object.defineProperty(ResourceMap.prototype, "size", {
            get: function () {
                return this.map.size;
            },
            enumerable: true,
            configurable: true
        });
        ResourceMap.prototype.clear = function () {
            this.map.clear();
        };
        ResourceMap.prototype.delete = function (resource) {
            return this.map.delete(this.toKey(resource));
        };
        ResourceMap.prototype.forEach = function (clb) {
            this.map.forEach(clb);
        };
        ResourceMap.prototype.values = function () {
            return values(this.map);
        };
        ResourceMap.prototype.toKey = function (resource) {
            var key = resource.toString();
            if (this.ignoreCase) {
                key = key.toLowerCase();
            }
            return key;
        };
        return ResourceMap;
    }());
    exports.ResourceMap = ResourceMap;
    var StrictResourceMap = (function (_super) {
        __extends(StrictResourceMap, _super);
        function StrictResourceMap() {
            return _super.call(this) || this;
        }
        StrictResourceMap.prototype.keys = function () {
            return keys(this.map).map(function (key) { return uri_1.default.parse(key); });
        };
        return StrictResourceMap;
    }(ResourceMap));
    exports.StrictResourceMap = StrictResourceMap;
    var Touch;
    (function (Touch) {
        Touch.None = 0;
        Touch.First = 1;
        Touch.Last = 2;
    })(Touch = exports.Touch || (exports.Touch = {}));
    var LinkedMap = (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;
        };
        LinkedMap.prototype.isEmpty = function () {
            return !this._head && !this._tail;
        };
        Object.defineProperty(LinkedMap.prototype, "size", {
            get: function () {
                return this._size;
            },
            enumerable: true,
            configurable: true
        });
        LinkedMap.prototype.has = function (key) {
            return this._map.has(key);
        };
        LinkedMap.prototype.get = function (key) {
            var item = this._map.get(key);
            if (!item) {
                return undefined;
            }
            return item.value;
        };
        LinkedMap.prototype.set = function (key, value, touch) {
            if (touch === void 0) { touch = Touch.None; }
            var item = this._map.get(key);
            if (item) {
                item.value = value;
                if (touch !== Touch.None) {
                    this.touch(item, touch);
                }
            }
            else {
                item = { key: key, value: value, next: undefined, previous: undefined };
                switch (touch) {
                    case Touch.None:
                        this.addItemLast(item);
                        break;
                    case Touch.First:
                        this.addItemFirst(item);
                        break;
                    case Touch.Last:
                        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.shift = function () {
            if (!this._head && !this._tail) {
                return undefined;
            }
            if (!this._head || !this._tail) {
                throw new Error('Invalid list');
            }
            var item = this._head;
            this._map.delete(item.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;
            }
        };
        LinkedMap.prototype.forEachReverse = function (callbackfn, thisArg) {
            var current = this._tail;
            while (current) {
                if (thisArg) {
                    callbackfn.bind(thisArg)(current.value, current.key, this);
                }
                else {
                    callbackfn(current.value, current.key, this);
                }
                current = current.previous;
            }
        };
        LinkedMap.prototype.values = function () {
            var result = [];
            var current = this._head;
            while (current) {
                result.push(current.value);
                current = current.next;
            }
            return result;
        };
        LinkedMap.prototype.keys = function () {
            var result = [];
            var current = this._head;
            while (current) {
                result.push(current.key);
                current = current.next;
            }
            return result;
        };
        /* VS Code / Monaco editor runs on es5 which has no Symbol.iterator
        public keys(): IterableIterator<K> {
            let current = this._head;
            let iterator: IterableIterator<K> = {
                [Symbol.iterator]() {
                    return iterator;
                },
                next():IteratorResult<K> {
                    if (current) {
                        let result = { value: current.key, done: false };
                        current = current.next;
                        return result;
                    } else {
                        return { value: undefined, done: true };
                    }
                }
            };
            return iterator;
        }
    
        public values(): IterableIterator<V> {
            let current = this._head;
            let iterator: IterableIterator<V> = {
                [Symbol.iterator]() {
                    return iterator;
                },
                next():IteratorResult<V> {
                    if (current) {
                        let result = { value: current.value, done: false };
                        current = current.next;
                        return result;
                    } else {
                        return { value: undefined, done: true };
                    }
                }
            };
            return iterator;
        }
        */
        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._head = item.next;
            }
            else if (item === this._tail) {
                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;
            }
        };
        LinkedMap.prototype.touch = function (item, touch) {
            if (!this._head || !this._tail) {
                throw new Error('Invalid list');
            }
            if ((touch !== Touch.First && touch !== Touch.Last)) {
                return;
            }
            if (touch === Touch.First) {
                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 === Touch.Last) {
                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;
            }
        };
        return LinkedMap;
    }());
    exports.LinkedMap = LinkedMap;
});

define(__m[487/*vs/base/common/marshalling*/], __M([1/*require*/,0/*exports*/,24/*vs/base/common/uri*/]), function (require, exports, uri_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function stringify(obj) {
        return JSON.stringify(obj, replacer);
    }
    exports.stringify = stringify;
    function parse(text) {
        return JSON.parse(text, reviver);
    }
    exports.parse = parse;
    function replacer(key, value) {
        // URI is done via toJSON-member
        if (value instanceof RegExp) {
            return {
                $mid: 2,
                source: value.source,
                flags: (value.global ? 'g' : '') + (value.ignoreCase ? 'i' : '') + (value.multiline ? 'm' : ''),
            };
        }
        return value;
    }
    function reviver(key, value) {
        var marshallingConst;
        if (value !== void 0 && value !== null) {
            marshallingConst = value.$mid;
        }
        switch (marshallingConst) {
            case 1: return uri_1.default.revive(value);
            case 2: return new RegExp(value.source, value.flags);
            default: return value;
        }
    }
});

define(__m[9/*vs/base/common/strings*/], __M([1/*require*/,0/*exports*/,80/*vs/base/common/map*/]), function (require, exports, map_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * 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 '&lt;';
                case '>': return '&gt;';
                case '&': return '&amp;';
                default: return match;
            }
        });
    }
    exports.escape = escape;
    /**
     * Escapes regular expression characters in a given string
     */
    function escapeRegExpCharacters(value) {
        return value.replace(/[\-\\\{\}\*\+\?\|\^\$\.\[\]\(\)\#]/g, '\\$&');
    }
    exports.escapeRegExpCharacters = escapeRegExpCharacters;
    /**
     * Removes all occurrences of needle from the beginning and end of haystack.
     * @param haystack string to trim
     * @param needle the thing to trim (default is a blank)
     */
    function trim(haystack, needle) {
        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, idx = -1;
        while ((idx = 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;
    function stripWildcards(pattern) {
        return pattern.replace(/\*/g, '');
    }
    exports.stripWildcards = stripWildcards;
    /**
     * Determines if haystack starts with needle.
     */
    function startsWith(haystack, needle) {
        if (haystack.length < needle.length) {
            return false;
        }
        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 indexOfIgnoreCase(haystack, needle, position) {
        if (position === void 0) { position = 0; }
        var index = haystack.indexOf(needle, position);
        if (index < 0) {
            if (position > 0) {
                haystack = haystack.substr(position);
            }
            needle = escapeRegExpCharacters(needle);
            index = haystack.search(new RegExp(needle, 'i'));
        }
        return index;
    }
    exports.indexOfIgnoreCase = indexOfIgnoreCase;
    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';
        }
        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 === '$') {
            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;
    /**
     * The normalize() method returns the Unicode Normalization Form of a given string. The form will be
     * the Normalization Form Canonical Composition.
     *
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize}
     */
    exports.canNormalize = typeof (''.normalize) === 'function';
    var nonAsciiCharactersPattern = /[^\u0000-\u0080]/;
    var normalizedCache = new map_1.BoundedMap(10000); // bounded to 10000 elements
    function normalizeNFC(str) {
        if (!exports.canNormalize || !str) {
            return str;
        }
        var cached = normalizedCache.get(str);
        if (cached) {
            return cached;
        }
        var res;
        if (nonAsciiCharactersPattern.test(str)) {
            res = str.normalize('NFC');
        }
        else {
            res = str;
        }
        // Use the cache for fast lookup
        normalizedCache.set(str, res);
        return res;
    }
    exports.normalizeNFC = normalizeNFC;
    /**
     * Returns first index of the string that is not whitespace.
     * If string is empty or contains only whitespaces, returns -1
     */
    function firstNonWhitespaceIndex(str) {
        for (var i = 0, len = str.length; i < len; i++) {
            var chCode = str.charCodeAt(i);
            if (chCode !== 32 /* Space */ && chCode !== 9 /* Tab */) {
                return i;
            }
        }
        return -1;
    }
    exports.firstNonWhitespaceIndex = firstNonWhitespaceIndex;
    /**
     * Returns the leading whitespace of the string.
     * If the string contains only whitespaces, returns entire string
     */
    function getLeadingWhitespace(str, start, end) {
        if (start === void 0) { start = 0; }
        if (end === void 0) { end = str.length; }
        for (var i = start; i < end; i++) {
            var chCode = str.charCodeAt(i);
            if (chCode !== 32 /* Space */ && chCode !== 9 /* Tab */) {
                return str.substring(start, i);
            }
        }
        return str.substring(start, end);
    }
    exports.getLeadingWhitespace = getLeadingWhitespace;
    /**
     * Returns last index of the string that is not whitespace.
     * If string is empty or contains only whitespaces, returns -1
     */
    function lastNonWhitespaceIndex(str, startIndex) {
        if (startIndex === void 0) { startIndex = str.length - 1; }
        for (var i = startIndex; i >= 0; i--) {
            var chCode = str.charCodeAt(i);
            if (chCode !== 32 /* Space */ && chCode !== 9 /* Tab */) {
                return i;
            }
        }
        return -1;
    }
    exports.lastNonWhitespaceIndex = lastNonWhitespaceIndex;
    function compare(a, b) {
        if (a < b) {
            return -1;
        }
        else if (a > b) {
            return 1;
        }
        else {
            return 0;
        }
    }
    exports.compare = compare;
    function compareIgnoreCase(a, b) {
        var len = Math.min(a.length, b.length);
        for (var i = 0; i < len; i++) {
            var codeA = a.charCodeAt(i);
            var codeB = b.charCodeAt(i);
            if (codeA === codeB) {
                // equal
                continue;
            }
            if (isUpperAsciiLetter(codeA)) {
                codeA += 32;
            }
            if (isUpperAsciiLetter(codeB)) {
                codeB += 32;
            }
            var diff = codeA - codeB;
            if (diff === 0) {
                // equal -> ignoreCase
                continue;
            }
            else if (isLowerAsciiLetter(codeA) && isLowerAsciiLetter(codeB)) {
                //
                return diff;
            }
            else {
                return compare(a.toLowerCase(), b.toLowerCase());
            }
        }
        if (a.length < b.length) {
            return -1;
        }
        else if (a.length > b.length) {
            return 1;
        }
        else {
            return 0;
        }
    }
    exports.compareIgnoreCase = compareIgnoreCase;
    function isLowerAsciiLetter(code) {
        return code >= 97 /* a */ && code <= 122 /* z */;
    }
    function isUpperAsciiLetter(code) {
        return code >= 65 /* A */ && code <= 90 /* Z */;
    }
    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;
                }
            }
            else {
                if (String.fromCharCode(codeA).toLowerCase() !== String.fromCharCode(codeB).toLowerCase()) {
                    return false;
                }
            }
        }
        return true;
    }
    function beginsWithIgnoreCase(str, candidate) {
        var candidateLength = candidate.length;
        if (candidate.length > str.length) {
            return false;
        }
        return doEqualsIgnoreCase(str, candidate, candidateLength);
    }
    exports.beginsWithIgnoreCase = beginsWithIgnoreCase;
    /**
     * @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;
    function substrEquals(a, aStart, aEnd, b, bStart, bEnd) {
        while (aStart < aEnd && bStart < bEnd) {
            if (a[aStart] !== b[bStart]) {
                return false;
            }
            aStart += 1;
            bStart += 1;
        }
        return true;
    }
    /**
     * Return the overlap between the suffix of `a` and the prefix of `b`.
     * For instance `overlap("foobar", "arr, I'm a pirate") === 2`.
     */
    function overlap(a, b) {
        var aEnd = a.length;
        var bEnd = b.length;
        var aStart = aEnd - bEnd;
        if (aStart === 0) {
            return a === b ? aEnd : 0;
        }
        else if (aStart < 0) {
            bEnd += aStart;
            aStart = 0;
        }
        while (aStart < aEnd && bEnd > 0) {
            if (substrEquals(a, aStart, aEnd, b, 0, bEnd)) {
                return bEnd;
            }
            bEnd -= 1;
            aStart += 1;
        }
        return 0;
    }
    exports.overlap = overlap;
    // --- 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 {
    //	let chrCode = str.charCodeAt(index);
    //	if (0xD800 <= chrCode && chrCode <= 0xDBFF && index + 1 < len) {
    //		let 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;
    /**
     * Computes the difference score for two strings. More similar strings have a higher score.
     * We use largest common subsequence dynamic programming approach but penalize in the end for length differences.
     * Strings that have a large length difference will get a bad default score 0.
     * Complexity - both time and space O(first.length * second.length)
     * Dynamic programming LCS computation http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
     *
     * @param first a string
     * @param second a string
     */
    function difference(first, second, maxLenDelta) {
        if (maxLenDelta === void 0) { maxLenDelta = 4; }
        var lengthDifference = Math.abs(first.length - second.length);
        // We only compute score if length of the currentWord and length of entry.name are similar.
        if (lengthDifference > maxLenDelta) {
            return 0;
        }
        // Initialize LCS (largest common subsequence) matrix.
        var LCS = [];
        var zeroArray = [];
        var i, j;
        for (i = 0; i < second.length + 1; ++i) {
            zeroArray.push(0);
        }
        for (i = 0; i < first.length + 1; ++i) {
            LCS.push(zeroArray);
        }
        for (i = 1; i < first.length + 1; ++i) {
            for (j = 1; j < second.length + 1; ++j) {
                if (first[i - 1] === second[j - 1]) {
                    LCS[i][j] = LCS[i - 1][j - 1] + 1;
                }
                else {
                    LCS[i][j] = Math.max(LCS[i - 1][j], LCS[i][j - 1]);
                }
            }
        }
        return LCS[first.length][second.length] - Math.sqrt(lengthDifference);
    }
    exports.difference = difference;
    /**
     * Returns an array in which every entry is the offset of a
     * line. There is always one entry which is zero.
     */
    function computeLineStarts(text) {
        var regexp = /\r\n|\r|\n/g, ret = [0], match;
        while ((match = regexp.exec(text))) {
            ret.push(regexp.lastIndex);
        }
        return ret;
    }
    exports.computeLineStarts = computeLineStarts;
    /**
     * Given a string and a max length returns a shorted version. Shorting
     * happens at favorable positions - such as whitespace or punctuation characters.
     */
    function lcut(text, n) {
        if (text.length < n) {
            return text;
        }
        var segments = text.split(/\b/), count = 0;
        for (var i = segments.length - 1; i >= 0; i--) {
            count += segments[i].length;
            if (count > n) {
                segments.splice(0, i);
                break;
            }
        }
        return segments.join(exports.empty).replace(/^\s/, exports.empty);
    }
    exports.lcut = lcut;
    // Escape codes
    // http://en.wikipedia.org/wiki/ANSI_escape_code
    var EL = /\x1B\x5B[12]?K/g; // Erase in line
    var COLOR_START = /\x1b\[\d+m/g; // Color
    var COLOR_END = /\x1b\[0?m/g; // Color
    function removeAnsiEscapeCodes(str) {
        if (str) {
            str = str.replace(EL, '');
            str = str.replace(COLOR_START, '');
            str = str.replace(COLOR_END, '');
        }
        return str;
    }
    exports.removeAnsiEscapeCodes = removeAnsiEscapeCodes;
    // -- 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;
    /**
     * Appends two strings. If the appended result is longer than maxLength,
     * trims the start of the result and replaces it with '...'.
     */
    function appendWithLimit(first, second, maxLength) {
        var newLength = first.length + second.length;
        if (newLength > maxLength) {
            first = '...' + first.substr(newLength - maxLength);
        }
        if (second.length > maxLength) {
            first += second.substr(second.length - maxLength);
        }
        else {
            first += second;
        }
        return first;
    }
    exports.appendWithLimit = appendWithLimit;
    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;
});

define(__m[512/*vs/base/browser/ui/octiconLabel/octiconLabel*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/]), function (require, exports, strings_1) {
    "use strict";
    function expand(text) {
        return text;
    }
    var MockOcticonLabel = (function () {
        function MockOcticonLabel(container) {
            this._container = container;
        }
        Object.defineProperty(MockOcticonLabel.prototype, "text", {
            set: function (text) {
                var innerHTML = text || '';
                innerHTML = strings_1.escape(innerHTML);
                innerHTML = expand(innerHTML);
                this._container.innerHTML = innerHTML;
            },
            enumerable: true,
            configurable: true
        });
        return MockOcticonLabel;
    }());
    var mock = {
        expand: expand,
        OcticonLabel: MockOcticonLabel
    };
    return mock;
});

define(__m[81/*vs/base/common/filters*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,80/*vs/base/common/map*/]), function (require, exports, strings, map_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    // 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;
    /**
     * @returns A filter which combines the provided set
     * of filters with an and. The combines matches are
     * returned if *all* filters match.
     */
    function and() {
        var filter = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            filter[_i] = arguments[_i];
        }
        return function (word, wordToMatchAgainst) {
            var result = [];
            for (var i = 0, len = filter.length; i < len; i++) {
                var match = filter[i](word, wordToMatchAgainst);
                if (!match) {
                    return null;
                }
                result = result.concat(match);
            }
            return result;
        };
    }
    exports.and = and;
    // Prefix
    exports.matchesStrictPrefix = _matchesPrefix.bind(undefined, false);
    exports.matchesPrefix = _matchesPrefix.bind(undefined, true);
    function _matchesPrefix(ignoreCase, word, wordToMatchAgainst) {
        if (!wordToMatchAgainst || wordToMatchAgainst.length < word.length) {
            return null;
        }
        var matches;
        if (ignoreCase) {
            matches = strings.beginsWithIgnoreCase(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 _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 */;
    }
    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 */);
    }
    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 || 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;
        while (i < camelCaseWord.length && (result = _matchesCamelCase(word.toLowerCase(), camelCaseWord, 0, i)) === null) {
            i = nextAnchor(camelCaseWord, i + 1);
        }
        return result;
    }
    exports.matchesCamelCase = matchesCamelCase;
    // Matches beginning of words supporting non-ASCII languages
    // If `contiguous` is true then matches word with beginnings of the words in the target. E.g. "pul" will match "Git: Pull"
    // Otherwise also matches sub string of the word with beginnings of the words in the target. E.g. "gp" or "g p" will match "Git: Pull"
    // Useful in cases where the target is words (e.g. command labels)
    function matchesWords(word, target, contiguous) {
        if (contiguous === void 0) { contiguous = false; }
        if (!target || target.length === 0) {
            return null;
        }
        var result = null;
        var i = 0;
        while (i < target.length && (result = _matchesWords(word.toLowerCase(), target, 0, i, contiguous)) === null) {
            i = nextWord(target, i + 1);
        }
        return result;
    }
    exports.matchesWords = matchesWords;
    function _matchesWords(word, target, i, j, contiguous) {
        if (i === word.length) {
            return [];
        }
        else if (j === target.length) {
            return null;
        }
        else if (word[i] !== target[j].toLowerCase()) {
            return null;
        }
        else {
            var result = null;
            var nextWordIndex = j + 1;
            result = _matchesWords(word, target, i + 1, j + 1, contiguous);
            if (!contiguous) {
                while (!result && (nextWordIndex = nextWord(target, nextWordIndex)) < target.length) {
                    result = _matchesWords(word, target, i + 1, nextWordIndex, contiguous);
                    nextWordIndex++;
                }
            }
            return result === null ? null : join({ start: j, end: j + 1 }, result);
        }
    }
    function nextWord(word, start) {
        for (var i = start; i < word.length; i++) {
            var c = word.charCodeAt(i);
            if (isWhitespace(c) || (i > 0 && isWhitespace(word.charCodeAt(i - 1)))) {
                return i;
            }
        }
        return word.length;
    }
    // Fuzzy
    var SubstringMatching;
    (function (SubstringMatching) {
        SubstringMatching[SubstringMatching["Contiguous"] = 0] = "Contiguous";
        SubstringMatching[SubstringMatching["Separate"] = 1] = "Separate";
    })(SubstringMatching = exports.SubstringMatching || (exports.SubstringMatching = {}));
    exports.fuzzyContiguousFilter = or(exports.matchesPrefix, matchesCamelCase, matchesContiguousSubString);
    var fuzzySeparateFilter = or(exports.matchesPrefix, matchesCamelCase, matchesSubString);
    var fuzzyRegExpCache = new map_1.BoundedMap(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) : exports.fuzzyContiguousFilter(word, wordToMatchAgainst);
    }
    exports.matchesFuzzy = matchesFuzzy;
    function createMatches(position) {
        var ret = [];
        if (!position) {
            return ret;
        }
        var last;
        for (var _i = 0, position_1 = position; _i < position_1.length; _i++) {
            var pos = position_1[_i];
            if (last && last.end === pos) {
                last.end += 1;
            }
            else {
                last = { start: pos, end: pos + 1 };
                ret.push(last);
            }
        }
        return ret;
    }
    exports.createMatches = createMatches;
    function initTable() {
        var table = [];
        var row = [0];
        for (var i = 1; i <= 100; i++) {
            row.push(-i);
        }
        for (var i = 0; i <= 100; 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;
    }
    var _seps = Object.create(null);
    _seps['_'] = true;
    _seps['-'] = true;
    _seps['.'] = true;
    _seps[' '] = true;
    _seps['/'] = true;
    _seps['\\'] = true;
    _seps['\''] = true;
    _seps['"'] = true;
    _seps[':'] = true;
    var _ws = Object.create(null);
    _ws[' '] = true;
    _ws['\t'] = true;
    var Arrow;
    (function (Arrow) {
        Arrow[Arrow["Top"] = 1] = "Top";
        Arrow[Arrow["Diag"] = 2] = "Diag";
        Arrow[Arrow["Left"] = 4] = "Left";
    })(Arrow || (Arrow = {}));
    function fuzzyScore(pattern, word, patternMaxWhitespaceIgnore) {
        var patternLen = pattern.length > 100 ? 100 : pattern.length;
        var wordLen = word.length > 100 ? 100 : word.length;
        // Check for leading whitespace in the pattern and
        // start matching just after that position. This is
        // like `pattern = pattern.rtrim()` but doesn't create
        // a new string
        var patternStartPos = 0;
        if (patternMaxWhitespaceIgnore === undefined) {
            patternMaxWhitespaceIgnore = patternLen;
        }
        while (patternStartPos < patternMaxWhitespaceIgnore) {
            if (_ws[pattern[patternStartPos]]) {
                patternStartPos += 1;
            }
            else {
                break;
            }
        }
        if (patternStartPos === patternLen) {
            return [-100, []];
        }
        if (patternLen > wordLen) {
            return undefined;
        }
        var lowPattern = pattern.toLowerCase();
        var lowWord = word.toLowerCase();
        var patternPos = patternStartPos;
        var wordPos = 0;
        // 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
        while (patternPos < patternLen && wordPos < wordLen) {
            if (lowPattern[patternPos] === lowWord[wordPos]) {
                patternPos += 1;
            }
            wordPos += 1;
        }
        if (patternPos !== patternLen) {
            return undefined;
        }
        // There will be a mach, fill in tables
        for (patternPos = patternStartPos + 1; patternPos <= patternLen; patternPos++) {
            var lastLowWordChar = '';
            for (wordPos = 1; wordPos <= wordLen; wordPos++) {
                var score = -1;
                var lowWordChar = lowWord[wordPos - 1];
                if (lowPattern[patternPos - 1] === lowWordChar) {
                    if (wordPos === (patternPos - patternStartPos)) {
                        // common prefix: `foobar <-> foobaz`
                        if (pattern[patternPos - 1] === word[wordPos - 1]) {
                            score = 7;
                        }
                        else {
                            score = 5;
                        }
                    }
                    else if (lowWordChar !== word[wordPos - 1]) {
                        // hitting upper-case: `foo <-> forOthers`
                        if (pattern[patternPos - 1] === word[wordPos - 1]) {
                            score = 7;
                        }
                        else {
                            score = 5;
                        }
                    }
                    else if (_seps[lastLowWordChar]) {
                        // 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 */;
                    }
                }
                lastLowWordChar = lowWordChar;
            }
        }
        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));
        }
        // _bucket is an array of [PrefixArray] we use to keep
        // track of scores and matches. After calling `_findAllMatches`
        // the best match (if available) is the first item in the array
        _bucket.length = 0;
        _topScore = -100;
        _patternStartPos = patternStartPos;
        _findAllMatches(patternLen, wordLen, 0, new LazyArray(), false);
        if (_bucket.length === 0) {
            return undefined;
        }
        return [_topScore, _bucket[0].toArray()];
    }
    exports.fuzzyScore = fuzzyScore;
    var _bucket = [];
    var _topScore = 0;
    var _patternStartPos = 0;
    function _findAllMatches(patternPos, wordPos, total, matches, lastMatched) {
        if (_bucket.length >= 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
                wordPos -= 1;
                if (lastMatched) {
                    total -= 5; // new gap penalty
                }
                else if (!matches.isEmpty()) {
                    total -= 1; // gap penalty after first match
                }
                lastMatched = false;
                simpleMatchCount = 0;
            }
            else if (arrow & 2 /* Diag */) {
                if (arrow & 4 /* Left */) {
                    // left
                    _findAllMatches(patternPos, wordPos - 1, !matches.isEmpty() ? total - 1 : total, // gap penalty after first match
                    matches.slice(), lastMatched);
                }
                // diag
                total += score;
                patternPos -= 1;
                wordPos -= 1;
                matches.unshift(wordPos);
                lastMatched = true;
                // 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) {
                        // 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
        if (total > _topScore) {
            _topScore = total;
            _bucket.unshift(matches);
        }
        else {
            _bucket.push(matches);
        }
    }
    var LazyArray = (function () {
        function LazyArray() {
        }
        LazyArray.prototype.isEmpty = function () {
            return !this._data && (!this._parent || this._parent.isEmpty());
        };
        LazyArray.prototype.unshift = function (n) {
            if (!this._data) {
                this._data = [n];
            }
            else {
                this._data.unshift(n);
            }
        };
        LazyArray.prototype.slice = function () {
            var ret = new LazyArray();
            ret._parent = this;
            ret._parentLen = this._data ? this._data.length : 0;
            return ret;
        };
        LazyArray.prototype.toArray = function () {
            if (!this._data) {
                return this._parent.toArray();
            }
            var bucket = [];
            var element = this;
            while (element) {
                if (element._parent && element._parent._data) {
                    bucket.push(element._parent._data.slice(element._parent._data.length - element._parentLen));
                }
                element = element._parent;
            }
            return Array.prototype.concat.apply(this._data, bucket);
        };
        return LazyArray;
    }());
    function nextTypoPermutation(pattern, patternPos) {
        if (patternPos + 1 >= pattern.length) {
            return undefined;
        }
        return pattern.slice(0, patternPos)
            + pattern[patternPos + 1]
            + pattern[patternPos]
            + pattern.slice(patternPos + 2);
    }
    exports.nextTypoPermutation = nextTypoPermutation;
    function fuzzyScoreGraceful(pattern, word) {
        var ret = fuzzyScore(pattern, word);
        for (var patternPos = 1; patternPos < pattern.length - 1 && !ret; patternPos++) {
            var pattern2 = nextTypoPermutation(pattern, patternPos);
            ret = fuzzyScore(pattern2, word);
        }
        return ret;
    }
    exports.fuzzyScoreGraceful = fuzzyScoreGraceful;
});

define(__m[45/*vs/base/common/paths*/], __M([1/*require*/,0/*exports*/,15/*vs/base/common/platform*/,33/*vs/base/common/arrays*/,9/*vs/base/common/strings*/]), function (require, exports, platform_1, arrays_1, strings_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * The forward slash path separator.
     */
    exports.sep = '/';
    /**
     * The native path separator depending on the OS.
     */
    exports.nativeSep = platform_1.isWindows ? '\\' : '/';
    function relative(from, to) {
        // ignore trailing slashes
        var originalNormalizedFrom = strings_1.rtrim(normalize(from), exports.sep);
        var originalNormalizedTo = strings_1.rtrim(normalize(to), exports.sep);
        // we're assuming here that any non=linux OS is case insensitive
        // so we must compare each part in its lowercase form
        var normalizedFrom = platform_1.isLinux ? originalNormalizedFrom : originalNormalizedFrom.toLowerCase();
        var normalizedTo = platform_1.isLinux ? originalNormalizedTo : originalNormalizedTo.toLowerCase();
        var fromParts = normalizedFrom.split(exports.sep);
        var toParts = normalizedTo.split(exports.sep);
        var i = 0, max = Math.min(fromParts.length, toParts.length);
        for (; i < max; i++) {
            if (fromParts[i] !== toParts[i]) {
                break;
            }
        }
        var result = arrays_1.fill(fromParts.length - i, function () { return '..'; }).concat(originalNormalizedTo.split(exports.sep).slice(i));
        return result.join(exports.sep);
    }
    exports.relative = relative;
    /**
     * @returns the directory name of a path.
     */
    function dirname(path) {
        var idx = ~path.lastIndexOf('/') || ~path.lastIndexOf('\\');
        if (idx === 0) {
            return '.';
        }
        else if (~idx === 0) {
            return path[0];
        }
        else {
            var res = path.substring(0, ~idx);
            if (platform_1.isWindows && res[res.length - 1] === ':') {
                res += exports.nativeSep; // make sure drive letters end with backslash
            }
            return res;
        }
    }
    exports.dirname = dirname;
    /**
     * @returns the base name of a path.
     */
    function basename(path) {
        var idx = ~path.lastIndexOf('/') || ~path.lastIndexOf('\\');
        if (idx === 0) {
            return path;
        }
        else if (~idx === path.length - 1) {
            return basename(path.substring(0, path.length - 1));
        }
        else {
            return path.substr(~idx + 1);
        }
    }
    exports.basename = basename;
    /**
     * @returns {{.far}} from boo.far or the empty string.
     */
    function extname(path) {
        path = basename(path);
        var idx = ~path.lastIndexOf('.');
        return idx ? path.substring(~idx) : '';
    }
    exports.extname = extname;
    var _posixBadPath = /(\/\.\.?\/)|(\/\.\.?)$|^(\.\.?\/)|(\/\/+)|(\\)/;
    var _winBadPath = /(\\\.\.?\\)|(\\\.\.?)$|^(\.\.?\\)|(\\\\+)|(\/)/;
    function _isNormal(path, win) {
        return win
            ? !_winBadPath.test(path)
            : !_posixBadPath.test(path);
    }
    function normalize(path, toOSPath) {
        if (path === null || path === void 0) {
            return path;
        }
        var len = path.length;
        if (len === 0) {
            return '.';
        }
        var wantsBackslash = platform_1.isWindows && toOSPath;
        if (_isNormal(path, wantsBackslash)) {
            return path;
        }
        var sep = wantsBackslash ? '\\' : '/';
        var root = getRoot(path, sep);
        // skip the root-portion of the path
        var start = root.length;
        var skip = false;
        var res = '';
        for (var end = root.length; end <= len; end++) {
            // either at the end or at a path-separator character
            if (end === len || path.charCodeAt(end) === 47 /* Slash */ || path.charCodeAt(end) === 92 /* Backslash */) {
                if (streql(path, start, end, '..')) {
                    // skip current and remove parent (if there is already something)
                    var prev_start = res.lastIndexOf(sep);
                    var prev_part = res.slice(prev_start + 1);
                    if ((root || prev_part.length > 0) && prev_part !== '..') {
                        res = prev_start === -1 ? '' : res.slice(0, prev_start);
                        skip = true;
                    }
                }
                else if (streql(path, start, end, '.') && (root || res || end < len - 1)) {
                    // skip current (if there is already something or if there is more to come)
                    skip = true;
                }
                if (!skip) {
                    var part = path.slice(start, end);
                    if (res !== '' && res[res.length - 1] !== sep) {
                        res += sep;
                    }
                    res += part;
                }
                start = end + 1;
                skip = false;
            }
        }
        return root + res;
    }
    exports.normalize = normalize;
    function streql(value, start, end, other) {
        return start + other.length === end && value.indexOf(other, start) === start;
    }
    /**
     * Computes the _root_ this path, like `getRoot('c:\files') === c:\`,
     * `getRoot('files:///files/path') === files:///`,
     * or `getRoot('\\server\shares\path') === \\server\shares\`
     */
    function getRoot(path, sep) {
        if (sep === void 0) { sep = '/'; }
        if (!path) {
            return '';
        }
        var len = path.length;
        var code = path.charCodeAt(0);
        if (code === 47 /* Slash */ || code === 92 /* Backslash */) {
            code = path.charCodeAt(1);
            if (code === 47 /* Slash */ || code === 92 /* Backslash */) {
                // UNC candidate \\localhost\shares\ddd
                //               ^^^^^^^^^^^^^^^^^^^
                code = path.charCodeAt(2);
                if (code !== 47 /* Slash */ && code !== 92 /* Backslash */) {
                    var pos_1 = 3;
                    var start = pos_1;
                    for (; pos_1 < len; pos_1++) {
                        code = path.charCodeAt(pos_1);
                        if (code === 47 /* Slash */ || code === 92 /* Backslash */) {
                            break;
                        }
                    }
                    code = path.charCodeAt(pos_1 + 1);
                    if (start !== pos_1 && code !== 47 /* Slash */ && code !== 92 /* Backslash */) {
                        pos_1 += 1;
                        for (; pos_1 < len; pos_1++) {
                            code = path.charCodeAt(pos_1);
                            if (code === 47 /* Slash */ || code === 92 /* Backslash */) {
                                return path.slice(0, pos_1 + 1) // consume this separator
                                    .replace(/[\\/]/g, sep);
                            }
                        }
                    }
                }
            }
            // /user/far
            // ^
            return sep;
        }
        else if ((code >= 65 /* A */ && code <= 90 /* Z */) || (code >= 97 /* a */ && code <= 122 /* z */)) {
            // check for windows drive letter c:\ or c:
            if (path.charCodeAt(1) === 58 /* Colon */) {
                code = path.charCodeAt(2);
                if (code === 47 /* Slash */ || code === 92 /* Backslash */) {
                    // C:\fff
                    // ^^^
                    return path.slice(0, 2) + sep;
                }
                else {
                    // C:
                    // ^^
                    return path.slice(0, 2);
                }
            }
        }
        // check for URI
        // scheme://authority/path
        // ^^^^^^^^^^^^^^^^^^^
        var pos = path.indexOf('://');
        if (pos !== -1) {
            pos += 3; // 3 -> "://".length
            for (; pos < len; pos++) {
                code = path.charCodeAt(pos);
                if (code === 47 /* Slash */ || code === 92 /* Backslash */) {
                    return path.slice(0, pos + 1); // consume this separator
                }
            }
        }
        return '';
    }
    exports.getRoot = getRoot;
    exports.join = function () {
        // Not using a function with var-args because of how TS compiles
        // them to JS - it would result in 2*n runtime cost instead
        // of 1*n, where n is parts.length.
        var value = '';
        for (var i = 0; i < arguments.length; i++) {
            var part = arguments[i];
            if (i > 0) {
                // add the separater between two parts unless
                // there already is one
                var last = value.charCodeAt(value.length - 1);
                if (last !== 47 /* Slash */ && last !== 92 /* Backslash */) {
                    var next = part.charCodeAt(0);
                    if (next !== 47 /* Slash */ && next !== 92 /* Backslash */) {
                        value += exports.sep;
                    }
                }
            }
            value += part;
        }
        return normalize(value);
    };
    /**
     * Check if the path follows this pattern: `\\hostname\sharename`.
     *
     * @see https://msdn.microsoft.com/en-us/library/gg465305.aspx
     * @return A boolean indication if the path is a UNC path, on none-windows
     * always false.
     */
    function isUNC(path) {
        if (!platform_1.isWindows) {
            // UNC is a windows concept
            return false;
        }
        if (!path || path.length < 5) {
            // at least \\a\b
            return false;
        }
        var code = path.charCodeAt(0);
        if (code !== 92 /* Backslash */) {
            return false;
        }
        code = path.charCodeAt(1);
        if (code !== 92 /* Backslash */) {
            return false;
        }
        var pos = 2;
        var start = pos;
        for (; pos < path.length; pos++) {
            code = path.charCodeAt(pos);
            if (code === 92 /* Backslash */) {
                break;
            }
        }
        if (start === pos) {
            return false;
        }
        code = path.charCodeAt(pos + 1);
        if (isNaN(code) || code === 92 /* Backslash */) {
            return false;
        }
        return true;
    }
    exports.isUNC = isUNC;
    // Reference: https://en.wikipedia.org/wiki/Filename
    var INVALID_FILE_CHARS = platform_1.isWindows ? /[\\/:\*\?"<>\|]/g : /[\\/]/g;
    var WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])$/i;
    function isValidBasename(name) {
        if (!name || name.length === 0 || /^\s+$/.test(name)) {
            return false; // require a name that is not just whitespace
        }
        INVALID_FILE_CHARS.lastIndex = 0; // the holy grail of software development
        if (INVALID_FILE_CHARS.test(name)) {
            return false; // check for certain invalid file characters
        }
        if (platform_1.isWindows && WINDOWS_FORBIDDEN_NAMES.test(name)) {
            return false; // check for certain invalid file names
        }
        if (name === '.' || name === '..') {
            return false; // check for reserved values
        }
        if (platform_1.isWindows && name[name.length - 1] === '.') {
            return false; // Windows: file cannot end with a "."
        }
        if (platform_1.isWindows && name.length !== name.trim().length) {
            return false; // Windows: file cannot end with a whitespace
        }
        return true;
    }
    exports.isValidBasename = isValidBasename;
    function isEqual(pathA, pathB, ignoreCase) {
        var identityEquals = (pathA === pathB);
        if (!ignoreCase || identityEquals) {
            return identityEquals;
        }
        if (!pathA || !pathB) {
            return false;
        }
        return strings_1.equalsIgnoreCase(pathA, pathB);
    }
    exports.isEqual = isEqual;
    function isEqualOrParent(path, candidate, ignoreCase) {
        if (path === candidate) {
            return true;
        }
        if (!path || !candidate) {
            return false;
        }
        if (candidate.length > path.length) {
            return false;
        }
        if (ignoreCase) {
            var beginsWith = strings_1.beginsWithIgnoreCase(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) === exports.nativeSep) {
                sepOffset--; // adjust the expected sep offset in case our candidate already ends in separator character
            }
            return path.charAt(sepOffset) === exports.nativeSep;
        }
        if (candidate.charAt(candidate.length - 1) !== exports.nativeSep) {
            candidate += exports.nativeSep;
        }
        return path.indexOf(candidate) === 0;
    }
    exports.isEqualOrParent = isEqualOrParent;
    /**
     * Adapted from Node's path.isAbsolute functions
     */
    function isAbsolute(path) {
        return platform_1.isWindows ?
            isAbsolute_win32(path) :
            isAbsolute_posix(path);
    }
    exports.isAbsolute = isAbsolute;
    function isAbsolute_win32(path) {
        if (!path) {
            return false;
        }
        var char0 = path.charCodeAt(0);
        if (char0 === 47 /* Slash */ || char0 === 92 /* Backslash */) {
            return true;
        }
        else if ((char0 >= 65 /* A */ && char0 <= 90 /* Z */) || (char0 >= 97 /* a */ && char0 <= 122 /* z */)) {
            if (path.length > 2 && path.charCodeAt(1) === 58 /* Colon */) {
                var char2 = path.charCodeAt(2);
                if (char2 === 47 /* Slash */ || char2 === 92 /* Backslash */) {
                    return true;
                }
            }
        }
        return false;
    }
    exports.isAbsolute_win32 = isAbsolute_win32;
    function isAbsolute_posix(path) {
        return path && path.charCodeAt(0) === 47 /* Slash */;
    }
    exports.isAbsolute_posix = isAbsolute_posix;
});

define(__m[229/*vs/base/common/comparers*/], __M([1/*require*/,0/*exports*/,423/*vs/base/common/scorer*/,9/*vs/base/common/strings*/,45/*vs/base/common/paths*/]), function (require, exports, scorer, strings, paths) {
    /*---------------------------------------------------------------------------------------------
     *  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 intlFileNameCollator;
    var intlFileNameCollatorIsNumeric;
    function setFileNameComparer(collator) {
        intlFileNameCollator = collator;
        intlFileNameCollatorIsNumeric = collator.resolvedOptions().numeric;
    }
    exports.setFileNameComparer = setFileNameComparer;
    function compareFileNames(one, other) {
        if (intlFileNameCollator) {
            var a = one || '';
            var b = other || '';
            var result = intlFileNameCollator.compare(a, b);
            // Using the numeric option in the collator will
            // make compare(`foo1`, `foo01`) === 0. We must disambiguate.
            if (intlFileNameCollatorIsNumeric && result === 0 && a !== b) {
                return a < b ? -1 : 1;
            }
            return result;
        }
        return noIntlCompareFileNames(one, other);
    }
    exports.compareFileNames = compareFileNames;
    var FileNameMatch = /^(.*?)(\.([^.]*))?$/;
    function noIntlCompareFileNames(one, other) {
        var oneMatch = FileNameMatch.exec(one.toLowerCase());
        var otherMatch = FileNameMatch.exec(other.toLowerCase());
        var oneName = oneMatch[1] || '';
        var oneExtension = oneMatch[3] || '';
        var otherName = otherMatch[1] || '';
        var otherExtension = otherMatch[3] || '';
        if (oneName !== otherName) {
            return oneName < otherName ? -1 : 1;
        }
        if (oneExtension === otherExtension) {
            return 0;
        }
        return oneExtension < otherExtension ? -1 : 1;
    }
    exports.noIntlCompareFileNames = noIntlCompareFileNames;
    function compareFileExtensions(one, other) {
        if (intlFileNameCollator) {
            var oneMatch = one ? FileNameMatch.exec(one) : [];
            var otherMatch = other ? FileNameMatch.exec(other) : [];
            var oneName = oneMatch[1] || '';
            var oneExtension = oneMatch[3] || '';
            var otherName = otherMatch[1] || '';
            var otherExtension = otherMatch[3] || '';
            var result = intlFileNameCollator.compare(oneExtension, otherExtension);
            if (result === 0) {
                // Using the numeric option in the collator will
                // make compare(`foo1`, `foo01`) === 0. We must disambiguate.
                if (intlFileNameCollatorIsNumeric && oneExtension !== otherExtension) {
                    return oneExtension < otherExtension ? -1 : 1;
                }
                // Extensions are equal, compare filenames
                result = intlFileNameCollator.compare(oneName, otherName);
                if (intlFileNameCollatorIsNumeric && result === 0 && oneName !== otherName) {
                    return oneName < otherName ? -1 : 1;
                }
            }
            return result;
        }
        return noIntlCompareFileExtensions(one, other);
    }
    exports.compareFileExtensions = compareFileExtensions;
    function noIntlCompareFileExtensions(one, other) {
        var oneMatch = one ? FileNameMatch.exec(one.toLowerCase()) : [];
        var otherMatch = other ? FileNameMatch.exec(other.toLowerCase()) : [];
        var oneName = oneMatch[1] || '';
        var oneExtension = oneMatch[3] || '';
        var otherName = otherMatch[1] || '';
        var otherExtension = otherMatch[3] || '';
        if (oneExtension !== otherExtension) {
            return oneExtension < otherExtension ? -1 : 1;
        }
        if (oneName === otherName) {
            return 0;
        }
        return oneName < otherName ? -1 : 1;
    }
    function comparePaths(one, other) {
        var oneParts = one.split(paths.nativeSep);
        var otherParts = other.split(paths.nativeSep);
        var lastOne = oneParts.length - 1;
        var lastOther = otherParts.length - 1;
        var endOne, endOther, onePart, otherPart;
        for (var i = 0;; i++) {
            endOne = lastOne === i;
            endOther = lastOther === i;
            if (endOne && endOther) {
                return compareFileNames(oneParts[i], otherParts[i]);
            }
            else if (endOne) {
                return -1;
            }
            else if (endOther) {
                return 1;
            }
            else if ((onePart = oneParts[i].toLowerCase()) !== (otherPart = otherParts[i].toLowerCase())) {
                return onePart < otherPart ? -1 : 1;
            }
        }
    }
    exports.comparePaths = comparePaths;
    function compareAnything(one, other, lookFor) {
        var elementAName = one.toLowerCase();
        var elementBName = other.toLowerCase();
        // Sort prefix matches over non prefix matches
        var prefixCompare = compareByPrefix(one, other, lookFor);
        if (prefixCompare) {
            return prefixCompare;
        }
        // Sort suffix matches over non suffix matches
        var elementASuffixMatch = strings.endsWith(elementAName, lookFor);
        var elementBSuffixMatch = strings.endsWith(elementBName, lookFor);
        if (elementASuffixMatch !== elementBSuffixMatch) {
            return elementASuffixMatch ? -1 : 1;
        }
        // Understand file names
        var r = compareFileNames(elementAName, elementBName);
        if (r !== 0) {
            return r;
        }
        // Compare by name
        return elementAName.localeCompare(elementBName);
    }
    exports.compareAnything = compareAnything;
    function compareByPrefix(one, other, lookFor) {
        var elementAName = one.toLowerCase();
        var elementBName = other.toLowerCase();
        // Sort prefix matches over non prefix matches
        var elementAPrefixMatch = strings.startsWith(elementAName, lookFor);
        var elementBPrefixMatch = strings.startsWith(elementBName, lookFor);
        if (elementAPrefixMatch !== elementBPrefixMatch) {
            return elementAPrefixMatch ? -1 : 1;
        }
        else if (elementAPrefixMatch && elementBPrefixMatch) {
            if (elementAName.length < elementBName.length) {
                return -1;
            }
            if (elementAName.length > elementBName.length) {
                return 1;
            }
        }
        return 0;
    }
    exports.compareByPrefix = compareByPrefix;
    function compareByScore(elementA, elementB, accessor, lookFor, lookForNormalizedLower, scorerCache) {
        var labelA = accessor.getLabel(elementA);
        var labelB = accessor.getLabel(elementB);
        // treat prefix matches highest in any case
        var prefixCompare = compareByPrefix(labelA, labelB, lookFor);
        if (prefixCompare) {
            return prefixCompare;
        }
        // Give higher importance to label score
        var labelAScore = scorer.score(labelA, lookFor, scorerCache);
        var labelBScore = scorer.score(labelB, lookFor, scorerCache);
        if (labelAScore !== labelBScore) {
            return labelAScore > labelBScore ? -1 : 1;
        }
        // Score on full resource path comes next (if available)
        var resourcePathA = accessor.getResourcePath(elementA);
        var resourcePathB = accessor.getResourcePath(elementB);
        if (resourcePathA && resourcePathB) {
            var resourceAScore = scorer.score(resourcePathA, lookFor, scorerCache);
            var resourceBScore = scorer.score(resourcePathB, lookFor, scorerCache);
            if (resourceAScore !== resourceBScore) {
                return resourceAScore > resourceBScore ? -1 : 1;
            }
        }
        // At this place, the scores are identical so we check for string lengths and favor shorter ones
        if (labelA.length !== labelB.length) {
            return labelA.length < labelB.length ? -1 : 1;
        }
        if (resourcePathA && resourcePathB && resourcePathA.length !== resourcePathB.length) {
            return resourcePathA.length < resourcePathB.length ? -1 : 1;
        }
        // Finally compare by label or resource path
        if (labelA === labelB && resourcePathA && resourcePathB) {
            return compareAnything(resourcePathA, resourcePathB, lookForNormalizedLower);
        }
        return compareAnything(labelA, labelB, lookForNormalizedLower);
    }
    exports.compareByScore = compareByScore;
});

define(__m[174/*vs/base/common/labels*/], __M([1/*require*/,0/*exports*/,24/*vs/base/common/uri*/,15/*vs/base/common/platform*/,45/*vs/base/common/paths*/,9/*vs/base/common/strings*/]), function (require, exports, uri_1, platform, paths_1, strings_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function getPathLabel(resource, rootProvider, userHomeProvider) {
        if (!resource) {
            return null;
        }
        if (typeof resource === 'string') {
            resource = uri_1.default.file(resource);
        }
        // return early if we can resolve a relative path label from the root
        var baseResource = rootProvider ? rootProvider.getRoot(resource) : null;
        if (baseResource) {
            var hasMultipleRoots = rootProvider.getWorkspace().roots.length > 1;
            var pathLabel = void 0;
            if (paths_1.isEqual(baseResource.fsPath, resource.fsPath, !platform.isLinux /* ignorecase */)) {
                pathLabel = ''; // no label if pathes are identical
            }
            else {
                pathLabel = paths_1.normalize(strings_1.ltrim(resource.fsPath.substr(baseResource.fsPath.length), paths_1.nativeSep), true);
            }
            if (hasMultipleRoots) {
                var rootName = paths_1.basename(baseResource.fsPath);
                pathLabel = pathLabel ? paths_1.join(rootName, pathLabel) : rootName; // always show root basename if there are multiple
            }
            return pathLabel;
        }
        // convert c:\something => C:\something
        if (platform.isWindows && resource.fsPath && resource.fsPath[1] === ':') {
            return paths_1.normalize(resource.fsPath.charAt(0).toUpperCase() + resource.fsPath.slice(1), true);
        }
        // normalize and tildify (macOS, Linux only)
        var res = paths_1.normalize(resource.fsPath, true);
        if (!platform.isWindows && userHomeProvider) {
            res = tildify(res, userHomeProvider.userHome);
        }
        return res;
    }
    exports.getPathLabel = getPathLabel;
    function tildify(path, userHome) {
        if (path && (platform.isMacintosh || platform.isLinux) && paths_1.isEqualOrParent(path, userHome, !platform.isLinux /* ignorecase */)) {
            path = "~" + path.substr(userHome.length);
        }
        return path;
    }
    exports.tildify = tildify;
    /**
     * Shortens the paths but keeps them easy to distinguish.
     * Replaces not important parts with ellipsis.
     * Every shorten path matches only one original path and vice versa.
     *
     * Algorithm for shortening paths is as follows:
     * 1. For every path in list, find unique substring of that path.
     * 2. Unique substring along with ellipsis is shortened path of that path.
     * 3. To find unique substring of path, consider every segment of length from 1 to path.length of path from end of string
     *    and if present segment is not substring to any other paths then present segment is unique path,
     *    else check if it is not present as suffix of any other path and present segment is suffix of path itself,
     *    if it is true take present segment as unique path.
     * 4. Apply ellipsis to unique segment according to whether segment is present at start/in-between/end of path.
     *
     * Example 1
     * 1. consider 2 paths i.e. ['a\\b\\c\\d', 'a\\f\\b\\c\\d']
     * 2. find unique path of first path,
     * 	a. 'd' is present in path2 and is suffix of path2, hence not unique of present path.
     * 	b. 'c' is present in path2 and 'c' is not suffix of present path, similarly for 'b' and 'a' also.
     * 	c. 'd\\c' is suffix of path2.
     *  d. 'b\\c' is not suffix of present path.
     *  e. 'a\\b' is not present in path2, hence unique path is 'a\\b...'.
     * 3. for path2, 'f' is not present in path1 hence unique is '...\\f\\...'.
     *
     * Example 2
     * 1. consider 2 paths i.e. ['a\\b', 'a\\b\\c'].
     * 	a. Even if 'b' is present in path2, as 'b' is suffix of path1 and is not suffix of path2, unique path will be '...\\b'.
     * 2. for path2, 'c' is not present in path1 hence unique path is '..\\c'.
     */
    var ellipsis = '\u2026';
    var unc = '\\\\';
    function shorten(paths) {
        var shortenedPaths = new Array(paths.length);
        // for every path
        var match = false;
        for (var pathIndex = 0; pathIndex < paths.length; pathIndex++) {
            var path = paths[pathIndex];
            if (path === '') {
                shortenedPaths[pathIndex] = "." + paths_1.nativeSep;
                continue;
            }
            if (!path) {
                shortenedPaths[pathIndex] = path;
                continue;
            }
            match = true;
            // trim for now and concatenate unc path (e.g. \\network) or root path (/etc) later
            var prefix = '';
            if (path.indexOf(unc) === 0) {
                prefix = path.substr(0, path.indexOf(unc) + unc.length);
                path = path.substr(path.indexOf(unc) + unc.length);
            }
            else if (path.indexOf(paths_1.nativeSep) === 0) {
                prefix = path.substr(0, path.indexOf(paths_1.nativeSep) + paths_1.nativeSep.length);
                path = path.substr(path.indexOf(paths_1.nativeSep) + paths_1.nativeSep.length);
            }
            // pick the first shortest subpath found
            var segments = path.split(paths_1.nativeSep);
            for (var subpathLength = 1; match && subpathLength <= segments.length; subpathLength++) {
                for (var start = segments.length - subpathLength; match && start >= 0; start--) {
                    match = false;
                    var subpath = segments.slice(start, start + subpathLength).join(paths_1.nativeSep);
                    // that is unique to any other path
                    for (var otherPathIndex = 0; !match && otherPathIndex < paths.length; otherPathIndex++) {
                        // suffix subpath treated specially as we consider no match 'x' and 'x/...'
                        if (otherPathIndex !== pathIndex && paths[otherPathIndex] && paths[otherPathIndex].indexOf(subpath) > -1) {
                            var isSubpathEnding = (start + subpathLength === segments.length);
                            // Adding separator as prefix for subpath, such that 'endsWith(src, trgt)' considers subpath as directory name instead of plain string.
                            // prefix is not added when either subpath is root directory or path[otherPathIndex] does not have multiple directories.
                            var subpathWithSep = (start > 0 && paths[otherPathIndex].indexOf(paths_1.nativeSep) > -1) ? paths_1.nativeSep + subpath : subpath;
                            var isOtherPathEnding = strings_1.endsWith(paths[otherPathIndex], subpathWithSep);
                            match = !isSubpathEnding || isOtherPathEnding;
                        }
                    }
                    // found unique subpath
                    if (!match) {
                        var result = '';
                        // preserve disk drive or root prefix
                        if (strings_1.endsWith(segments[0], ':') || prefix !== '') {
                            if (start === 1) {
                                // extend subpath to include disk drive prefix
                                start = 0;
                                subpathLength++;
                                subpath = segments[0] + paths_1.nativeSep + subpath;
                            }
                            if (start > 0) {
                                result = segments[0] + paths_1.nativeSep;
                            }
                            result = prefix + result;
                        }
                        // add ellipsis at the beginning if neeeded
                        if (start > 0) {
                            result = result + ellipsis + paths_1.nativeSep;
                        }
                        result = result + subpath;
                        // add ellipsis at the end if needed
                        if (start + subpathLength < segments.length) {
                            result = result + paths_1.nativeSep + ellipsis;
                        }
                        shortenedPaths[pathIndex] = result;
                    }
                }
            }
            if (match) {
                shortenedPaths[pathIndex] = path; // use full path if no unique subpaths found
            }
        }
        return shortenedPaths;
    }
    exports.shorten = shorten;
    var Type;
    (function (Type) {
        Type[Type["TEXT"] = 0] = "TEXT";
        Type[Type["VARIABLE"] = 1] = "VARIABLE";
        Type[Type["SEPARATOR"] = 2] = "SEPARATOR";
    })(Type || (Type = {}));
    /**
     * Helper to insert values for specific template variables into the string. E.g. "this $(is) a $(template)" can be
     * passed to this function together with an object that maps "is" and "template" to strings to have them replaced.
     * @param value string to which templating is applied
     * @param values the values of the templates to use
     */
    function template(template, values) {
        if (values === void 0) { values = Object.create(null); }
        var segments = [];
        var inVariable = false;
        var char;
        var curVal = '';
        for (var i = 0; i < template.length; i++) {
            char = template[i];
            // Beginning of variable
            if (char === '$' || (inVariable && char === '{')) {
                if (curVal) {
                    segments.push({ value: curVal, type: Type.TEXT });
                }
                curVal = '';
                inVariable = true;
            }
            else if (char === '}' && inVariable) {
                var resolved = values[curVal];
                // Variable
                if (typeof resolved === 'string') {
                    if (resolved.length) {
                        segments.push({ value: resolved, type: Type.VARIABLE });
                    }
                }
                else if (resolved) {
                    var prevSegment = segments[segments.length - 1];
                    if (!prevSegment || prevSegment.type !== Type.SEPARATOR) {
                        segments.push({ value: resolved.label, type: Type.SEPARATOR }); // prevent duplicate separators
                    }
                }
                curVal = '';
                inVariable = false;
            }
            else {
                curVal += char;
            }
        }
        // Tail
        if (curVal && !inVariable) {
            segments.push({ value: curVal, type: Type.TEXT });
        }
        return segments.filter(function (segment, index) {
            // Only keep separator if we have values to the left and right
            if (segment.type === Type.SEPARATOR) {
                var left = segments[index - 1];
                var right = segments[index + 1];
                return [left, right].every(function (segment) { return segment && segment.type === Type.VARIABLE && segment.value.length > 0; });
            }
            // accept any TEXT and VARIABLE
            return true;
        }).map(function (segment) { return segment.value; }).join('');
    }
    exports.template = template;
    function mnemonicButtonLabel(label) {
        if (!platform.isWindows) {
            return label.replace(/\(&&\w\)|&&/g, ''); // no mnemonic support on mac/linux
        }
        return label.replace(/&&/g, '&');
    }
    exports.mnemonicButtonLabel = mnemonicButtonLabel;
});

/**
 * Extracted from https://github.com/winjs/winjs
 * Version: 4.4.0(ec3258a9f3a36805a187848984e3bb938044178d)
 * Copyright (c) Microsoft Corporation.
 * All Rights Reserved.
 * Licensed under the MIT License.
 */
(function() {

var _modules = {};
_modules["WinJS/Core/_WinJS"] = {};

var _winjs = function(moduleId, deps, factory) {
    var exports = {};
    var exportsPassedIn = false;

    var depsValues = deps.map(function(dep) {
        if (dep === 'exports') {
            exportsPassedIn = true;
            return exports;
        }
        return _modules[dep];
    });

    var result = factory.apply({}, depsValues);

    _modules[moduleId] = exportsPassedIn ? exports : result;
};


_winjs("WinJS/Core/_Global", [], function () {
    "use strict";

    // Appease jshint
    /* global window, self, global */

    var globalObject =
        typeof window !== 'undefined' ? window :
        typeof self !== 'undefined' ? self :
        typeof global !== 'undefined' ? global :
        {};
    return globalObject;
});

_winjs("WinJS/Core/_BaseCoreUtils", ["WinJS/Core/_Global"], function baseCoreUtilsInit(_Global) {
    "use strict";

    var hasWinRT = !!_Global.Windows;

    function markSupportedForProcessing(func) {
        /// <signature helpKeyword="WinJS.Utilities.markSupportedForProcessing">
        /// <summary locid="WinJS.Utilities.markSupportedForProcessing">
        /// Marks a function as being compatible with declarative processing, such as WinJS.UI.processAll
        /// or WinJS.Binding.processAll.
        /// </summary>
        /// <param name="func" type="Function" locid="WinJS.Utilities.markSupportedForProcessing_p:func">
        /// The function to be marked as compatible with declarative processing.
        /// </param>
        /// <returns type="Function" locid="WinJS.Utilities.markSupportedForProcessing_returnValue">
        /// The input function.
        /// </returns>
        /// </signature>
        func.supportedForProcessing = true;
        return func;
    }

    return {
        hasWinRT: hasWinRT,
        markSupportedForProcessing: markSupportedForProcessing,
        _setImmediate: _Global.setImmediate ? _Global.setImmediate.bind(_Global) : function (handler) {
            _Global.setTimeout(handler, 0);
        }
    };
});
_winjs("WinJS/Core/_WriteProfilerMark", ["WinJS/Core/_Global"], function profilerInit(_Global) {
    "use strict";

    return _Global.msWriteProfilerMark || function () { };
});
_winjs("WinJS/Core/_Base", ["WinJS/Core/_WinJS","WinJS/Core/_Global","WinJS/Core/_BaseCoreUtils","WinJS/Core/_WriteProfilerMark"], function baseInit(_WinJS, _Global, _BaseCoreUtils, _WriteProfilerMark) {
    "use strict";

    function initializeProperties(target, members, prefix) {
        var keys = Object.keys(members);
        var isArray = Array.isArray(target);
        var properties;
        var i, len;
        for (i = 0, len = keys.length; i < len; i++) {
            var key = keys[i];
            var enumerable = key.charCodeAt(0) !== /*_*/95;
            var member = members[key];
            if (member && typeof member === 'object') {
                if (member.value !== undefined || typeof member.get === 'function' || typeof member.set === 'function') {
                    if (member.enumerable === undefined) {
                        member.enumerable = enumerable;
                    }
                    if (prefix && member.setName && typeof member.setName === 'function') {
                        member.setName(prefix + "." + key);
                    }
                    properties = properties || {};
                    properties[key] = member;
                    continue;
                }
            }
            if (!enumerable) {
                properties = properties || {};
                properties[key] = { value: member, enumerable: enumerable, configurable: true, writable: true };
                continue;
            }
            if (isArray) {
                target.forEach(function (target) {
                    target[key] = member;
                });
            } else {
                target[key] = member;
            }
        }
        if (properties) {
            if (isArray) {
                target.forEach(function (target) {
                    Object.defineProperties(target, properties);
                });
            } else {
                Object.defineProperties(target, properties);
            }
        }
    }

    (function () {

        var _rootNamespace = _WinJS;
        if (!_rootNamespace.Namespace) {
            _rootNamespace.Namespace = Object.create(Object.prototype);
        }

        function createNamespace(parentNamespace, name) {
            var currentNamespace = parentNamespace || {};
            if (name) {
                var namespaceFragments = name.split(".");
                if (currentNamespace === _Global && namespaceFragments[0] === "WinJS") {
                    currentNamespace = _WinJS;
                    namespaceFragments.splice(0, 1);
                }
                for (var i = 0, len = namespaceFragments.length; i < len; i++) {
                    var namespaceName = namespaceFragments[i];
                    if (!currentNamespace[namespaceName]) {
                        Object.defineProperty(currentNamespace, namespaceName,
                            { value: {}, writable: false, enumerable: true, configurable: true }
                        );
                    }
                    currentNamespace = currentNamespace[namespaceName];
                }
            }
            return currentNamespace;
        }

        function defineWithParent(parentNamespace, name, members) {
            /// <signature helpKeyword="WinJS.Namespace.defineWithParent">
            /// <summary locid="WinJS.Namespace.defineWithParent">
            /// Defines a new namespace with the specified name under the specified parent namespace.
            /// </summary>
            /// <param name="parentNamespace" type="Object" locid="WinJS.Namespace.defineWithParent_p:parentNamespace">
            /// The parent namespace.
            /// </param>
            /// <param name="name" type="String" locid="WinJS.Namespace.defineWithParent_p:name">
            /// The name of the new namespace.
            /// </param>
            /// <param name="members" type="Object" locid="WinJS.Namespace.defineWithParent_p:members">
            /// The members of the new namespace.
            /// </param>
            /// <returns type="Object" locid="WinJS.Namespace.defineWithParent_returnValue">
            /// The newly-defined namespace.
            /// </returns>
            /// </signature>
            var currentNamespace = createNamespace(parentNamespace, name);

            if (members) {
                initializeProperties(currentNamespace, members, name || "<ANONYMOUS>");
            }

            return currentNamespace;
        }

        function define(name, members) {
            /// <signature helpKeyword="WinJS.Namespace.define">
            /// <summary locid="WinJS.Namespace.define">
            /// Defines a new namespace with the specified name.
            /// </summary>
            /// <param name="name" type="String" locid="WinJS.Namespace.define_p:name">
            /// The name of the namespace. This could be a dot-separated name for nested namespaces.
            /// </param>
            /// <param name="members" type="Object" locid="WinJS.Namespace.define_p:members">
            /// The members of the new namespace.
            /// </param>
            /// <returns type="Object" locid="WinJS.Namespace.define_returnValue">
            /// The newly-defined namespace.
            /// </returns>
            /// </signature>
            return defineWithParent(_Global, name, members);
        }

        var LazyStates = {
            uninitialized: 1,
            working: 2,
            initialized: 3,
        };

        function lazy(f) {
            var name;
            var state = LazyStates.uninitialized;
            var result;
            return {
                setName: function (value) {
                    name = value;
                },
                get: function () {
                    switch (state) {
                        case LazyStates.initialized:
                            return result;

                        case LazyStates.uninitialized:
                            state = LazyStates.working;
                            try {
                                _WriteProfilerMark("WinJS.Namespace._lazy:" + name + ",StartTM");
                                result = f();
                            } finally {
                                _WriteProfilerMark("WinJS.Namespace._lazy:" + name + ",StopTM");
                                state = LazyStates.uninitialized;
                            }
                            f = null;
                            state = LazyStates.initialized;
                            return result;

                        case LazyStates.working:
                            throw "Illegal: reentrancy on initialization";

                        default:
                            throw "Illegal";
                    }
                },
                set: function (value) {
                    switch (state) {
                        case LazyStates.working:
                            throw "Illegal: reentrancy on initialization";

                        default:
                            state = LazyStates.initialized;
                            result = value;
                            break;
                    }
                },
                enumerable: true,
                configurable: true,
            };
        }

        // helper for defining AMD module members
        function moduleDefine(exports, name, members) {
            var target = [exports];
            var publicNS = null;
            if (name) {
                publicNS = createNamespace(_Global, name);
                target.push(publicNS);
            }
            initializeProperties(target, members, name || "<ANONYMOUS>");
            return publicNS;
        }

        // Establish members of the "WinJS.Namespace" namespace
        Object.defineProperties(_rootNamespace.Namespace, {

            defineWithParent: { value: defineWithParent, writable: true, enumerable: true, configurable: true },

            define: { value: define, writable: true, enumerable: true, configurable: true },

            _lazy: { value: lazy, writable: true, enumerable: true, configurable: true },

            _moduleDefine: { value: moduleDefine, writable: true, enumerable: true, configurable: true }

        });

    })();

    (function () {

        function define(constructor, instanceMembers, staticMembers) {
            /// <signature helpKeyword="WinJS.Class.define">
            /// <summary locid="WinJS.Class.define">
            /// Defines a class using the given constructor and the specified instance members.
            /// </summary>
            /// <param name="constructor" type="Function" locid="WinJS.Class.define_p:constructor">
            /// A constructor function that is used to instantiate this class.
            /// </param>
            /// <param name="instanceMembers" type="Object" locid="WinJS.Class.define_p:instanceMembers">
            /// The set of instance fields, properties, and methods made available on the class.
            /// </param>
            /// <param name="staticMembers" type="Object" locid="WinJS.Class.define_p:staticMembers">
            /// The set of static fields, properties, and methods made available on the class.
            /// </param>
            /// <returns type="Function" locid="WinJS.Class.define_returnValue">
            /// The newly-defined class.
            /// </returns>
            /// </signature>
            constructor = constructor || function () { };
            _BaseCoreUtils.markSupportedForProcessing(constructor);
            if (instanceMembers) {
                initializeProperties(constructor.prototype, instanceMembers);
            }
            if (staticMembers) {
                initializeProperties(constructor, staticMembers);
            }
            return constructor;
        }

        function derive(baseClass, constructor, instanceMembers, staticMembers) {
            /// <signature helpKeyword="WinJS.Class.derive">
            /// <summary locid="WinJS.Class.derive">
            /// Creates a sub-class based on the supplied baseClass parameter, using prototypal inheritance.
            /// </summary>
            /// <param name="baseClass" type="Function" locid="WinJS.Class.derive_p:baseClass">
            /// The class to inherit from.
            /// </param>
            /// <param name="constructor" type="Function" locid="WinJS.Class.derive_p:constructor">
            /// A constructor function that is used to instantiate this class.
            /// </param>
            /// <param name="instanceMembers" type="Object" locid="WinJS.Class.derive_p:instanceMembers">
            /// The set of instance fields, properties, and methods to be made available on the class.
            /// </param>
            /// <param name="staticMembers" type="Object" locid="WinJS.Class.derive_p:staticMembers">
            /// The set of static fields, properties, and methods to be made available on the class.
            /// </param>
            /// <returns type="Function" locid="WinJS.Class.derive_returnValue">
            /// The newly-defined class.
            /// </returns>
            /// </signature>
            if (baseClass) {
                constructor = constructor || function () { };
                var basePrototype = baseClass.prototype;
                constructor.prototype = Object.create(basePrototype);
                _BaseCoreUtils.markSupportedForProcessing(constructor);
                Object.defineProperty(constructor.prototype, "constructor", { value: constructor, writable: true, configurable: true, enumerable: true });
                if (instanceMembers) {
                    initializeProperties(constructor.prototype, instanceMembers);
                }
                if (staticMembers) {
                    initializeProperties(constructor, staticMembers);
                }
                return constructor;
            } else {
                return define(constructor, instanceMembers, staticMembers);
            }
        }

        function mix(constructor) {
            /// <signature helpKeyword="WinJS.Class.mix">
            /// <summary locid="WinJS.Class.mix">
            /// Defines a class using the given constructor and the union of the set of instance members
            /// specified by all the mixin objects. The mixin parameter list is of variable length.
            /// </summary>
            /// <param name="constructor" locid="WinJS.Class.mix_p:constructor">
            /// A constructor function that is used to instantiate this class.
            /// </param>
            /// <returns type="Function" locid="WinJS.Class.mix_returnValue">
            /// The newly-defined class.
            /// </returns>
            /// </signature>
            constructor = constructor || function () { };
            var i, len;
            for (i = 1, len = arguments.length; i < len; i++) {
                initializeProperties(constructor.prototype, arguments[i]);
            }
            return constructor;
        }

        // Establish members of "WinJS.Class" namespace
        _WinJS.Namespace.define("WinJS.Class", {
            define: define,
            derive: derive,
            mix: mix
        });

    })();

    return {
        Namespace: _WinJS.Namespace,
        Class: _WinJS.Class
    };

});
_winjs("WinJS/Core/_ErrorFromName", ["WinJS/Core/_Base"], function errorsInit(_Base) {
    "use strict";

    var ErrorFromName = _Base.Class.derive(Error, function (name, message) {
        /// <signature helpKeyword="WinJS.ErrorFromName">
        /// <summary locid="WinJS.ErrorFromName">
        /// Creates an Error object with the specified name and message properties.
        /// </summary>
        /// <param name="name" type="String" locid="WinJS.ErrorFromName_p:name">The name of this error. The name is meant to be consumed programmatically and should not be localized.</param>
        /// <param name="message" type="String" optional="true" locid="WinJS.ErrorFromName_p:message">The message for this error. The message is meant to be consumed by humans and should be localized.</param>
        /// <returns type="Error" locid="WinJS.ErrorFromName_returnValue">Error instance with .name and .message properties populated</returns>
        /// </signature>
        this.name = name;
        this.message = message || name;
    }, {
        /* empty */
    }, {
        supportedForProcessing: false,
    });

    _Base.Namespace.define("WinJS", {
        // ErrorFromName establishes a simple pattern for returning error codes.
        //
        ErrorFromName: ErrorFromName
    });

    return ErrorFromName;

});


_winjs("WinJS/Core/_Events", ["exports","WinJS/Core/_Base"], function eventsInit(exports, _Base) {
    "use strict";


    function createEventProperty(name) {
        var eventPropStateName = "_on" + name + "state";

        return {
            get: function () {
                var state = this[eventPropStateName];
                return state && state.userHandler;
            },
            set: function (handler) {
                var state = this[eventPropStateName];
                if (handler) {
                    if (!state) {
                        state = { wrapper: function (evt) { return state.userHandler(evt); }, userHandler: handler };
                        Object.defineProperty(this, eventPropStateName, { value: state, enumerable: false, writable:true, configurable: true });
                        this.addEventListener(name, state.wrapper, false);
                    }
                    state.userHandler = handler;
                } else if (state) {
                    this.removeEventListener(name, state.wrapper, false);
                    this[eventPropStateName] = null;
                }
            },
            enumerable: true
        };
    }

    function createEventProperties() {
        /// <signature helpKeyword="WinJS.Utilities.createEventProperties">
        /// <summary locid="WinJS.Utilities.createEventProperties">
        /// Creates an object that has one property for each name passed to the function.
        /// </summary>
        /// <param name="events" locid="WinJS.Utilities.createEventProperties_p:events">
        /// A variable list of property names.
        /// </param>
        /// <returns type="Object" locid="WinJS.Utilities.createEventProperties_returnValue">
        /// The object with the specified properties. The names of the properties are prefixed with 'on'.
        /// </returns>
        /// </signature>
        var props = {};
        for (var i = 0, len = arguments.length; i < len; i++) {
            var name = arguments[i];
            props["on" + name] = createEventProperty(name);
        }
        return props;
    }

    var EventMixinEvent = _Base.Class.define(
        function EventMixinEvent_ctor(type, detail, target) {
            this.detail = detail;
            this.target = target;
            this.timeStamp = Date.now();
            this.type = type;
        },
        {
            bubbles: { value: false, writable: false },
            cancelable: { value: false, writable: false },
            currentTarget: {
                get: function () { return this.target; }
            },
            defaultPrevented: {
                get: function () { return this._preventDefaultCalled; }
            },
            trusted: { value: false, writable: false },
            eventPhase: { value: 0, writable: false },
            target: null,
            timeStamp: null,
            type: null,

            preventDefault: function () {
                this._preventDefaultCalled = true;
            },
            stopImmediatePropagation: function () {
                this._stopImmediatePropagationCalled = true;
            },
            stopPropagation: function () {
            }
        }, {
            supportedForProcessing: false,
        }
    );

    var eventMixin = {
        _listeners: null,

        addEventListener: function (type, listener, useCapture) {
            /// <signature helpKeyword="WinJS.Utilities.eventMixin.addEventListener">
            /// <summary locid="WinJS.Utilities.eventMixin.addEventListener">
            /// Adds an event listener to the control.
            /// </summary>
            /// <param name="type" locid="WinJS.Utilities.eventMixin.addEventListener_p:type">
            /// The type (name) of the event.
            /// </param>
            /// <param name="listener" locid="WinJS.Utilities.eventMixin.addEventListener_p:listener">
            /// The listener to invoke when the event is raised.
            /// </param>
            /// <param name="useCapture" locid="WinJS.Utilities.eventMixin.addEventListener_p:useCapture">
            /// if true initiates capture, otherwise false.
            /// </param>
            /// </signature>
            useCapture = useCapture || false;
            this._listeners = this._listeners || {};
            var eventListeners = (this._listeners[type] = this._listeners[type] || []);
            for (var i = 0, len = eventListeners.length; i < len; i++) {
                var l = eventListeners[i];
                if (l.useCapture === useCapture && l.listener === listener) {
                    return;
                }
            }
            eventListeners.push({ listener: listener, useCapture: useCapture });
        },
        dispatchEvent: function (type, details) {
            /// <signature helpKeyword="WinJS.Utilities.eventMixin.dispatchEvent">
            /// <summary locid="WinJS.Utilities.eventMixin.dispatchEvent">
            /// Raises an event of the specified type and with the specified additional properties.
            /// </summary>
            /// <param name="type" locid="WinJS.Utilities.eventMixin.dispatchEvent_p:type">
            /// The type (name) of the event.
            /// </param>
            /// <param name="details" locid="WinJS.Utilities.eventMixin.dispatchEvent_p:details">
            /// The set of additional properties to be attached to the event object when the event is raised.
            /// </param>
            /// <returns type="Boolean" locid="WinJS.Utilities.eventMixin.dispatchEvent_returnValue">
            /// true if preventDefault was called on the event.
            /// </returns>
            /// </signature>
            var listeners = this._listeners && this._listeners[type];
            if (listeners) {
                var eventValue = new EventMixinEvent(type, details, this);
                // Need to copy the array to protect against people unregistering while we are dispatching
                listeners = listeners.slice(0, listeners.length);
                for (var i = 0, len = listeners.length; i < len && !eventValue._stopImmediatePropagationCalled; i++) {
                    listeners[i].listener(eventValue);
                }
                return eventValue.defaultPrevented || false;
            }
            return false;
        },
        removeEventListener: function (type, listener, useCapture) {
            /// <signature helpKeyword="WinJS.Utilities.eventMixin.removeEventListener">
            /// <summary locid="WinJS.Utilities.eventMixin.removeEventListener">
            /// Removes an event listener from the control.
            /// </summary>
            /// <param name="type" locid="WinJS.Utilities.eventMixin.removeEventListener_p:type">
            /// The type (name) of the event.
            /// </param>
            /// <param name="listener" locid="WinJS.Utilities.eventMixin.removeEventListener_p:listener">
            /// The listener to remove.
            /// </param>
            /// <param name="useCapture" locid="WinJS.Utilities.eventMixin.removeEventListener_p:useCapture">
            /// Specifies whether to initiate capture.
            /// </param>
            /// </signature>
            useCapture = useCapture || false;
            var listeners = this._listeners && this._listeners[type];
            if (listeners) {
                for (var i = 0, len = listeners.length; i < len; i++) {
                    var l = listeners[i];
                    if (l.listener === listener && l.useCapture === useCapture) {
                        listeners.splice(i, 1);
                        if (listeners.length === 0) {
                            delete this._listeners[type];
                        }
                        // Only want to remove one element for each call to removeEventListener
                        break;
                    }
                }
            }
        }
    };

    _Base.Namespace._moduleDefine(exports, "WinJS.Utilities", {
        _createEventProperty: createEventProperty,
        createEventProperties: createEventProperties,
        eventMixin: eventMixin
    });

});


_winjs("WinJS/Core/_Trace", ["WinJS/Core/_Global"], function traceInit(_Global) {
    "use strict";

    function nop(v) {
        return v;
    }

    return {
        _traceAsyncOperationStarting: (_Global.Debug && _Global.Debug.msTraceAsyncOperationStarting && _Global.Debug.msTraceAsyncOperationStarting.bind(_Global.Debug)) || nop,
        _traceAsyncOperationCompleted: (_Global.Debug && _Global.Debug.msTraceAsyncOperationCompleted && _Global.Debug.msTraceAsyncOperationCompleted.bind(_Global.Debug)) || nop,
        _traceAsyncCallbackStarting: (_Global.Debug && _Global.Debug.msTraceAsyncCallbackStarting && _Global.Debug.msTraceAsyncCallbackStarting.bind(_Global.Debug)) || nop,
        _traceAsyncCallbackCompleted: (_Global.Debug && _Global.Debug.msTraceAsyncCallbackCompleted && _Global.Debug.msTraceAsyncCallbackCompleted.bind(_Global.Debug)) || nop
    };
});
_winjs("WinJS/Promise/_StateMachine", ["WinJS/Core/_Global","WinJS/Core/_BaseCoreUtils","WinJS/Core/_Base","WinJS/Core/_ErrorFromName","WinJS/Core/_Events","WinJS/Core/_Trace"], function promiseStateMachineInit(_Global, _BaseCoreUtils, _Base, _ErrorFromName, _Events, _Trace) {
    "use strict";

    _Global.Debug && (_Global.Debug.setNonUserCodeExceptions = true);

    var ListenerType = _Base.Class.mix(_Base.Class.define(null, { /*empty*/ }, { supportedForProcessing: false }), _Events.eventMixin);
    var promiseEventListeners = new ListenerType();
    // make sure there is a listeners collection so that we can do a more trivial check below
    promiseEventListeners._listeners = {};
    var errorET = "error";
    var canceledName = "Canceled";
    var tagWithStack = false;
    var tag = {
        promise: 0x01,
        thenPromise: 0x02,
        errorPromise: 0x04,
        exceptionPromise: 0x08,
        completePromise: 0x10,
    };
    tag.all = tag.promise | tag.thenPromise | tag.errorPromise | tag.exceptionPromise | tag.completePromise;

    //
    // Global error counter, for each error which enters the system we increment this once and then
    // the error number travels with the error as it traverses the tree of potential handlers.
    //
    // When someone has registered to be told about errors (WinJS.Promise.callonerror) promises
    // which are in error will get tagged with a ._errorId field. This tagged field is the
    // contract by which nested promises with errors will be identified as chaining for the
    // purposes of the callonerror semantics. If a nested promise in error is encountered without
    // a ._errorId it will be assumed to be foreign and treated as an interop boundary and
    // a new error id will be minted.
    //
    var error_number = 1;

    //
    // The state machine has a interesting hiccup in it with regards to notification, in order
    // to flatten out notification and avoid recursion for synchronous completion we have an
    // explicit set of *_notify states which are responsible for notifying their entire tree
    // of children. They can do this because they know that immediate children are always
    // ThenPromise instances and we can therefore reach into their state to access the
    // _listeners collection.
    //
    // So, what happens is that a Promise will be fulfilled through the _completed or _error
    // messages at which point it will enter a *_notify state and be responsible for to move
    // its children into an (as appropriate) success or error state and also notify that child's
    // listeners of the state transition, until leaf notes are reached.
    //

    var state_created,              // -> working
        state_working,              // -> error | error_notify | success | success_notify | canceled | waiting
        state_waiting,              // -> error | error_notify | success | success_notify | waiting_canceled
        state_waiting_canceled,     // -> error | error_notify | success | success_notify | canceling
        state_canceled,             // -> error | error_notify | success | success_notify | canceling
        state_canceling,            // -> error_notify
        state_success_notify,       // -> success
        state_success,              // -> .
        state_error_notify,         // -> error
        state_error;                // -> .

    // Noop function, used in the various states to indicate that they don't support a given
    // message. Named with the somewhat cute name '_' because it reads really well in the states.

    function _() { }

    // Initial state
    //
    state_created = {
        name: "created",
        enter: function (promise) {
            promise._setState(state_working);
        },
        cancel: _,
        done: _,
        then: _,
        _completed: _,
        _error: _,
        _notify: _,
        _progress: _,
        _setCompleteValue: _,
        _setErrorValue: _
    };

    // Ready state, waiting for a message (completed/error/progress), able to be canceled
    //
    state_working = {
        name: "working",
        enter: _,
        cancel: function (promise) {
            promise._setState(state_canceled);
        },
        done: done,
        then: then,
        _completed: completed,
        _error: error,
        _notify: _,
        _progress: progress,
        _setCompleteValue: setCompleteValue,
        _setErrorValue: setErrorValue
    };

    // Waiting state, if a promise is completed with a value which is itself a promise
    // (has a then() method) it signs up to be informed when that child promise is
    // fulfilled at which point it will be fulfilled with that value.
    //
    state_waiting = {
        name: "waiting",
        enter: function (promise) {
            var waitedUpon = promise._value;
            // We can special case our own intermediate promises which are not in a
            //  terminal state by just pushing this promise as a listener without
            //  having to create new indirection functions
            if (waitedUpon instanceof ThenPromise &&
                waitedUpon._state !== state_error &&
                waitedUpon._state !== state_success) {
                pushListener(waitedUpon, { promise: promise });
            } else {
                var error = function (value) {
                    if (waitedUpon._errorId) {
                        promise._chainedError(value, waitedUpon);
                    } else {
                        // Because this is an interop boundary we want to indicate that this
                        //  error has been handled by the promise infrastructure before we
                        //  begin a new handling chain.
                        //
                        callonerror(promise, value, detailsForHandledError, waitedUpon, error);
                        promise._error(value);
                    }
                };
                error.handlesOnError = true;
                waitedUpon.then(
                    promise._completed.bind(promise),
                    error,
                    promise._progress.bind(promise)
                );
            }
        },
        cancel: function (promise) {
            promise._setState(state_waiting_canceled);
        },
        done: done,
        then: then,
        _completed: completed,
        _error: error,
        _notify: _,
        _progress: progress,
        _setCompleteValue: setCompleteValue,
        _setErrorValue: setErrorValue
    };

    // Waiting canceled state, when a promise has been in a waiting state and receives a
    // request to cancel its pending work it will forward that request to the child promise
    // and then waits to be informed of the result. This promise moves itself into the
    // canceling state but understands that the child promise may instead push it to a
    // different state.
    //
    state_waiting_canceled = {
        name: "waiting_canceled",
        enter: function (promise) {
            // Initiate a transition to canceling. Triggering a cancel on the promise
            // that we are waiting upon may result in a different state transition
            // before the state machine pump runs again.
            promise._setState(state_canceling);
            var waitedUpon = promise._value;
            if (waitedUpon.cancel) {
                waitedUpon.cancel();
            }
        },
        cancel: _,
        done: done,
        then: then,
        _completed: completed,
        _error: error,
        _notify: _,
        _progress: progress,
        _setCompleteValue: setCompleteValue,
        _setErrorValue: setErrorValue
    };

    // Canceled state, moves to the canceling state and then tells the promise to do
    // whatever it might need to do on cancelation.
    //
    state_canceled = {
        name: "canceled",
        enter: function (promise) {
            // Initiate a transition to canceling. The _cancelAction may change the state
            // before the state machine pump runs again.
            promise._setState(state_canceling);
            promise._cancelAction();
        },
        cancel: _,
        done: done,
        then: then,
        _completed: completed,
        _error: error,
        _notify: _,
        _progress: progress,
        _setCompleteValue: setCompleteValue,
        _setErrorValue: setErrorValue
    };

    // Canceling state, commits to the promise moving to an error state with an error
    // object whose 'name' and 'message' properties contain the string "Canceled"
    //
    state_canceling = {
        name: "canceling",
        enter: function (promise) {
            var error = new Error(canceledName);
            error.name = error.message;
            promise._value = error;
            promise._setState(state_error_notify);
        },
        cancel: _,
        done: _,
        then: _,
        _completed: _,
        _error: _,
        _notify: _,
        _progress: _,
        _setCompleteValue: _,
        _setErrorValue: _
    };

    // Success notify state, moves a promise to the success state and notifies all children
    //
    state_success_notify = {
        name: "complete_notify",
        enter: function (promise) {
            promise.done = CompletePromise.prototype.done;
            promise.then = CompletePromise.prototype.then;
            if (promise._listeners) {
                var queue = [promise];
                var p;
                while (queue.length) {
                    p = queue.shift();
                    p._state._notify(p, queue);
                }
            }
            promise._setState(state_success);
        },
        cancel: _,
        done: null, /*error to get here */
        then: null, /*error to get here */
        _completed: _,
        _error: _,
        _notify: notifySuccess,
        _progress: _,
        _setCompleteValue: _,
        _setErrorValue: _
    };

    // Success state, moves a promise to the success state and does NOT notify any children.
    // Some upstream promise is owning the notification pass.
    //
    state_success = {
        name: "success",
        enter: function (promise) {
            promise.done = CompletePromise.prototype.done;
            promise.then = CompletePromise.prototype.then;
            promise._cleanupAction();
        },
        cancel: _,
        done: null, /*error to get here */
        then: null, /*error to get here */
        _completed: _,
        _error: _,
        _notify: notifySuccess,
        _progress: _,
        _setCompleteValue: _,
        _setErrorValue: _
    };

    // Error notify state, moves a promise to the error state and notifies all children
    //
    state_error_notify = {
        name: "error_notify",
        enter: function (promise) {
            promise.done = ErrorPromise.prototype.done;
            promise.then = ErrorPromise.prototype.then;
            if (promise._listeners) {
                var queue = [promise];
                var p;
                while (queue.length) {
                    p = queue.shift();
                    p._state._notify(p, queue);
                }
            }
            promise._setState(state_error);
        },
        cancel: _,
        done: null, /*error to get here*/
        then: null, /*error to get here*/
        _completed: _,
        _error: _,
        _notify: notifyError,
        _progress: _,
        _setCompleteValue: _,
        _setErrorValue: _
    };

    // Error state, moves a promise to the error state and does NOT notify any children.
    // Some upstream promise is owning the notification pass.
    //
    state_error = {
        name: "error",
        enter: function (promise) {
            promise.done = ErrorPromise.prototype.done;
            promise.then = ErrorPromise.prototype.then;
            promise._cleanupAction();
        },
        cancel: _,
        done: null, /*error to get here*/
        then: null, /*error to get here*/
        _completed: _,
        _error: _,
        _notify: notifyError,
        _progress: _,
        _setCompleteValue: _,
        _setErrorValue: _
    };

    //
    // The statemachine implementation follows a very particular pattern, the states are specified
    // as static stateless bags of functions which are then indirected through the state machine
    // instance (a Promise). As such all of the functions on each state have the promise instance
    // passed to them explicitly as a parameter and the Promise instance members do a little
    // dance where they indirect through the state and insert themselves in the argument list.
    //
    // We could instead call directly through the promise states however then every caller
    // would have to remember to do things like pumping the state machine to catch state transitions.
    //

    var PromiseStateMachine = _Base.Class.define(null, {
        _listeners: null,
        _nextState: null,
        _state: null,
        _value: null,

        cancel: function () {
            /// <signature helpKeyword="WinJS.PromiseStateMachine.cancel">
            /// <summary locid="WinJS.PromiseStateMachine.cancel">
            /// Attempts to cancel the fulfillment of a promised value. If the promise hasn't
            /// already been fulfilled and cancellation is supported, the promise enters
            /// the error state with a value of Error("Canceled").
            /// </summary>
            /// </signature>
            this._state.cancel(this);
            this._run();
        },
        done: function Promise_done(onComplete, onError, onProgress) {
            /// <signature helpKeyword="WinJS.PromiseStateMachine.done">
            /// <summary locid="WinJS.PromiseStateMachine.done">
            /// Allows you to specify the work to be done on the fulfillment of the promised value,
            /// the error handling to be performed if the promise fails to fulfill
            /// a value, and the handling of progress notifications along the way.
            ///
            /// After the handlers have finished executing, this function throws any error that would have been returned
            /// from then() as a promise in the error state.
            /// </summary>
            /// <param name='onComplete' type='Function' locid="WinJS.PromiseStateMachine.done_p:onComplete">
            /// The function to be called if the promise is fulfilled successfully with a value.
            /// The fulfilled value is passed as the single argument. If the value is null,
            /// the fulfilled value is returned. The value returned
            /// from the function becomes the fulfilled value of the promise returned by
            /// then(). If an exception is thrown while executing the function, the promise returned
            /// by then() moves into the error state.
            /// </param>
            /// <param name='onError' type='Function' optional='true' locid="WinJS.PromiseStateMachine.done_p:onError">
            /// The function to be called if the promise is fulfilled with an error. The error
            /// is passed as the single argument. If it is null, the error is forwarded.
            /// The value returned from the function is the fulfilled value of the promise returned by then().
            /// </param>
            /// <param name='onProgress' type='Function' optional='true' locid="WinJS.PromiseStateMachine.done_p:onProgress">
            /// the function to be called if the promise reports progress. Data about the progress
            /// is passed as the single argument. Promises are not required to support
            /// progress.
            /// </param>
            /// </signature>
            this._state.done(this, onComplete, onError, onProgress);
        },
        then: function Promise_then(onComplete, onError, onProgress) {
            /// <signature helpKeyword="WinJS.PromiseStateMachine.then">
            /// <summary locid="WinJS.PromiseStateMachine.then">
            /// Allows you to specify the work to be done on the fulfillment of the promised value,
            /// the error handling to be performed if the promise fails to fulfill
            /// a value, and the handling of progress notifications along the way.
            /// </summary>
            /// <param name='onComplete' type='Function' locid="WinJS.PromiseStateMachine.then_p:onComplete">
            /// The function to be called if the promise is fulfilled successfully with a value.
            /// The value is passed as the single argument. If the value is null, the value is returned.
            /// The value returned from the function becomes the fulfilled value of the promise returned by
            /// then(). If an exception is thrown while this function is being executed, the promise returned
            /// by then() moves into the error state.
            /// </param>
            /// <param name='onError' type='Function' optional='true' locid="WinJS.PromiseStateMachine.then_p:onError">
            /// The function to be called if the promise is fulfilled with an error. The error
            /// is passed as the single argument. If it is null, the error is forwarded.
            /// The value returned from the function becomes the fulfilled value of the promise returned by then().
            /// </param>
            /// <param name='onProgress' type='Function' optional='true' locid="WinJS.PromiseStateMachine.then_p:onProgress">
            /// The function to be called if the promise reports progress. Data about the progress
            /// is passed as the single argument. Promises are not required to support
            /// progress.
            /// </param>
            /// <returns type="WinJS.Promise" locid="WinJS.PromiseStateMachine.then_returnValue">
            /// The promise whose value is the result of executing the complete or
            /// error function.
            /// </returns>
            /// </signature>
            return this._state.then(this, onComplete, onError, onProgress);
        },

        _chainedError: function (value, context) {
            var result = this._state._error(this, value, detailsForChainedError, context);
            this._run();
            return result;
        },
        _completed: function (value) {
            var result = this._state._completed(this, value);
            this._run();
            return result;
        },
        _error: function (value) {
            var result = this._state._error(this, value, detailsForError);
            this._run();
            return result;
        },
        _progress: function (value) {
            this._state._progress(this, value);
        },
        _setState: function (state) {
            this._nextState = state;
        },
        _setCompleteValue: function (value) {
            this._state._setCompleteValue(this, value);
            this._run();
        },
        _setChainedErrorValue: function (value, context) {
            var result = this._state._setErrorValue(this, value, detailsForChainedError, context);
            this._run();
            return result;
        },
        _setExceptionValue: function (value) {
            var result = this._state._setErrorValue(this, value, detailsForException);
            this._run();
            return result;
        },
        _run: function () {
            while (this._nextState) {
                this._state = this._nextState;
                this._nextState = null;
                this._state.enter(this);
            }
        }
    }, {
        supportedForProcessing: false
    });

    //
    // Implementations of shared state machine code.
    //

    function completed(promise, value) {
        var targetState;
        if (value && typeof value === "object" && typeof value.then === "function") {
            targetState = state_waiting;
        } else {
            targetState = state_success_notify;
        }
        promise._value = value;
        promise._setState(targetState);
    }
    function createErrorDetails(exception, error, promise, id, parent, handler) {
        return {
            exception: exception,
            error: error,
            promise: promise,
            handler: handler,
            id: id,
            parent: parent
        };
    }
    function detailsForHandledError(promise, errorValue, context, handler) {
        var exception = context._isException;
        var errorId = context._errorId;
        return createErrorDetails(
            exception ? errorValue : null,
            exception ? null : errorValue,
            promise,
            errorId,
            context,
            handler
        );
    }
    function detailsForChainedError(promise, errorValue, context) {
        var exception = context._isException;
        var errorId = context._errorId;
        setErrorInfo(promise, errorId, exception);
        return createErrorDetails(
            exception ? errorValue : null,
            exception ? null : errorValue,
            promise,
            errorId,
            context
        );
    }
    function detailsForError(promise, errorValue) {
        var errorId = ++error_number;
        setErrorInfo(promise, errorId);
        return createErrorDetails(
            null,
            errorValue,
            promise,
            errorId
        );
    }
    function detailsForException(promise, exceptionValue) {
        var errorId = ++error_number;
        setErrorInfo(promise, errorId, true);
        return createErrorDetails(
            exceptionValue,
            null,
            promise,
            errorId
        );
    }
    function done(promise, onComplete, onError, onProgress) {
        var asyncOpID = _Trace._traceAsyncOperationStarting("WinJS.Promise.done");
        pushListener(promise, { c: onComplete, e: onError, p: onProgress, asyncOpID: asyncOpID });
    }
    function error(promise, value, onerrorDetails, context) {
        promise._value = value;
        callonerror(promise, value, onerrorDetails, context);
        promise._setState(state_error_notify);
    }
    function notifySuccess(promise, queue) {
        var value = promise._value;
        var listeners = promise._listeners;
        if (!listeners) {
            return;
        }
        promise._listeners = null;
        var i, len;
        for (i = 0, len = Array.isArray(listeners) ? listeners.length : 1; i < len; i++) {
            var listener = len === 1 ? listeners : listeners[i];
            var onComplete = listener.c;
            var target = listener.promise;

            _Trace._traceAsyncOperationCompleted(listener.asyncOpID, _Global.Debug && _Global.Debug.MS_ASYNC_OP_STATUS_SUCCESS);

            if (target) {
                _Trace._traceAsyncCallbackStarting(listener.asyncOpID);
                try {
                    target._setCompleteValue(onComplete ? onComplete(value) : value);
                } catch (ex) {
                    target._setExceptionValue(ex);
                } finally {
                    _Trace._traceAsyncCallbackCompleted();
                }
                if (target._state !== state_waiting && target._listeners) {
                    queue.push(target);
                }
            } else {
                CompletePromise.prototype.done.call(promise, onComplete);
            }
        }
    }
    function notifyError(promise, queue) {
        var value = promise._value;
        var listeners = promise._listeners;
        if (!listeners) {
            return;
        }
        promise._listeners = null;
        var i, len;
        for (i = 0, len = Array.isArray(listeners) ? listeners.length : 1; i < len; i++) {
            var listener = len === 1 ? listeners : listeners[i];
            var onError = listener.e;
            var target = listener.promise;

            var errorID = _Global.Debug && (value && value.name === canceledName ? _Global.Debug.MS_ASYNC_OP_STATUS_CANCELED : _Global.Debug.MS_ASYNC_OP_STATUS_ERROR);
            _Trace._traceAsyncOperationCompleted(listener.asyncOpID, errorID);

            if (target) {
                var asyncCallbackStarted = false;
                try {
                    if (onError) {
                        _Trace._traceAsyncCallbackStarting(listener.asyncOpID);
                        asyncCallbackStarted = true;
                        if (!onError.handlesOnError) {
                            callonerror(target, value, detailsForHandledError, promise, onError);
                        }
                        target._setCompleteValue(onError(value));
                    } else {
                        target._setChainedErrorValue(value, promise);
                    }
                } catch (ex) {
                    target._setExceptionValue(ex);
                } finally {
                    if (asyncCallbackStarted) {
                        _Trace._traceAsyncCallbackCompleted();
                    }
                }
                if (target._state !== state_waiting && target._listeners) {
                    queue.push(target);
                }
            } else {
                ErrorPromise.prototype.done.call(promise, null, onError);
            }
        }
    }
    function callonerror(promise, value, onerrorDetailsGenerator, context, handler) {
        if (promiseEventListeners._listeners[errorET]) {
            if (value instanceof Error && value.message === canceledName) {
                return;
            }
            promiseEventListeners.dispatchEvent(errorET, onerrorDetailsGenerator(promise, value, context, handler));
        }
    }
    function progress(promise, value) {
        var listeners = promise._listeners;
        if (listeners) {
            var i, len;
            for (i = 0, len = Array.isArray(listeners) ? listeners.length : 1; i < len; i++) {
                var listener = len === 1 ? listeners : listeners[i];
                var onProgress = listener.p;
                if (onProgress) {
                    try { onProgress(value); } catch (ex) { }
                }
                if (!(listener.c || listener.e) && listener.promise) {
                    listener.promise._progress(value);
                }
            }
        }
    }
    function pushListener(promise, listener) {
        var listeners = promise._listeners;
        if (listeners) {
            // We may have either a single listener (which will never be wrapped in an array)
            // or 2+ listeners (which will be wrapped). Since we are now adding one more listener
            // we may have to wrap the single listener before adding the second.
            listeners = Array.isArray(listeners) ? listeners : [listeners];
            listeners.push(listener);
        } else {
            listeners = listener;
        }
        promise._listeners = listeners;
    }
    // The difference beween setCompleteValue()/setErrorValue() and complete()/error() is that setXXXValue() moves
    // a promise directly to the success/error state without starting another notification pass (because one
    // is already ongoing).
    function setErrorInfo(promise, errorId, isException) {
        promise._isException = isException || false;
        promise._errorId = errorId;
    }
    function setErrorValue(promise, value, onerrorDetails, context) {
        promise._value = value;
        callonerror(promise, value, onerrorDetails, context);
        promise._setState(state_error);
    }
    function setCompleteValue(promise, value) {
        var targetState;
        if (value && typeof value === "object" && typeof value.then === "function") {
            targetState = state_waiting;
        } else {
            targetState = state_success;
        }
        promise._value = value;
        promise._setState(targetState);
    }
    function then(promise, onComplete, onError, onProgress) {
        var result = new ThenPromise(promise);
        var asyncOpID = _Trace._traceAsyncOperationStarting("WinJS.Promise.then");
        pushListener(promise, { promise: result, c: onComplete, e: onError, p: onProgress, asyncOpID: asyncOpID });
        return result;
    }

    //
    // Internal implementation detail promise, ThenPromise is created when a promise needs
    // to be returned from a then() method.
    //
    var ThenPromise = _Base.Class.derive(PromiseStateMachine,
        function (creator) {

            if (tagWithStack && (tagWithStack === true || (tagWithStack & tag.thenPromise))) {
                this._stack = Promise._getStack();
            }

            this._creator = creator;
            this._setState(state_created);
            this._run();
        }, {
            _creator: null,

            _cancelAction: function () { if (this._creator) { this._creator.cancel(); } },
            _cleanupAction: function () { this._creator = null; }
        }, {
            supportedForProcessing: false
        }
    );

    //
    // Slim promise implementations for already completed promises, these are created
    // under the hood on synchronous completion paths as well as by WinJS.Promise.wrap
    // and WinJS.Promise.wrapError.
    //

    var ErrorPromise = _Base.Class.define(
        function ErrorPromise_ctor(value) {

            if (tagWithStack && (tagWithStack === true || (tagWithStack & tag.errorPromise))) {
                this._stack = Promise._getStack();
            }

            this._value = value;
            callonerror(this, value, detailsForError);
        }, {
            cancel: function () {
                /// <signature helpKeyword="WinJS.PromiseStateMachine.cancel">
                /// <summary locid="WinJS.PromiseStateMachine.cancel">
                /// Attempts to cancel the fulfillment of a promised value. If the promise hasn't
                /// already been fulfilled and cancellation is supported, the promise enters
                /// the error state with a value of Error("Canceled").
                /// </summary>
                /// </signature>
            },
            done: function ErrorPromise_done(unused, onError) {
                /// <signature helpKeyword="WinJS.PromiseStateMachine.done">
                /// <summary locid="WinJS.PromiseStateMachine.done">
                /// Allows you to specify the work to be done on the fulfillment of the promised value,
                /// the error handling to be performed if the promise fails to fulfill
                /// a value, and the handling of progress notifications along the way.
                ///
                /// After the handlers have finished executing, this function throws any error that would have been returned
                /// from then() as a promise in the error state.
                /// </summary>
                /// <param name='onComplete' type='Function' locid="WinJS.PromiseStateMachine.done_p:onComplete">
                /// The function to be called if the promise is fulfilled successfully with a value.
                /// The fulfilled value is passed as the single argument. If the value is null,
                /// the fulfilled value is returned. The value returned
                /// from the function becomes the fulfilled value of the promise returned by
                /// then(). If an exception is thrown while executing the function, the promise returned
                /// by then() moves into the error state.
                /// </param>
                /// <param name='onError' type='Function' optional='true' locid="WinJS.PromiseStateMachine.done_p:onError">
                /// The function to be called if the promise is fulfilled with an error. The error
                /// is passed as the single argument. If it is null, the error is forwarded.
                /// The value returned from the function is the fulfilled value of the promise returned by then().
                /// </param>
                /// <param name='onProgress' type='Function' optional='true' locid="WinJS.PromiseStateMachine.done_p:onProgress">
                /// the function to be called if the promise reports progress. Data about the progress
                /// is passed as the single argument. Promises are not required to support
                /// progress.
                /// </param>
                /// </signature>
                var value = this._value;
                if (onError) {
                    try {
                        if (!onError.handlesOnError) {
                            callonerror(null, value, detailsForHandledError, this, onError);
                        }
                        var result = onError(value);
                        if (result && typeof result === "object" && typeof result.done === "function") {
                            // If a promise is returned we need to wait on it.
                            result.done();
                        }
                        return;
                    } catch (ex) {
                        value = ex;
                    }
                }
                if (value instanceof Error && value.message === canceledName) {
                    // suppress cancel
                    return;
                }
                // force the exception to be thrown asyncronously to avoid any try/catch blocks
                //
                Promise._doneHandler(value);
            },
            then: function ErrorPromise_then(unused, onError) {
                /// <signature helpKeyword="WinJS.PromiseStateMachine.then">
                /// <summary locid="WinJS.PromiseStateMachine.then">
                /// Allows you to specify the work to be done on the fulfillment of the promised value,
                /// the error handling to be performed if the promise fails to fulfill
                /// a value, and the handling of progress notifications along the way.
                /// </summary>
                /// <param name='onComplete' type='Function' locid="WinJS.PromiseStateMachine.then_p:onComplete">
                /// The function to be called if the promise is fulfilled successfully with a value.
                /// The value is passed as the single argument. If the value is null, the value is returned.
                /// The value returned from the function becomes the fulfilled value of the promise returned by
                /// then(). If an exception is thrown while this function is being executed, the promise returned
                /// by then() moves into the error state.
                /// </param>
                /// <param name='onError' type='Function' optional='true' locid="WinJS.PromiseStateMachine.then_p:onError">
                /// The function to be called if the promise is fulfilled with an error. The error
                /// is passed as the single argument. If it is null, the error is forwarded.
                /// The value returned from the function becomes the fulfilled value of the promise returned by then().
                /// </param>
                /// <param name='onProgress' type='Function' optional='true' locid="WinJS.PromiseStateMachine.then_p:onProgress">
                /// The function to be called if the promise reports progress. Data about the progress
                /// is passed as the single argument. Promises are not required to support
                /// progress.
                /// </param>
                /// <returns type="WinJS.Promise" locid="WinJS.PromiseStateMachine.then_returnValue">
                /// The promise whose value is the result of executing the complete or
                /// error function.
                /// </returns>
                /// </signature>

                // If the promise is already in a error state and no error handler is provided
                // we optimize by simply returning the promise instead of creating a new one.
                //
                if (!onError) { return this; }
                var result;
                var value = this._value;
                try {
                    if (!onError.handlesOnError) {
                        callonerror(null, value, detailsForHandledError, this, onError);
                    }
                    result = new CompletePromise(onError(value));
                } catch (ex) {
                    // If the value throw from the error handler is the same as the value
                    // provided to the error handler then there is no need for a new promise.
                    //
                    if (ex === value) {
                        result = this;
                    } else {
                        result = new ExceptionPromise(ex);
                    }
                }
                return result;
            }
        }, {
            supportedForProcessing: false
        }
    );

    var ExceptionPromise = _Base.Class.derive(ErrorPromise,
        function ExceptionPromise_ctor(value) {

            if (tagWithStack && (tagWithStack === true || (tagWithStack & tag.exceptionPromise))) {
                this._stack = Promise._getStack();
            }

            this._value = value;
            callonerror(this, value, detailsForException);
        }, {
            /* empty */
        }, {
            supportedForProcessing: false
        }
    );

    var CompletePromise = _Base.Class.define(
        function CompletePromise_ctor(value) {

            if (tagWithStack && (tagWithStack === true || (tagWithStack & tag.completePromise))) {
                this._stack = Promise._getStack();
            }

            if (value && typeof value === "object" && typeof value.then === "function") {
                var result = new ThenPromise(null);
                result._setCompleteValue(value);
                return result;
            }
            this._value = value;
        }, {
            cancel: function () {
                /// <signature helpKeyword="WinJS.PromiseStateMachine.cancel">
                /// <summary locid="WinJS.PromiseStateMachine.cancel">
                /// Attempts to cancel the fulfillment of a promised value. If the promise hasn't
                /// already been fulfilled and cancellation is supported, the promise enters
                /// the error state with a value of Error("Canceled").
                /// </summary>
                /// </signature>
            },
            done: function CompletePromise_done(onComplete) {
                /// <signature helpKeyword="WinJS.PromiseStateMachine.done">
                /// <summary locid="WinJS.PromiseStateMachine.done">
                /// Allows you to specify the work to be done on the fulfillment of the promised value,
                /// the error handling to be performed if the promise fails to fulfill
                /// a value, and the handling of progress notifications along the way.
                ///
                /// After the handlers have finished executing, this function throws any error that would have been returned
                /// from then() as a promise in the error state.
                /// </summary>
                /// <param name='onComplete' type='Function' locid="WinJS.PromiseStateMachine.done_p:onComplete">
                /// The function to be called if the promise is fulfilled successfully with a value.
                /// The fulfilled value is passed as the single argument. If the value is null,
                /// the fulfilled value is returned. The value returned
                /// from the function becomes the fulfilled value of the promise returned by
                /// then(). If an exception is thrown while executing the function, the promise returned
                /// by then() moves into the error state.
                /// </param>
                /// <param name='onError' type='Function' optional='true' locid="WinJS.PromiseStateMachine.done_p:onError">
                /// The function to be called if the promise is fulfilled with an error. The error
                /// is passed as the single argument. If it is null, the error is forwarded.
                /// The value returned from the function is the fulfilled value of the promise returned by then().
                /// </param>
                /// <param name='onProgress' type='Function' optional='true' locid="WinJS.PromiseStateMachine.done_p:onProgress">
                /// the function to be called if the promise reports progress. Data about the progress
                /// is passed as the single argument. Promises are not required to support
                /// progress.
                /// </param>
                /// </signature>
                if (!onComplete) { return; }
                try {
                    var result = onComplete(this._value);
                    if (result && typeof result === "object" && typeof result.done === "function") {
                        result.done();
                    }
                } catch (ex) {
                    // force the exception to be thrown asynchronously to avoid any try/catch blocks
                    Promise._doneHandler(ex);
                }
            },
            then: function CompletePromise_then(onComplete) {
                /// <signature helpKeyword="WinJS.PromiseStateMachine.then">
                /// <summary locid="WinJS.PromiseStateMachine.then">
                /// Allows you to specify the work to be done on the fulfillment of the promised value,
                /// the error handling to be performed if the promise fails to fulfill
                /// a value, and the handling of progress notifications along the way.
                /// </summary>
                /// <param name='onComplete' type='Function' locid="WinJS.PromiseStateMachine.then_p:onComplete">
                /// The function to be called if the promise is fulfilled successfully with a value.
                /// The value is passed as the single argument. If the value is null, the value is returned.
                /// The value returned from the function becomes the fulfilled value of the promise returned by
                /// then(). If an exception is thrown while this function is being executed, the promise returned
                /// by then() moves into the error state.
                /// </param>
                /// <param name='onError' type='Function' optional='true' locid="WinJS.PromiseStateMachine.then_p:onError">
                /// The function to be called if the promise is fulfilled with an error. The error
                /// is passed as the single argument. If it is null, the error is forwarded.
                /// The value returned from the function becomes the fulfilled value of the promise returned by then().
                /// </param>
                /// <param name='onProgress' type='Function' optional='true' locid="WinJS.PromiseStateMachine.then_p:onProgress">
                /// The function to be called if the promise reports progress. Data about the progress
                /// is passed as the single argument. Promises are not required to support
                /// progress.
                /// </param>
                /// <returns type="WinJS.Promise" locid="WinJS.PromiseStateMachine.then_returnValue">
                /// The promise whose value is the result of executing the complete or
                /// error function.
                /// </returns>
                /// </signature>
                try {
                    // If the value returned from the completion handler is the same as the value
                    // provided to the completion handler then there is no need for a new promise.
                    //
                    var newValue = onComplete ? onComplete(this._value) : this._value;
                    return newValue === this._value ? this : new CompletePromise(newValue);
                } catch (ex) {
                    return new ExceptionPromise(ex);
                }
            }
        }, {
            supportedForProcessing: false
        }
    );

    //
    // Promise is the user-creatable WinJS.Promise object.
    //

    function timeout(timeoutMS) {
        var id;
        return new Promise(
            function (c) {
                if (timeoutMS) {
                    id = _Global.setTimeout(c, timeoutMS);
                } else {
                    _BaseCoreUtils._setImmediate(c);
                }
            },
            function () {
                if (id) {
                    _Global.clearTimeout(id);
                }
            }
        );
    }

    function timeoutWithPromise(timeout, promise) {
        var cancelPromise = function () { promise.cancel(); };
        var cancelTimeout = function () { timeout.cancel(); };
        timeout.then(cancelPromise);
        promise.then(cancelTimeout, cancelTimeout);
        return promise;
    }

    var staticCanceledPromise;

    var Promise = _Base.Class.derive(PromiseStateMachine,
        function Promise_ctor(init, oncancel) {
            /// <signature helpKeyword="WinJS.Promise">
            /// <summary locid="WinJS.Promise">
            /// A promise provides a mechanism to schedule work to be done on a value that
            /// has not yet been computed. It is a convenient abstraction for managing
            /// interactions with asynchronous APIs.
            /// </summary>
            /// <param name="init" type="Function" locid="WinJS.Promise_p:init">
            /// The function that is called during construction of the  promise. The function
            /// is given three arguments (complete, error, progress). Inside this function
            /// you should add event listeners for the notifications supported by this value.
            /// </param>
            /// <param name="oncancel" optional="true" locid="WinJS.Promise_p:oncancel">
            /// The function to call if a consumer of this promise wants
            /// to cancel its undone work. Promises are not required to
            /// support cancellation.
            /// </param>
            /// </signature>

            if (tagWithStack && (tagWithStack === true || (tagWithStack & tag.promise))) {
                this._stack = Promise._getStack();
            }

            this._oncancel = oncancel;
            this._setState(state_created);
            this._run();

            try {
                var complete = this._completed.bind(this);
                var error = this._error.bind(this);
                var progress = this._progress.bind(this);
                init(complete, error, progress);
            } catch (ex) {
                this._setExceptionValue(ex);
            }
        }, {
            _oncancel: null,

            _cancelAction: function () {
                // BEGIN monaco change
                try {
                    if (this._oncancel) {
                        this._oncancel();
                    } else {
                        throw new Error('Promise did not implement oncancel');
                    }
                } catch (ex) {
                    // Access fields to get them created
                    var msg = ex.message;
                    var stack = ex.stack;
                    promiseEventListeners.dispatchEvent('error', ex);
                }
                // END monaco change
            },
            _cleanupAction: function () { this._oncancel = null; }
        }, {

            addEventListener: function Promise_addEventListener(eventType, listener, capture) {
                /// <signature helpKeyword="WinJS.Promise.addEventListener">
                /// <summary locid="WinJS.Promise.addEventListener">
                /// Adds an event listener to the control.
                /// </summary>
                /// <param name="eventType" locid="WinJS.Promise.addEventListener_p:eventType">
                /// The type (name) of the event.
                /// </param>
                /// <param name="listener" locid="WinJS.Promise.addEventListener_p:listener">
                /// The listener to invoke when the event is raised.
                /// </param>
                /// <param name="capture" locid="WinJS.Promise.addEventListener_p:capture">
                /// Specifies whether or not to initiate capture.
                /// </param>
                /// </signature>
                promiseEventListeners.addEventListener(eventType, listener, capture);
            },
            any: function Promise_any(values) {
                /// <signature helpKeyword="WinJS.Promise.any">
                /// <summary locid="WinJS.Promise.any">
                /// Returns a promise that is fulfilled when one of the input promises
                /// has been fulfilled.
                /// </summary>
                /// <param name="values" type="Array" locid="WinJS.Promise.any_p:values">
                /// An array that contains promise objects or objects whose property
                /// values include promise objects.
                /// </param>
                /// <returns type="WinJS.Promise" locid="WinJS.Promise.any_returnValue">
                /// A promise that on fulfillment yields the value of the input (complete or error).
                /// </returns>
                /// </signature>
                return new Promise(
                    function (complete, error) {
                        var keys = Object.keys(values);
                        if (keys.length === 0) {
                            complete();
                        }
                        var canceled = 0;
                        keys.forEach(function (key) {
                            Promise.as(values[key]).then(
                                function () { complete({ key: key, value: values[key] }); },
                                function (e) {
                                    if (e instanceof Error && e.name === canceledName) {
                                        if ((++canceled) === keys.length) {
                                            complete(Promise.cancel);
                                        }
                                        return;
                                    }
                                    error({ key: key, value: values[key] });
                                }
                            );
                        });
                    },
                    function () {
                        var keys = Object.keys(values);
                        keys.forEach(function (key) {
                            var promise = Promise.as(values[key]);
                            if (typeof promise.cancel === "function") {
                                promise.cancel();
                            }
                        });
                    }
                );
            },
            as: function Promise_as(value) {
                /// <signature helpKeyword="WinJS.Promise.as">
                /// <summary locid="WinJS.Promise.as">
                /// Returns a promise. If the object is already a promise it is returned;
                /// otherwise the object is wrapped in a promise.
                /// </summary>
                /// <param name="value" locid="WinJS.Promise.as_p:value">
                /// The value to be treated as a promise.
                /// </param>
                /// <returns type="WinJS.Promise" locid="WinJS.Promise.as_returnValue">
                /// A promise.
                /// </returns>
                /// </signature>
                if (value && typeof value === "object" && typeof value.then === "function") {
                    return value;
                }
                return new CompletePromise(value);
            },
            /// <field type="WinJS.Promise" helpKeyword="WinJS.Promise.cancel" locid="WinJS.Promise.cancel">
            /// Canceled promise value, can be returned from a promise completion handler
            /// to indicate cancelation of the promise chain.
            /// </field>
            cancel: {
                get: function () {
                    return (staticCanceledPromise = staticCanceledPromise || new ErrorPromise(new _ErrorFromName(canceledName)));
                }
            },
            dispatchEvent: function Promise_dispatchEvent(eventType, details) {
                /// <signature helpKeyword="WinJS.Promise.dispatchEvent">
                /// <summary locid="WinJS.Promise.dispatchEvent">
                /// Raises an event of the specified type and properties.
                /// </summary>
                /// <param name="eventType" locid="WinJS.Promise.dispatchEvent_p:eventType">
                /// The type (name) of the event.
                /// </param>
                /// <param name="details" locid="WinJS.Promise.dispatchEvent_p:details">
                /// The set of additional properties to be attached to the event object.
                /// </param>
                /// <returns type="Boolean" locid="WinJS.Promise.dispatchEvent_returnValue">
                /// Specifies whether preventDefault was called on the event.
                /// </returns>
                /// </signature>
                return promiseEventListeners.dispatchEvent(eventType, details);
            },
            is: function Promise_is(value) {
                /// <signature helpKeyword="WinJS.Promise.is">
                /// <summary locid="WinJS.Promise.is">
                /// Determines whether a value fulfills the promise contract.
                /// </summary>
                /// <param name="value" locid="WinJS.Promise.is_p:value">
                /// A value that may be a promise.
                /// </param>
                /// <returns type="Boolean" locid="WinJS.Promise.is_returnValue">
                /// true if the specified value is a promise, otherwise false.
                /// </returns>
                /// </signature>
                return value && typeof value === "object" && typeof value.then === "function";
            },
            join: function Promise_join(values) {
                /// <signature helpKeyword="WinJS.Promise.join">
                /// <summary locid="WinJS.Promise.join">
                /// Creates a promise that is fulfilled when all the values are fulfilled.
                /// </summary>
                /// <param name="values" type="Object" locid="WinJS.Promise.join_p:values">
                /// An object whose fields contain values, some of which may be promises.
                /// </param>
                /// <returns type="WinJS.Promise" locid="WinJS.Promise.join_returnValue">
                /// A promise whose value is an object with the same field names as those of the object in the values parameter, where
                /// each field value is the fulfilled value of a promise.
                /// </returns>
                /// </signature>
                return new Promise(
                    function (complete, error, progress) {
                        var keys = Object.keys(values);
                        var errors = Array.isArray(values) ? [] : {};
                        var results = Array.isArray(values) ? [] : {};
                        var undefineds = 0;
                        var pending = keys.length;
                        var argDone = function (key) {
                            if ((--pending) === 0) {
                                var errorCount = Object.keys(errors).length;
                                if (errorCount === 0) {
                                    complete(results);
                                } else {
                                    var canceledCount = 0;
                                    keys.forEach(function (key) {
                                        var e = errors[key];
                                        if (e instanceof Error && e.name === canceledName) {
                                            canceledCount++;
                                        }
                                    });
                                    if (canceledCount === errorCount) {
                                        complete(Promise.cancel);
                                    } else {
                                        error(errors);
                                    }
                                }
                            } else {
                                progress({ Key: key, Done: true });
                            }
                        };
                        keys.forEach(function (key) {
                            var value = values[key];
                            if (value === undefined) {
                                undefineds++;
                            } else {
                                Promise.then(value,
                                    function (value) { results[key] = value; argDone(key); },
                                    function (value) { errors[key] = value; argDone(key); }
                                );
                            }
                        });
                        pending -= undefineds;
                        if (pending === 0) {
                            complete(results);
                            return;
                        }
                    },
                    function () {
                        Object.keys(values).forEach(function (key) {
                            var promise = Promise.as(values[key]);
                            if (typeof promise.cancel === "function") {
                                promise.cancel();
                            }
                        });
                    }
                );
            },
            removeEventListener: function Promise_removeEventListener(eventType, listener, capture) {
                /// <signature helpKeyword="WinJS.Promise.removeEventListener">
                /// <summary locid="WinJS.Promise.removeEventListener">
                /// Removes an event listener from the control.
                /// </summary>
                /// <param name='eventType' locid="WinJS.Promise.removeEventListener_eventType">
                /// The type (name) of the event.
                /// </param>
                /// <param name='listener' locid="WinJS.Promise.removeEventListener_listener">
                /// The listener to remove.
                /// </param>
                /// <param name='capture' locid="WinJS.Promise.removeEventListener_capture">
                /// Specifies whether or not to initiate capture.
                /// </param>
                /// </signature>
                promiseEventListeners.removeEventListener(eventType, listener, capture);
            },
            supportedForProcessing: false,
            then: function Promise_then(value, onComplete, onError, onProgress) {
                /// <signature helpKeyword="WinJS.Promise.then">
                /// <summary locid="WinJS.Promise.then">
                /// A static version of the promise instance method then().
                /// </summary>
                /// <param name="value" locid="WinJS.Promise.then_p:value">
                /// the value to be treated as a promise.
                /// </param>
                /// <param name="onComplete" type="Function" locid="WinJS.Promise.then_p:complete">
                /// The function to be called if the promise is fulfilled with a value.
                /// If it is null, the promise simply
                /// returns the value. The value is passed as the single argument.
                /// </param>
                /// <param name="onError" type="Function" optional="true" locid="WinJS.Promise.then_p:error">
                /// The function to be called if the promise is fulfilled with an error. The error
                /// is passed as the single argument.
                /// </param>
                /// <param name="onProgress" type="Function" optional="true" locid="WinJS.Promise.then_p:progress">
                /// The function to be called if the promise reports progress. Data about the progress
                /// is passed as the single argument. Promises are not required to support
                /// progress.
                /// </param>
                /// <returns type="WinJS.Promise" locid="WinJS.Promise.then_returnValue">
                /// A promise whose value is the result of executing the provided complete function.
                /// </returns>
                /// </signature>
                return Promise.as(value).then(onComplete, onError, onProgress);
            },
            thenEach: function Promise_thenEach(values, onComplete, onError, onProgress) {
                /// <signature helpKeyword="WinJS.Promise.thenEach">
                /// <summary locid="WinJS.Promise.thenEach">
                /// Performs an operation on all the input promises and returns a promise
                /// that has the shape of the input and contains the result of the operation
                /// that has been performed on each input.
                /// </summary>
                /// <param name="values" locid="WinJS.Promise.thenEach_p:values">
                /// A set of values (which could be either an array or an object) of which some or all are promises.
                /// </param>
                /// <param name="onComplete" type="Function" locid="WinJS.Promise.thenEach_p:complete">
                /// The function to be called if the promise is fulfilled with a value.
                /// If the value is null, the promise returns the value.
                /// The value is passed as the single argument.
                /// </param>
                /// <param name="onError" type="Function" optional="true" locid="WinJS.Promise.thenEach_p:error">
                /// The function to be called if the promise is fulfilled with an error. The error
                /// is passed as the single argument.
                /// </param>
                /// <param name="onProgress" type="Function" optional="true" locid="WinJS.Promise.thenEach_p:progress">
                /// The function to be called if the promise reports progress. Data about the progress
                /// is passed as the single argument. Promises are not required to support
                /// progress.
                /// </param>
                /// <returns type="WinJS.Promise" locid="WinJS.Promise.thenEach_returnValue">
                /// A promise that is the result of calling Promise.join on the values parameter.
                /// </returns>
                /// </signature>
                var result = Array.isArray(values) ? [] : {};
                Object.keys(values).forEach(function (key) {
                    result[key] = Promise.as(values[key]).then(onComplete, onError, onProgress);
                });
                return Promise.join(result);
            },
            timeout: function Promise_timeout(time, promise) {
                /// <signature helpKeyword="WinJS.Promise.timeout">
                /// <summary locid="WinJS.Promise.timeout">
                /// Creates a promise that is fulfilled after a timeout.
                /// </summary>
                /// <param name="timeout" type="Number" optional="true" locid="WinJS.Promise.timeout_p:timeout">
                /// The timeout period in milliseconds. If this value is zero or not specified
                /// setImmediate is called, otherwise setTimeout is called.
                /// </param>
                /// <param name="promise" type="Promise" optional="true" locid="WinJS.Promise.timeout_p:promise">
                /// A promise that will be canceled if it doesn't complete before the
                /// timeout has expired.
                /// </param>
                /// <returns type="WinJS.Promise" locid="WinJS.Promise.timeout_returnValue">
                /// A promise that is completed asynchronously after the specified timeout.
                /// </returns>
                /// </signature>
                var to = timeout(time);
                return promise ? timeoutWithPromise(to, promise) : to;
            },
            wrap: function Promise_wrap(value) {
                /// <signature helpKeyword="WinJS.Promise.wrap">
                /// <summary locid="WinJS.Promise.wrap">
                /// Wraps a non-promise value in a promise. You can use this function if you need
                /// to pass a value to a function that requires a promise.
                /// </summary>
                /// <param name="value" locid="WinJS.Promise.wrap_p:value">
                /// Some non-promise value to be wrapped in a promise.
                /// </param>
                /// <returns type="WinJS.Promise" locid="WinJS.Promise.wrap_returnValue">
                /// A promise that is successfully fulfilled with the specified value
                /// </returns>
                /// </signature>
                return new CompletePromise(value);
            },
            wrapError: function Promise_wrapError(error) {
                /// <signature helpKeyword="WinJS.Promise.wrapError">
                /// <summary locid="WinJS.Promise.wrapError">
                /// Wraps a non-promise error value in a promise. You can use this function if you need
                /// to pass an error to a function that requires a promise.
                /// </summary>
                /// <param name="error" locid="WinJS.Promise.wrapError_p:error">
                /// A non-promise error value to be wrapped in a promise.
                /// </param>
                /// <returns type="WinJS.Promise" locid="WinJS.Promise.wrapError_returnValue">
                /// A promise that is in an error state with the specified value.
                /// </returns>
                /// </signature>
                return new ErrorPromise(error);
            },

            _veryExpensiveTagWithStack: {
                get: function () { return tagWithStack; },
                set: function (value) { tagWithStack = value; }
            },
            _veryExpensiveTagWithStack_tag: tag,
            _getStack: function () {
                if (_Global.Debug && _Global.Debug.debuggerEnabled) {
                    try { throw new Error(); } catch (e) { return e.stack; }
                }
            },

            _cancelBlocker: function Promise__cancelBlocker(input, oncancel) {
                //
                // Returns a promise which on cancelation will still result in downstream cancelation while
                //  protecting the promise 'input' from being  canceled which has the effect of allowing
                //  'input' to be shared amoung various consumers.
                //
                if (!Promise.is(input)) {
                    return Promise.wrap(input);
                }
                var complete;
                var error;
                var output = new Promise(
                    function (c, e) {
                        complete = c;
                        error = e;
                    },
                    function () {
                        complete = null;
                        error = null;
                        oncancel && oncancel();
                    }
                );
                input.then(
                    function (v) { complete && complete(v); },
                    function (e) { error && error(e); }
                );
                return output;
            },

        }
    );
    Object.defineProperties(Promise, _Events.createEventProperties(errorET));

    Promise._doneHandler = function (value) {
        _BaseCoreUtils._setImmediate(function Promise_done_rethrow() {
            throw value;
        });
    };

    return {
        PromiseStateMachine: PromiseStateMachine,
        Promise: Promise,
        state_created: state_created
    };
});

_winjs("WinJS/Promise", ["WinJS/Core/_Base","WinJS/Promise/_StateMachine"], function promiseInit( _Base, _StateMachine) {
    "use strict";

    _Base.Namespace.define("WinJS", {
        Promise: _StateMachine.Promise
    });

    return _StateMachine.Promise;
});

var exported = _modules["WinJS/Core/_WinJS"];

if (typeof exports === 'undefined' && typeof define === 'function' && define.amd) {
    define("vs/base/common/winjs.base.raw", exported);
} else {
    module.exports = exported;
}

if (typeof process !== 'undefined' && typeof process.nextTick === 'function') {
    _modules["WinJS/Core/_BaseCoreUtils"]._setImmediate = function(handler) {
        return process.nextTick(handler);
    };
}

})();
/*---------------------------------------------------------------------------------------------
 *  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/common/winjs.base*/], __M([551/*vs/base/common/winjs.base.raw*/]), function (winjs) {
	'use strict';
	return {
		Promise: winjs.Promise,
		TPromise: winjs.Promise,
		PPromise: winjs.Promise
	};
});

define(__m[10/*vs/base/common/errors*/], __M([1/*require*/,0/*exports*/,15/*vs/base/common/platform*/,29/*vs/base/common/types*/,7/*vs/base/common/winjs.base*/]), function (require, exports, platform, types, winjs_base_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    // ------ BEGIN Hook up error listeners to winjs promises
    var outstandingPromiseErrors = {};
    function promiseErrorHandler(e) {
        //
        // e.detail looks like: { exception, error, promise, handler, id, parent }
        //
        var details = e.detail;
        var id = details.id;
        // If the error has a parent promise then this is not the origination of the
        //  error so we check if it has a handler, and if so we mark that the error
        //  was handled by removing it from outstandingPromiseErrors
        //
        if (details.parent) {
            if (details.handler && outstandingPromiseErrors) {
                delete outstandingPromiseErrors[id];
            }
            return;
        }
        // Indicate that this error was originated and needs to be handled
        outstandingPromiseErrors[id] = details;
        // The first time the queue fills up this iteration, schedule a timeout to
        // check if any errors are still unhandled.
        if (Object.keys(outstandingPromiseErrors).length === 1) {
            setTimeout(function () {
                var errors = outstandingPromiseErrors;
                outstandingPromiseErrors = {};
                Object.keys(errors).forEach(function (errorId) {
                    var error = errors[errorId];
                    if (error.exception) {
                        onUnexpectedError(error.exception);
                    }
                    else if (error.error) {
                        onUnexpectedError(error.error);
                    }
                    console.log('WARNING: Promise with no error callback:' + error.id);
                    console.log(error);
                    if (error.exception) {
                        console.log(error.exception.stack);
                    }
                });
            }, 0);
        }
    }
    winjs_base_1.TPromise.addEventListener('error', promiseErrorHandler);
    // Avoid circular dependency on EventEmitter by implementing a subset of the interface.
    var ErrorHandler = (function () {
        function ErrorHandler() {
            this.listeners = [];
            this.unexpectedErrorHandler = function (e) {
                platform.setTimeout(function () {
                    if (e.stack) {
                        throw new Error(e.message + '\n\n' + e.stack);
                    }
                    throw e;
                }, 0);
            };
        }
        ErrorHandler.prototype.addListener = function (listener) {
            var _this = this;
            this.listeners.push(listener);
            return function () {
                _this._removeListener(listener);
            };
        };
        ErrorHandler.prototype.emit = function (e) {
            this.listeners.forEach(function (listener) {
                listener(e);
            });
        };
        ErrorHandler.prototype._removeListener = function (listener) {
            this.listeners.splice(this.listeners.indexOf(listener), 1);
        };
        ErrorHandler.prototype.setUnexpectedErrorHandler = function (newUnexpectedErrorHandler) {
            this.unexpectedErrorHandler = newUnexpectedErrorHandler;
        };
        ErrorHandler.prototype.getUnexpectedErrorHandler = function () {
            return this.unexpectedErrorHandler;
        };
        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 setUnexpectedErrorHandler(newUnexpectedErrorHandler) {
        exports.errorHandler.setUnexpectedErrorHandler(newUnexpectedErrorHandler);
    }
    exports.setUnexpectedErrorHandler = setUnexpectedErrorHandler;
    function onUnexpectedError(e) {
        // ignore errors from cancelled promises
        if (!isPromiseCanceledError(e)) {
            exports.errorHandler.onUnexpectedError(e);
        }
    }
    exports.onUnexpectedError = onUnexpectedError;
    function onUnexpectedExternalError(e) {
        // ignore errors from cancelled promises
        if (!isPromiseCanceledError(e)) {
            exports.errorHandler.onUnexpectedExternalError(e);
        }
    }
    exports.onUnexpectedExternalError = onUnexpectedExternalError;
    function onUnexpectedPromiseError(promise) {
        return promise.then(null, onUnexpectedError);
    }
    exports.onUnexpectedPromiseError = onUnexpectedPromiseError;
    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;
    /**
     * Returns an error that signals something is not implemented.
     */
    function notImplemented() {
        return new Error('Not Implemented');
    }
    exports.notImplemented = notImplemented;
    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;
    function readonly(name) {
        return name
            ? new Error("readonly property '" + name + " cannot be changed'")
            : new Error('readonly property cannot be changed');
    }
    exports.readonly = readonly;
    function create(message, options) {
        if (options === void 0) { options = {}; }
        var result = new Error(message);
        if (types.isNumber(options.severity)) {
            result.severity = options.severity;
        }
        if (options.actions) {
            result.actions = options.actions;
        }
        return result;
    }
    exports.create = create;
    function getErrorMessage(err) {
        if (!err) {
            return 'Error';
        }
        if (err.message) {
            return err.message;
        }
        if (err.stack) {
            return err.stack.split('\n')[0];
        }
        return String(err);
    }
    exports.getErrorMessage = getErrorMessage;
});

define(__m[424/*vs/base/common/callbackList*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/]), function (require, exports, errors_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CallbackList = (function () {
        function CallbackList() {
        }
        CallbackList.prototype.add = function (callback, context, bucket) {
            var _this = this;
            if (context === void 0) { context = null; }
            if (!this._callbacks) {
                this._callbacks = [];
                this._contexts = [];
            }
            this._callbacks.push(callback);
            this._contexts.push(context);
            if (Array.isArray(bucket)) {
                bucket.push({ dispose: function () { return _this.remove(callback, context); } });
            }
        };
        CallbackList.prototype.remove = function (callback, context) {
            if (context === void 0) { context = null; }
            if (!this._callbacks) {
                return;
            }
            var foundCallbackWithDifferentContext = false;
            for (var i = 0, len = this._callbacks.length; i < len; i++) {
                if (this._callbacks[i] === callback) {
                    if (this._contexts[i] === context) {
                        // callback & context match => remove it
                        this._callbacks.splice(i, 1);
                        this._contexts.splice(i, 1);
                        return;
                    }
                    else {
                        foundCallbackWithDifferentContext = true;
                    }
                }
            }
            if (foundCallbackWithDifferentContext) {
                throw new Error('When adding a listener with a context, you should remove it with the same context');
            }
        };
        CallbackList.prototype.invoke = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            if (!this._callbacks) {
                return undefined;
            }
            var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
            for (var i = 0, len = callbacks.length; i < len; i++) {
                try {
                    ret.push(callbacks[i].apply(contexts[i], args));
                }
                catch (e) {
                    errors_1.onUnexpectedError(e);
                }
            }
            return ret;
        };
        CallbackList.prototype.isEmpty = function () {
            return !this._callbacks || this._callbacks.length === 0;
        };
        CallbackList.prototype.entries = function () {
            var _this = this;
            if (!this._callbacks) {
                return [];
            }
            return this._callbacks.map(function (fn, index) { return [fn, _this._contexts[index]]; });
        };
        CallbackList.prototype.dispose = function () {
            this._callbacks = undefined;
            this._contexts = undefined;
        };
        return CallbackList;
    }());
    exports.default = CallbackList;
});

define(__m[11/*vs/base/common/event*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,424/*vs/base/common/callbackList*/,7/*vs/base/common/winjs.base*/,136/*vs/base/common/functional*/]), function (require, exports, lifecycle_1, callbackList_1, winjs_base_1, functional_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var Event;
    (function (Event) {
        var _disposable = { dispose: function () { } };
        Event.None = function () { return _disposable; };
    })(Event || (Event = {}));
    exports.default = Event;
    /**
     * 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 = (function () {
        function Emitter(_options) {
            this._options = _options;
        }
        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._callbacks) {
                            _this._callbacks = new callbackList_1.default();
                        }
                        var firstListener = _this._callbacks.isEmpty();
                        if (firstListener && _this._options && _this._options.onFirstListenerAdd) {
                            _this._options.onFirstListenerAdd(_this);
                        }
                        _this._callbacks.add(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);
                        }
                        var result;
                        result = {
                            dispose: function () {
                                result.dispose = Emitter._noop;
                                if (!_this._disposed) {
                                    _this._callbacks.remove(listener, thisArgs);
                                    if (_this._options && _this._options.onLastListenerRemove && _this._callbacks.isEmpty()) {
                                        _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._callbacks) {
                this._callbacks.invoke.call(this._callbacks, event);
            }
        };
        Emitter.prototype.dispose = function () {
            if (this._callbacks) {
                this._callbacks.dispose();
                this._callbacks = undefined;
                this._disposed = true;
            }
        };
        Emitter._noop = function () { };
        return Emitter;
    }());
    exports.Emitter = Emitter;
    var EventMultiplexer = (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) {
            e.listener.dispose();
            e.listener = null;
        };
        EventMultiplexer.prototype.dispose = function () {
            this.emitter.dispose();
        };
        return EventMultiplexer;
    }());
    exports.EventMultiplexer = EventMultiplexer;
    /**
     * Creates an Event which is backed-up by the event emitter. This allows
     * to use the existing eventing pattern and is likely using less memory.
     * Sample:
     *
     * 	class Document {
     *
     *		private _eventbus = new EventEmitter();
     *
     *		public onDidChange = fromEventEmitter(this._eventbus, 'changed');
     *
     *		// getter-style
     *		// get onDidChange(): Event<(value:string)=>any> {
     *		// 	cache fromEventEmitter result and return
     *		// }
     *
     *		private _doIt() {
     *			// ...
     *			this._eventbus.emit('changed', value)
     *		}
     *	}
     */
    function fromEventEmitter(emitter, eventType) {
        return function (listener, thisArgs, disposables) {
            var result = emitter.addListener(eventType, function () {
                listener.apply(thisArgs, arguments);
            });
            if (Array.isArray(disposables)) {
                disposables.push(result);
            }
            return result;
        };
    }
    exports.fromEventEmitter = fromEventEmitter;
    function fromCallback(fn) {
        var listener;
        var emitter = new Emitter({
            onFirstListenerAdd: function () { return listener = fn(function (e) { return emitter.fire(e); }); },
            onLastListenerRemove: function () { return listener.dispose(); }
        });
        return emitter.event;
    }
    exports.fromCallback = fromCallback;
    function fromPromise(promise) {
        var emitter = new Emitter();
        var shouldEmit = false;
        promise
            .then(null, function () { return null; })
            .then(function () {
            if (!shouldEmit) {
                setTimeout(function () { return emitter.fire(); }, 0);
            }
            else {
                emitter.fire();
            }
        });
        shouldEmit = true;
        return emitter.event;
    }
    exports.fromPromise = fromPromise;
    function toPromise(event) {
        return new winjs_base_1.TPromise(function (complete) {
            var sub = event(function (e) {
                sub.dispose();
                complete(e);
            });
        });
    }
    exports.toPromise = toPromise;
    function delayed(promise) {
        var toCancel = null;
        var listener = null;
        var emitter = new Emitter({
            onFirstListenerAdd: function () {
                toCancel = promise.then(function (event) { return listener = event(function (e) { return emitter.fire(e); }); }, function () { return null; });
            },
            onLastListenerRemove: function () {
                if (toCancel) {
                    toCancel.cancel();
                    toCancel = null;
                }
                if (listener) {
                    listener.dispose();
                    listener = null;
                }
            }
        });
        return emitter.event;
    }
    exports.delayed = delayed;
    function once(event) {
        return function (listener, thisArgs, disposables) {
            if (thisArgs === void 0) { thisArgs = null; }
            var result = event(function (e) {
                result.dispose();
                return listener.call(thisArgs, e);
            }, null, disposables);
            return result;
        };
    }
    exports.once = once;
    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); }));
        };
    }
    exports.any = any;
    function debounceEvent(event, merger, delay, leading) {
        if (delay === void 0) { delay = 100; }
        if (leading === void 0) { leading = false; }
        var subscription;
        var output;
        var handle;
        var numDebouncedCalls = 0;
        var emitter = new Emitter({
            onFirstListenerAdd: function () {
                subscription = event(function (cur) {
                    numDebouncedCalls++;
                    output = merger(output, cur);
                    if (!handle && leading) {
                        emitter.fire(output);
                    }
                    clearTimeout(handle);
                    handle = setTimeout(function () {
                        var _output = output;
                        output = undefined;
                        if (!leading || numDebouncedCalls > 1) {
                            emitter.fire(_output);
                        }
                        handle = null;
                        numDebouncedCalls = 0;
                    }, delay);
                });
            },
            onLastListenerRemove: function () {
                subscription.dispose();
            }
        });
        return emitter.event;
    }
    exports.debounceEvent = debounceEvent;
    /**
     * The EventDelayer 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 = (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);
                    }
                }, void 0, disposables);
            };
        };
        EventBufferer.prototype.bufferEvents = function (fn) {
            var buffer = [];
            this.buffers.push(buffer);
            fn();
            this.buffers.pop();
            buffer.forEach(function (flush) { return flush(); });
        };
        return EventBufferer;
    }());
    exports.EventBufferer = EventBufferer;
    function mapEvent(event, map) {
        return function (listener, thisArgs, disposables) {
            if (thisArgs === void 0) { thisArgs = null; }
            return event(function (i) { return listener.call(thisArgs, map(i)); }, null, disposables);
        };
    }
    exports.mapEvent = mapEvent;
    function filterEvent(event, filter) {
        return function (listener, thisArgs, disposables) {
            if (thisArgs === void 0) { thisArgs = null; }
            return event(function (e) { return filter(e) && listener.call(thisArgs, e); }, null, disposables);
        };
    }
    exports.filterEvent = filterEvent;
    var ChainableEvent = (function () {
        function ChainableEvent(_event) {
            this._event = _event;
        }
        Object.defineProperty(ChainableEvent.prototype, "event", {
            get: function () { return this._event; },
            enumerable: true,
            configurable: true
        });
        ChainableEvent.prototype.map = function (fn) {
            return new ChainableEvent(mapEvent(this._event, fn));
        };
        ChainableEvent.prototype.filter = function (fn) {
            return new ChainableEvent(filterEvent(this._event, fn));
        };
        ChainableEvent.prototype.on = function (listener, thisArgs, disposables) {
            return this._event(listener, thisArgs, disposables);
        };
        return ChainableEvent;
    }());
    function chain(event) {
        return new ChainableEvent(event);
    }
    exports.chain = chain;
    function stopwatch(event) {
        var start = new Date().getTime();
        return mapEvent(once(event), function (_) { return new Date().getTime() - start; });
    }
    exports.stopwatch = stopwatch;
    /**
     * 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<number>();
     * 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 = []; }
        buffer = buffer.slice();
        var listener = event(function (e) {
            if (buffer) {
                buffer.push(e);
            }
            else {
                emitter.fire(e);
            }
        });
        var flush = function () {
            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 () {
                listener.dispose();
                listener = null;
            }
        });
        return emitter.event;
    }
    exports.buffer = buffer;
    /**
     * Similar to `buffer` but it buffers indefinitely and repeats
     * the buffered events to every new listener.
     */
    function echo(event, nextTick, buffer) {
        if (nextTick === void 0) { nextTick = false; }
        if (buffer === void 0) { buffer = []; }
        buffer = buffer.slice();
        event(function (e) {
            buffer.push(e);
            emitter.fire(e);
        });
        var flush = function (listener, thisArgs) { return buffer.forEach(function (e) { return listener.call(thisArgs, e); }); };
        var emitter = new Emitter({
            onListenerDidAdd: function (emitter, listener, thisArgs) {
                if (nextTick) {
                    setTimeout(function () { return flush(listener, thisArgs); });
                }
                else {
                    flush(listener, thisArgs);
                }
            }
        });
        return emitter.event;
    }
    exports.echo = echo;
});

define(__m[28/*vs/base/browser/browser*/], __M([1/*require*/,0/*exports*/,15/*vs/base/common/platform*/,11/*vs/base/common/event*/]), function (require, exports, Platform, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var WindowManager = (function () {
        function WindowManager() {
            // --- Zoom Level
            this._zoomLevel = 0;
            this._lastZoomLevelChangeTime = 0;
            this._onDidChangeZoomLevel = new event_1.Emitter();
            this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;
            // --- Zoom Factor
            this._zoomFactor = 0;
            this._onDidChangeFullscreen = new event_1.Emitter();
            this.onDidChangeFullscreen = this._onDidChangeFullscreen.event;
            // --- Accessibility
            this._accessibilitySupport = 0 /* Unknown */;
            this._onDidChangeAccessibilitySupport = new event_1.Emitter();
            this.onDidChangeAccessibilitySupport = this._onDidChangeAccessibilitySupport.event;
        }
        WindowManager.prototype.getZoomLevel = function () {
            return this._zoomLevel;
        };
        WindowManager.prototype.getTimeSinceLastZoomLevelChanged = function () {
            return Date.now() - this._lastZoomLevelChangeTime;
        };
        WindowManager.prototype.setZoomLevel = function (zoomLevel, isTrusted) {
            if (this._zoomLevel === zoomLevel) {
                return;
            }
            this._zoomLevel = zoomLevel;
            // See https://github.com/Microsoft/vscode/issues/26151
            this._lastZoomLevelChangeTime = isTrusted ? 0 : Date.now();
            this._onDidChangeZoomLevel.fire(this._zoomLevel);
        };
        WindowManager.prototype.getZoomFactor = function () {
            return this._zoomFactor;
        };
        WindowManager.prototype.setZoomFactor = function (zoomFactor) {
            this._zoomFactor = zoomFactor;
        };
        // --- 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.prototype.setFullscreen = function (fullscreen) {
            if (this._fullscreen === fullscreen) {
                return;
            }
            this._fullscreen = fullscreen;
            this._onDidChangeFullscreen.fire();
        };
        WindowManager.prototype.isFullscreen = function () {
            return this._fullscreen;
        };
        WindowManager.prototype.setAccessibilitySupport = function (accessibilitySupport) {
            if (this._accessibilitySupport === accessibilitySupport) {
                return;
            }
            this._accessibilitySupport = accessibilitySupport;
            this._onDidChangeAccessibilitySupport.fire();
        };
        WindowManager.prototype.getAccessibilitySupport = function () {
            return this._accessibilitySupport;
        };
        WindowManager.INSTANCE = new WindowManager();
        return WindowManager;
    }());
    /** A zoom index, e.g. 1, 2, 3 */
    function setZoomLevel(zoomLevel, isTrusted) {
        WindowManager.INSTANCE.setZoomLevel(zoomLevel, isTrusted);
    }
    exports.setZoomLevel = setZoomLevel;
    function getZoomLevel() {
        return WindowManager.INSTANCE.getZoomLevel();
    }
    exports.getZoomLevel = getZoomLevel;
    /** Returns the time (in ms) since the zoom level was changed */
    function getTimeSinceLastZoomLevelChanged() {
        return WindowManager.INSTANCE.getTimeSinceLastZoomLevelChanged();
    }
    exports.getTimeSinceLastZoomLevelChanged = getTimeSinceLastZoomLevelChanged;
    function onDidChangeZoomLevel(callback) {
        return WindowManager.INSTANCE.onDidChangeZoomLevel(callback);
    }
    exports.onDidChangeZoomLevel = onDidChangeZoomLevel;
    /** The zoom scale for an index, e.g. 1, 1.2, 1.4 */
    function getZoomFactor() {
        return WindowManager.INSTANCE.getZoomFactor();
    }
    exports.getZoomFactor = getZoomFactor;
    function setZoomFactor(zoomFactor) {
        WindowManager.INSTANCE.setZoomFactor(zoomFactor);
    }
    exports.setZoomFactor = setZoomFactor;
    function getPixelRatio() {
        return WindowManager.INSTANCE.getPixelRatio();
    }
    exports.getPixelRatio = getPixelRatio;
    function setFullscreen(fullscreen) {
        WindowManager.INSTANCE.setFullscreen(fullscreen);
    }
    exports.setFullscreen = setFullscreen;
    function isFullscreen() {
        return WindowManager.INSTANCE.isFullscreen();
    }
    exports.isFullscreen = isFullscreen;
    function onDidChangeFullscreen(callback) {
        return WindowManager.INSTANCE.onDidChangeFullscreen(callback);
    }
    exports.onDidChangeFullscreen = onDidChangeFullscreen;
    function setAccessibilitySupport(accessibilitySupport) {
        WindowManager.INSTANCE.setAccessibilitySupport(accessibilitySupport);
    }
    exports.setAccessibilitySupport = setAccessibilitySupport;
    function getAccessibilitySupport() {
        return WindowManager.INSTANCE.getAccessibilitySupport();
    }
    exports.getAccessibilitySupport = getAccessibilitySupport;
    function onDidChangeAccessibilitySupport(callback) {
        return WindowManager.INSTANCE.onDidChangeAccessibilitySupport(callback);
    }
    exports.onDidChangeAccessibilitySupport = onDidChangeAccessibilitySupport;
    var userAgent = navigator.userAgent;
    exports.isIE = (userAgent.indexOf('Trident') >= 0);
    exports.isEdge = (userAgent.indexOf('Edge/') >= 0);
    exports.isEdgeOrIE = exports.isIE || exports.isEdge;
    exports.isOpera = (userAgent.indexOf('Opera') >= 0);
    exports.isFirefox = (userAgent.indexOf('Firefox') >= 0);
    exports.isWebKit = (userAgent.indexOf('AppleWebKit') >= 0);
    exports.isChrome = (userAgent.indexOf('Chrome') >= 0);
    exports.isSafari = (userAgent.indexOf('Chrome') === -1) && (userAgent.indexOf('Safari') >= 0);
    exports.isIPad = (userAgent.indexOf('iPad') >= 0);
    exports.isChromev56 = (userAgent.indexOf('Chrome/56.') >= 0
        && userAgent.indexOf('Edge/') === -1);
    exports.supportsTranslate3d = !exports.isFirefox;
    function canUseTranslate3d() {
        if (!exports.supportsTranslate3d) {
            return false;
        }
        if (getZoomLevel() !== 0) {
            return false;
        }
        // see https://github.com/Microsoft/vscode/issues/24483
        if (exports.isChromev56) {
            var pixelRatio = getPixelRatio();
            if (Math.floor(pixelRatio) !== pixelRatio) {
                // Not an integer
                return false;
            }
        }
        return true;
    }
    exports.canUseTranslate3d = canUseTranslate3d;
});

define(__m[124/*vs/base/browser/event*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/event*/]), function (require, exports, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.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.mapEvent(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[65/*vs/base/browser/keyboardEvent*/], __M([1/*require*/,0/*exports*/,40/*vs/base/common/keyCodes*/,15/*vs/base/common/platform*/,28/*vs/base/browser/browser*/]), function (require, exports, keyCodes_1, platform, browser) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var KEY_CODE_MAP = {};
    (function () {
        KEY_CODE_MAP[3] = 7 /* PauseBreak */; // VK_CANCEL 0x03 Control-break processing
        KEY_CODE_MAP[8] = 1 /* Backspace */;
        KEY_CODE_MAP[9] = 2 /* Tab */;
        KEY_CODE_MAP[13] = 3 /* Enter */;
        KEY_CODE_MAP[16] = 4 /* Shift */;
        KEY_CODE_MAP[17] = 5 /* Ctrl */;
        KEY_CODE_MAP[18] = 6 /* Alt */;
        KEY_CODE_MAP[19] = 7 /* PauseBreak */;
        KEY_CODE_MAP[20] = 8 /* CapsLock */;
        KEY_CODE_MAP[27] = 9 /* Escape */;
        KEY_CODE_MAP[32] = 10 /* Space */;
        KEY_CODE_MAP[33] = 11 /* PageUp */;
        KEY_CODE_MAP[34] = 12 /* PageDown */;
        KEY_CODE_MAP[35] = 13 /* End */;
        KEY_CODE_MAP[36] = 14 /* Home */;
        KEY_CODE_MAP[37] = 15 /* LeftArrow */;
        KEY_CODE_MAP[38] = 16 /* UpArrow */;
        KEY_CODE_MAP[39] = 17 /* RightArrow */;
        KEY_CODE_MAP[40] = 18 /* DownArrow */;
        KEY_CODE_MAP[45] = 19 /* Insert */;
        KEY_CODE_MAP[46] = 20 /* Delete */;
        KEY_CODE_MAP[48] = 21 /* KEY_0 */;
        KEY_CODE_MAP[49] = 22 /* KEY_1 */;
        KEY_CODE_MAP[50] = 23 /* KEY_2 */;
        KEY_CODE_MAP[51] = 24 /* KEY_3 */;
        KEY_CODE_MAP[52] = 25 /* KEY_4 */;
        KEY_CODE_MAP[53] = 26 /* KEY_5 */;
        KEY_CODE_MAP[54] = 27 /* KEY_6 */;
        KEY_CODE_MAP[55] = 28 /* KEY_7 */;
        KEY_CODE_MAP[56] = 29 /* KEY_8 */;
        KEY_CODE_MAP[57] = 30 /* KEY_9 */;
        KEY_CODE_MAP[65] = 31 /* KEY_A */;
        KEY_CODE_MAP[66] = 32 /* KEY_B */;
        KEY_CODE_MAP[67] = 33 /* KEY_C */;
        KEY_CODE_MAP[68] = 34 /* KEY_D */;
        KEY_CODE_MAP[69] = 35 /* KEY_E */;
        KEY_CODE_MAP[70] = 36 /* KEY_F */;
        KEY_CODE_MAP[71] = 37 /* KEY_G */;
        KEY_CODE_MAP[72] = 38 /* KEY_H */;
        KEY_CODE_MAP[73] = 39 /* KEY_I */;
        KEY_CODE_MAP[74] = 40 /* KEY_J */;
        KEY_CODE_MAP[75] = 41 /* KEY_K */;
        KEY_CODE_MAP[76] = 42 /* KEY_L */;
        KEY_CODE_MAP[77] = 43 /* KEY_M */;
        KEY_CODE_MAP[78] = 44 /* KEY_N */;
        KEY_CODE_MAP[79] = 45 /* KEY_O */;
        KEY_CODE_MAP[80] = 46 /* KEY_P */;
        KEY_CODE_MAP[81] = 47 /* KEY_Q */;
        KEY_CODE_MAP[82] = 48 /* KEY_R */;
        KEY_CODE_MAP[83] = 49 /* KEY_S */;
        KEY_CODE_MAP[84] = 50 /* KEY_T */;
        KEY_CODE_MAP[85] = 51 /* KEY_U */;
        KEY_CODE_MAP[86] = 52 /* KEY_V */;
        KEY_CODE_MAP[87] = 53 /* KEY_W */;
        KEY_CODE_MAP[88] = 54 /* KEY_X */;
        KEY_CODE_MAP[89] = 55 /* KEY_Y */;
        KEY_CODE_MAP[90] = 56 /* KEY_Z */;
        KEY_CODE_MAP[93] = 58 /* ContextMenu */;
        KEY_CODE_MAP[96] = 93 /* NUMPAD_0 */;
        KEY_CODE_MAP[97] = 94 /* NUMPAD_1 */;
        KEY_CODE_MAP[98] = 95 /* NUMPAD_2 */;
        KEY_CODE_MAP[99] = 96 /* NUMPAD_3 */;
        KEY_CODE_MAP[100] = 97 /* NUMPAD_4 */;
        KEY_CODE_MAP[101] = 98 /* NUMPAD_5 */;
        KEY_CODE_MAP[102] = 99 /* NUMPAD_6 */;
        KEY_CODE_MAP[103] = 100 /* NUMPAD_7 */;
        KEY_CODE_MAP[104] = 101 /* NUMPAD_8 */;
        KEY_CODE_MAP[105] = 102 /* NUMPAD_9 */;
        KEY_CODE_MAP[106] = 103 /* NUMPAD_MULTIPLY */;
        KEY_CODE_MAP[107] = 104 /* NUMPAD_ADD */;
        KEY_CODE_MAP[108] = 105 /* NUMPAD_SEPARATOR */;
        KEY_CODE_MAP[109] = 106 /* NUMPAD_SUBTRACT */;
        KEY_CODE_MAP[110] = 107 /* NUMPAD_DECIMAL */;
        KEY_CODE_MAP[111] = 108 /* NUMPAD_DIVIDE */;
        KEY_CODE_MAP[112] = 59 /* F1 */;
        KEY_CODE_MAP[113] = 60 /* F2 */;
        KEY_CODE_MAP[114] = 61 /* F3 */;
        KEY_CODE_MAP[115] = 62 /* F4 */;
        KEY_CODE_MAP[116] = 63 /* F5 */;
        KEY_CODE_MAP[117] = 64 /* F6 */;
        KEY_CODE_MAP[118] = 65 /* F7 */;
        KEY_CODE_MAP[119] = 66 /* F8 */;
        KEY_CODE_MAP[120] = 67 /* F9 */;
        KEY_CODE_MAP[121] = 68 /* F10 */;
        KEY_CODE_MAP[122] = 69 /* F11 */;
        KEY_CODE_MAP[123] = 70 /* F12 */;
        KEY_CODE_MAP[124] = 71 /* F13 */;
        KEY_CODE_MAP[125] = 72 /* F14 */;
        KEY_CODE_MAP[126] = 73 /* F15 */;
        KEY_CODE_MAP[127] = 74 /* F16 */;
        KEY_CODE_MAP[128] = 75 /* F17 */;
        KEY_CODE_MAP[129] = 76 /* F18 */;
        KEY_CODE_MAP[130] = 77 /* F19 */;
        KEY_CODE_MAP[144] = 78 /* NumLock */;
        KEY_CODE_MAP[145] = 79 /* ScrollLock */;
        KEY_CODE_MAP[186] = 80 /* US_SEMICOLON */;
        KEY_CODE_MAP[187] = 81 /* US_EQUAL */;
        KEY_CODE_MAP[188] = 82 /* US_COMMA */;
        KEY_CODE_MAP[189] = 83 /* US_MINUS */;
        KEY_CODE_MAP[190] = 84 /* US_DOT */;
        KEY_CODE_MAP[191] = 85 /* US_SLASH */;
        KEY_CODE_MAP[192] = 86 /* US_BACKTICK */;
        KEY_CODE_MAP[193] = 110 /* ABNT_C1 */;
        KEY_CODE_MAP[194] = 111 /* ABNT_C2 */;
        KEY_CODE_MAP[219] = 87 /* US_OPEN_SQUARE_BRACKET */;
        KEY_CODE_MAP[220] = 88 /* US_BACKSLASH */;
        KEY_CODE_MAP[221] = 89 /* US_CLOSE_SQUARE_BRACKET */;
        KEY_CODE_MAP[222] = 90 /* US_QUOTE */;
        KEY_CODE_MAP[223] = 91 /* OEM_8 */;
        KEY_CODE_MAP[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.
         */
        KEY_CODE_MAP[229] = 109 /* KEY_IN_COMPOSITION */;
        if (browser.isIE) {
            KEY_CODE_MAP[91] = 57 /* Meta */;
        }
        else if (browser.isFirefox) {
            KEY_CODE_MAP[59] = 80 /* US_SEMICOLON */;
            KEY_CODE_MAP[107] = 81 /* US_EQUAL */;
            KEY_CODE_MAP[109] = 83 /* US_MINUS */;
            if (platform.isMacintosh) {
                KEY_CODE_MAP[224] = 57 /* Meta */;
            }
        }
        else if (browser.isWebKit) {
            KEY_CODE_MAP[91] = 57 /* Meta */;
            if (platform.isMacintosh) {
                // the two meta keys in the Mac have different key codes (91 and 93)
                KEY_CODE_MAP[93] = 57 /* Meta */;
            }
            else {
                KEY_CODE_MAP[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 = (function () {
        function StandardKeyboardEvent(source) {
            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;
});











define(__m[47/*vs/base/browser/mouseEvent*/], __M([1/*require*/,0/*exports*/,15/*vs/base/common/platform*/,28/*vs/base/browser/browser*/,148/*vs/base/browser/iframe*/]), function (require, exports, platform, browser, iframe_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var StandardMouseEvent = (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 = (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 DropMouseEvent = (function (_super) {
        __extends(DropMouseEvent, _super);
        function DropMouseEvent(e) {
            return _super.call(this, e) || this;
        }
        return DropMouseEvent;
    }(DragMouseEvent));
    exports.DropMouseEvent = DropMouseEvent;
    var StandardMouseWheelEvent = (function () {
        function StandardMouseWheelEvent(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;
                }
            }
        }
        StandardMouseWheelEvent.prototype.preventDefault = function () {
            if (this.browserEvent) {
                if (this.browserEvent.preventDefault) {
                    this.browserEvent.preventDefault();
                }
            }
        };
        StandardMouseWheelEvent.prototype.stopPropagation = function () {
            if (this.browserEvent) {
                if (this.browserEvent.stopPropagation) {
                    this.browserEvent.stopPropagation();
                }
            }
        };
        return StandardMouseWheelEvent;
    }());
    exports.StandardMouseWheelEvent = StandardMouseWheelEvent;
});

/*---------------------------------------------------------------------------------------------
 *  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/cancellation*/], __M([1/*require*/,0/*exports*/,11/*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) {
        CancellationToken.None = Object.freeze({
            isCancellationRequested: false,
            onCancellationRequested: event_1.default.None
        });
        CancellationToken.Cancelled = Object.freeze({
            isCancellationRequested: true,
            onCancellationRequested: shortcutEvent
        });
    })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
    var MutableToken = (function () {
        function MutableToken() {
            this._isCancelled = false;
        }
        MutableToken.prototype.cancel = function () {
            if (!this._isCancelled) {
                this._isCancelled = true;
                if (this._emitter) {
                    this._emitter.fire(undefined);
                    this._emitter = undefined;
                }
            }
        };
        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
        });
        return MutableToken;
    }());
    var CancellationTokenSource = (function () {
        function CancellationTokenSource() {
        }
        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 {
                this._token.cancel();
            }
        };
        CancellationTokenSource.prototype.dispose = function () {
            this.cancel();
        };
        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[18/*vs/base/common/async*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,15/*vs/base/common/platform*/,7/*vs/base/common/winjs.base*/,123/*vs/base/common/cancellation*/,3/*vs/base/common/lifecycle*/,11/*vs/base/common/event*/]), function (require, exports, errors, platform, winjs_base_1, cancellation_1, lifecycle_1, event_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function isThenable(obj) {
        return obj && typeof obj.then === 'function';
    }
    function toThenable(arg) {
        if (isThenable(arg)) {
            return arg;
        }
        else {
            return winjs_base_1.TPromise.as(arg);
        }
    }
    exports.toThenable = toThenable;
    function asWinJsPromise(callback) {
        var source = new cancellation_1.CancellationTokenSource();
        return new winjs_base_1.TPromise(function (resolve, reject, progress) {
            var item = callback(source.token);
            if (item instanceof winjs_base_1.TPromise) {
                item.then(resolve, reject, progress);
            }
            else if (isThenable(item)) {
                item.then(resolve, reject);
            }
            else {
                resolve(item);
            }
        }, function () {
            source.cancel();
        });
    }
    exports.asWinJsPromise = asWinJsPromise;
    /**
     * Hook a cancellation token to a WinJS Promise
     */
    function wireCancellationToken(token, promise, resolveAsUndefinedWhenCancelled) {
        var subscription = token.onCancellationRequested(function () { return promise.cancel(); });
        if (resolveAsUndefinedWhenCancelled) {
            promise = promise.then(undefined, function (err) {
                if (!errors.isPromiseCanceledError(err)) {
                    return winjs_base_1.TPromise.wrapError(err);
                }
                return undefined;
            });
        }
        return always(promise, function () { return subscription.dispose(); });
    }
    exports.wireCancellationToken = wireCancellationToken;
    /**
     * A helper to prevent accumulation of sequential async tasks.
     *
     * Imagine a mail man with the sole task of delivering letters. As soon as
     * a letter submitted for delivery, he drives to the destination, delivers it
     * and returns to his base. Imagine that during the trip, N more letters were submitted.
     * When the mail man returns, he picks those N letters and delivers them all in a
     * single trip. Even though N+1 submissions occurred, only 2 deliveries were made.
     *
     * The throttler implements this via the queue() method, by providing it a task
     * factory. Following the example:
     *
     * 		const throttler = new Throttler();
     * 		const letters = [];
     *
     * 		function deliver() {
     * 			const lettersToDeliver = letters;
     * 			letters = [];
     * 			return makeTheTrip(lettersToDeliver);
     * 		}
     *
     * 		function onLetterReceived(l) {
     * 			letters.push(l);
     * 			throttler.queue(deliver);
     * 		}
     */
    var Throttler = (function () {
        function Throttler() {
            this.activePromise = null;
            this.queuedPromise = null;
            this.queuedPromiseFactory = null;
        }
        Throttler.prototype.queue = function (promiseFactory) {
            var _this = this;
            if (this.activePromise) {
                this.queuedPromiseFactory = promiseFactory;
                if (!this.queuedPromise) {
                    var onComplete_1 = function () {
                        _this.queuedPromise = null;
                        var result = _this.queue(_this.queuedPromiseFactory);
                        _this.queuedPromiseFactory = null;
                        return result;
                    };
                    this.queuedPromise = new winjs_base_1.TPromise(function (c, e, p) {
                        _this.activePromise.then(onComplete_1, onComplete_1, p).done(c);
                    }, function () {
                        _this.activePromise.cancel();
                    });
                }
                return new winjs_base_1.TPromise(function (c, e, p) {
                    _this.queuedPromise.then(c, e, p);
                }, function () {
                    // no-op
                });
            }
            this.activePromise = promiseFactory();
            return new winjs_base_1.TPromise(function (c, e, p) {
                _this.activePromise.done(function (result) {
                    _this.activePromise = null;
                    c(result);
                }, function (err) {
                    _this.activePromise = null;
                    e(err);
                }, p);
            }, function () {
                _this.activePromise.cancel();
            });
        };
        return Throttler;
    }());
    exports.Throttler = Throttler;
    // TODO@Joao: can the previous throttler be replaced with this?
    var SimpleThrottler = (function () {
        function SimpleThrottler() {
            this.current = winjs_base_1.TPromise.as(null);
        }
        SimpleThrottler.prototype.queue = function (promiseTask) {
            return this.current = this.current.then(function () { return promiseTask(); });
        };
        return SimpleThrottler;
    }());
    exports.SimpleThrottler = SimpleThrottler;
    /**
     * 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 the 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 = (function () {
        function Delayer(defaultDelay) {
            this.defaultDelay = defaultDelay;
            this.timeout = null;
            this.completionPromise = null;
            this.onSuccess = 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 winjs_base_1.TPromise(function (c) {
                    _this.onSuccess = c;
                }, function () {
                    // no-op
                }).then(function () {
                    _this.completionPromise = null;
                    _this.onSuccess = null;
                    var task = _this.task;
                    _this.task = null;
                    return task();
                });
            }
            this.timeout = setTimeout(function () {
                _this.timeout = null;
                _this.onSuccess(null);
            }, delay);
            return this.completionPromise;
        };
        Delayer.prototype.isTriggered = function () {
            return this.timeout !== null;
        };
        Delayer.prototype.cancel = function () {
            this.cancelTimeout();
            if (this.completionPromise) {
                this.completionPromise.cancel();
                this.completionPromise = null;
            }
        };
        Delayer.prototype.cancelTimeout = function () {
            if (this.timeout !== null) {
                clearTimeout(this.timeout);
                this.timeout = null;
            }
        };
        return Delayer;
    }());
    exports.Delayer = Delayer;
    /**
     * A helper to delay execution of a task that is being requested often, while
     * preventing accumulation of consecutive executions, while the task runs.
     *
     * Simply combine the two mail man strategies from the Throttler and Delayer
     * helpers, for an analogy.
     */
    var ThrottledDelayer = (function (_super) {
        __extends(ThrottledDelayer, _super);
        function ThrottledDelayer(defaultDelay) {
            var _this = _super.call(this, defaultDelay) || this;
            _this.throttler = new Throttler();
            return _this;
        }
        ThrottledDelayer.prototype.trigger = function (promiseFactory, delay) {
            var _this = this;
            return _super.prototype.trigger.call(this, function () { return _this.throttler.queue(promiseFactory); }, delay);
        };
        return ThrottledDelayer;
    }(Delayer));
    exports.ThrottledDelayer = ThrottledDelayer;
    /**
     * Similar to the ThrottledDelayer, except it also guarantees that the promise
     * factory doesn't get called more often than every `minimumPeriod` milliseconds.
     */
    var PeriodThrottledDelayer = (function (_super) {
        __extends(PeriodThrottledDelayer, _super);
        function PeriodThrottledDelayer(defaultDelay, minimumPeriod) {
            if (minimumPeriod === void 0) { minimumPeriod = 0; }
            var _this = _super.call(this, defaultDelay) || this;
            _this.minimumPeriod = minimumPeriod;
            _this.periodThrottler = new Throttler();
            return _this;
        }
        PeriodThrottledDelayer.prototype.trigger = function (promiseFactory, delay) {
            var _this = this;
            return _super.prototype.trigger.call(this, function () {
                return _this.periodThrottler.queue(function () {
                    return winjs_base_1.Promise.join([
                        winjs_base_1.TPromise.timeout(_this.minimumPeriod),
                        promiseFactory()
                    ]).then(function (r) { return r[1]; });
                });
            }, delay);
        };
        return PeriodThrottledDelayer;
    }(ThrottledDelayer));
    exports.PeriodThrottledDelayer = PeriodThrottledDelayer;
    var PromiseSource = (function () {
        function PromiseSource() {
            var _this = this;
            this._value = new winjs_base_1.TPromise(function (c, e) {
                _this._completeCallback = c;
                _this._errorCallback = e;
            });
        }
        Object.defineProperty(PromiseSource.prototype, "value", {
            get: function () {
                return this._value;
            },
            enumerable: true,
            configurable: true
        });
        PromiseSource.prototype.complete = function (value) {
            this._completeCallback(value);
        };
        PromiseSource.prototype.error = function (err) {
            this._errorCallback(err);
        };
        return PromiseSource;
    }());
    exports.PromiseSource = PromiseSource;
    var ShallowCancelThenPromise = (function (_super) {
        __extends(ShallowCancelThenPromise, _super);
        function ShallowCancelThenPromise(outer) {
            var _this = this;
            var completeCallback, errorCallback, progressCallback;
            _this = _super.call(this, function (c, e, p) {
                completeCallback = c;
                errorCallback = e;
                progressCallback = p;
            }, function () {
                // cancel this promise but not the
                // outer promise
                errorCallback(errors.canceled());
            }) || this;
            outer.then(completeCallback, errorCallback, progressCallback);
            return _this;
        }
        return ShallowCancelThenPromise;
    }(winjs_base_1.TPromise));
    exports.ShallowCancelThenPromise = ShallowCancelThenPromise;
    /**
     * Returns a new promise that joins the provided promise. Upon completion of
     * the provided promise the provided function will always be called. This
     * method is comparable to a try-finally code block.
     * @param promise a promise
     * @param f a function that will be call in the success and error case.
     */
    function always(promise, f) {
        return new winjs_base_1.TPromise(function (c, e, p) {
            promise.done(function (result) {
                try {
                    f(result);
                }
                catch (e1) {
                    errors.onUnexpectedError(e1);
                }
                c(result);
            }, function (err) {
                try {
                    f(err);
                }
                catch (e1) {
                    errors.onUnexpectedError(e1);
                }
                e(err);
            }, function (progress) {
                p(progress);
            });
        }, function () {
            promise.cancel();
        });
    }
    exports.always = always;
    /**
     * Runs the provided list of promise factories in sequential order. The returned
     * promise will complete to an array of results from each promise.
     */
    function sequence(promiseFactories) {
        var results = [];
        // reverse since we start with last element using pop()
        promiseFactories = promiseFactories.reverse();
        function next() {
            if (promiseFactories.length) {
                return promiseFactories.pop()();
            }
            return null;
        }
        function thenHandler(result) {
            if (result !== undefined && result !== null) {
                results.push(result);
            }
            var n = next();
            if (n) {
                return n.then(thenHandler);
            }
            return winjs_base_1.TPromise.as(results);
        }
        return winjs_base_1.TPromise.as(null).then(thenHandler);
    }
    exports.sequence = sequence;
    function first(promiseFactories, shouldStop) {
        if (shouldStop === void 0) { shouldStop = function (t) { return !!t; }; }
        promiseFactories = promiseFactories.reverse().slice();
        var loop = function () {
            if (promiseFactories.length === 0) {
                return winjs_base_1.TPromise.as(null);
            }
            var factory = promiseFactories.pop();
            var promise = factory();
            return promise.then(function (result) {
                if (shouldStop(result)) {
                    return winjs_base_1.TPromise.as(result);
                }
                return loop();
            });
        };
        return loop();
    }
    exports.first = first;
    /**
     * A helper to queue N promises and run them all with a max degree of parallelism. The helper
     * ensures that at any time no more than M promises are running at the same time.
     */
    var Limiter = (function () {
        function Limiter(maxDegreeOfParalellism) {
            this.maxDegreeOfParalellism = maxDegreeOfParalellism;
            this.outstandingPromises = [];
            this.runningPromises = 0;
            this._onFinished = new event_1.Emitter();
        }
        Object.defineProperty(Limiter.prototype, "onFinished", {
            get: function () {
                return this._onFinished.event;
            },
            enumerable: true,
            configurable: true
        });
        Limiter.prototype.queue = function (promiseFactory) {
            var _this = this;
            return new winjs_base_1.TPromise(function (c, e, p) {
                _this.outstandingPromises.push({
                    factory: promiseFactory,
                    c: c,
                    e: e,
                    p: p
                });
                _this.consume();
            });
        };
        Limiter.prototype.consume = function () {
            var _this = this;
            while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) {
                var iLimitedTask = this.outstandingPromises.shift();
                this.runningPromises++;
                var promise = iLimitedTask.factory();
                promise.done(iLimitedTask.c, iLimitedTask.e, iLimitedTask.p);
                promise.done(function () { return _this.consumed(); }, function () { return _this.consumed(); });
            }
        };
        Limiter.prototype.consumed = function () {
            this.runningPromises--;
            if (this.outstandingPromises.length > 0) {
                this.consume();
            }
            else {
                this._onFinished.fire();
            }
        };
        Limiter.prototype.dispose = function () {
            this._onFinished.dispose();
        };
        return Limiter;
    }());
    exports.Limiter = Limiter;
    /**
     * A queue is handles one promise at a time and guarantees that at any time only one promise is executing.
     */
    var Queue = (function (_super) {
        __extends(Queue, _super);
        function Queue() {
            return _super.call(this, 1) || this;
        }
        return Queue;
    }(Limiter));
    exports.Queue = Queue;
    function setDisposableTimeout(handler, timeout) {
        var args = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            args[_i - 2] = arguments[_i];
        }
        var handle = setTimeout.apply(void 0, [handler, timeout].concat(args));
        return { dispose: function () { clearTimeout(handle); } };
    }
    exports.setDisposableTimeout = setDisposableTimeout;
    var TimeoutTimer = (function (_super) {
        __extends(TimeoutTimer, _super);
        function TimeoutTimer() {
            var _this = _super.call(this) || this;
            _this._token = -1;
            return _this;
        }
        TimeoutTimer.prototype.dispose = function () {
            this.cancel();
            _super.prototype.dispose.call(this);
        };
        TimeoutTimer.prototype.cancel = function () {
            if (this._token !== -1) {
                platform.clearTimeout(this._token);
                this._token = -1;
            }
        };
        TimeoutTimer.prototype.cancelAndSet = function (runner, timeout) {
            var _this = this;
            this.cancel();
            this._token = platform.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 = platform.setTimeout(function () {
                _this._token = -1;
                runner();
            }, timeout);
        };
        return TimeoutTimer;
    }(lifecycle_1.Disposable));
    exports.TimeoutTimer = TimeoutTimer;
    var IntervalTimer = (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) {
                platform.clearInterval(this._token);
                this._token = -1;
            }
        };
        IntervalTimer.prototype.cancelAndSet = function (runner, interval) {
            this.cancel();
            this._token = platform.setInterval(function () {
                runner();
            }, interval);
        };
        return IntervalTimer;
    }(lifecycle_1.Disposable));
    exports.IntervalTimer = IntervalTimer;
    var RunOnceScheduler = (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()) {
                platform.clearTimeout(this.timeoutToken);
                this.timeoutToken = -1;
            }
        };
        /**
         * Replace runner. If there is a runner already scheduled, the new runner will be called.
         */
        RunOnceScheduler.prototype.setRunner = function (runner) {
            this.runner = runner;
        };
        /**
         * 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 = platform.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.runner();
            }
        };
        return RunOnceScheduler;
    }());
    exports.RunOnceScheduler = RunOnceScheduler;
    function nfcall(fn) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        return new winjs_base_1.TPromise(function (c, e) { return fn.apply(void 0, args.concat([function (err, result) { return err ? e(err) : c(result); }])); }, function () { return null; });
    }
    exports.nfcall = nfcall;
    function ninvoke(thisArg, fn) {
        var args = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            args[_i - 2] = arguments[_i];
        }
        return new winjs_base_1.TPromise(function (c, e) { return fn.call.apply(fn, [thisArg].concat(args, [function (err, result) { return err ? e(err) : c(result); }])); }, function () { return null; });
    }
    exports.ninvoke = ninvoke;
});











define(__m[38/*vs/base/common/eventEmitter*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/]), function (require, exports, Errors) {
    /*---------------------------------------------------------------------------------------------
     *  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 EmitterEvent = (function () {
        function EmitterEvent(eventType, data) {
            if (eventType === void 0) { eventType = null; }
            if (data === void 0) { data = null; }
            this.type = eventType;
            this.data = data;
        }
        return EmitterEvent;
    }());
    exports.EmitterEvent = EmitterEvent;
    var EventEmitter = (function () {
        function EventEmitter(allowedEventTypes) {
            if (allowedEventTypes === void 0) { allowedEventTypes = null; }
            this._listeners = {};
            this._bulkListeners = [];
            this._collectedEvents = [];
            this._deferredCnt = 0;
            if (allowedEventTypes) {
                this._allowedEventTypes = {};
                for (var i = 0; i < allowedEventTypes.length; i++) {
                    this._allowedEventTypes[allowedEventTypes[i]] = true;
                }
            }
            else {
                this._allowedEventTypes = null;
            }
        }
        EventEmitter.prototype.dispose = function () {
            this._listeners = {};
            this._bulkListeners = [];
            this._collectedEvents = [];
            this._deferredCnt = 0;
            this._allowedEventTypes = null;
        };
        EventEmitter.prototype.addListener = function (eventType, listener) {
            if (eventType === '*') {
                throw new Error('Use addBulkListener(listener) to register your listener!');
            }
            if (this._allowedEventTypes && !this._allowedEventTypes.hasOwnProperty(eventType)) {
                throw new Error('This object will never emit this event type!');
            }
            if (this._listeners.hasOwnProperty(eventType)) {
                this._listeners[eventType].push(listener);
            }
            else {
                this._listeners[eventType] = [listener];
            }
            var bound = this;
            return {
                dispose: function () {
                    if (!bound) {
                        // Already called
                        return;
                    }
                    bound._removeListener(eventType, listener);
                    // Prevent leakers from holding on to the event emitter
                    bound = null;
                    listener = null;
                }
            };
        };
        EventEmitter.prototype.addOneTimeListener = function (eventType, listener) {
            var disposable = this.addListener(eventType, function (value) {
                disposable.dispose();
                listener(value);
            });
            return disposable;
        };
        EventEmitter.prototype.addBulkListener = function (listener) {
            var _this = this;
            this._bulkListeners.push(listener);
            return {
                dispose: function () {
                    _this._removeBulkListener(listener);
                }
            };
        };
        EventEmitter.prototype.addEmitter = function (eventEmitter) {
            var _this = this;
            return eventEmitter.addBulkListener(function (events) {
                if (_this._deferredCnt === 0) {
                    _this._emitEvents(events);
                }
                else {
                    // Collect for later
                    _this._collectedEvents.push.apply(_this._collectedEvents, events);
                }
            });
        };
        EventEmitter.prototype._removeListener = function (eventType, listener) {
            if (this._listeners.hasOwnProperty(eventType)) {
                var listeners = this._listeners[eventType];
                for (var i = 0, len = listeners.length; i < len; i++) {
                    if (listeners[i] === listener) {
                        listeners.splice(i, 1);
                        break;
                    }
                }
            }
        };
        EventEmitter.prototype._removeBulkListener = function (listener) {
            for (var i = 0, len = this._bulkListeners.length; i < len; i++) {
                if (this._bulkListeners[i] === listener) {
                    this._bulkListeners.splice(i, 1);
                    break;
                }
            }
        };
        EventEmitter.prototype._emitToSpecificTypeListeners = function (eventType, data) {
            if (this._listeners.hasOwnProperty(eventType)) {
                var listeners = this._listeners[eventType].slice(0);
                for (var i = 0, len = listeners.length; i < len; i++) {
                    safeInvoke1Arg(listeners[i], data);
                }
            }
        };
        EventEmitter.prototype._emitToBulkListeners = function (events) {
            var bulkListeners = this._bulkListeners.slice(0);
            for (var i = 0, len = bulkListeners.length; i < len; i++) {
                safeInvoke1Arg(bulkListeners[i], events);
            }
        };
        EventEmitter.prototype._emitEvents = function (events) {
            if (this._bulkListeners.length > 0) {
                this._emitToBulkListeners(events);
            }
            for (var i = 0, len = events.length; i < len; i++) {
                var e = events[i];
                this._emitToSpecificTypeListeners(e.type, e.data);
            }
        };
        EventEmitter.prototype.emit = function (eventType, data) {
            if (data === void 0) { data = {}; }
            if (this._allowedEventTypes && !this._allowedEventTypes.hasOwnProperty(eventType)) {
                throw new Error('Cannot emit this event type because it wasn\'t listed!');
            }
            // Early return if no listeners would get this
            if (!this._listeners.hasOwnProperty(eventType) && this._bulkListeners.length === 0) {
                return;
            }
            var emitterEvent = new EmitterEvent(eventType, data);
            if (this._deferredCnt === 0) {
                this._emitEvents([emitterEvent]);
            }
            else {
                // Collect for later
                this._collectedEvents.push(emitterEvent);
            }
        };
        EventEmitter.prototype.beginDeferredEmit = function () {
            this._deferredCnt = this._deferredCnt + 1;
        };
        EventEmitter.prototype.endDeferredEmit = function () {
            this._deferredCnt = this._deferredCnt - 1;
            if (this._deferredCnt === 0) {
                this._emitCollected();
            }
        };
        EventEmitter.prototype.deferredEmit = function (callback) {
            this.beginDeferredEmit();
            var result = safeInvokeNoArg(callback);
            this.endDeferredEmit();
            return result;
        };
        EventEmitter.prototype._emitCollected = function () {
            if (this._collectedEvents.length === 0) {
                return;
            }
            // Flush collected events
            var events = this._collectedEvents;
            this._collectedEvents = [];
            this._emitEvents(events);
        };
        return EventEmitter;
    }());
    exports.EventEmitter = EventEmitter;
    var EmitQueueElement = (function () {
        function EmitQueueElement(target, arg) {
            this.target = target;
            this.arg = arg;
        }
        return EmitQueueElement;
    }());
    /**
     * Same as EventEmitter, but guarantees events are delivered in order to each listener
     */
    var OrderGuaranteeEventEmitter = (function (_super) {
        __extends(OrderGuaranteeEventEmitter, _super);
        function OrderGuaranteeEventEmitter() {
            var _this = _super.call(this, null) || this;
            _this._emitQueue = [];
            return _this;
        }
        OrderGuaranteeEventEmitter.prototype._emitToSpecificTypeListeners = function (eventType, data) {
            if (this._listeners.hasOwnProperty(eventType)) {
                var listeners = this._listeners[eventType];
                for (var i = 0, len = listeners.length; i < len; i++) {
                    this._emitQueue.push(new EmitQueueElement(listeners[i], data));
                }
            }
        };
        OrderGuaranteeEventEmitter.prototype._emitToBulkListeners = function (events) {
            var bulkListeners = this._bulkListeners;
            for (var i = 0, len = bulkListeners.length; i < len; i++) {
                this._emitQueue.push(new EmitQueueElement(bulkListeners[i], events));
            }
        };
        OrderGuaranteeEventEmitter.prototype._emitEvents = function (events) {
            _super.prototype._emitEvents.call(this, events);
            while (this._emitQueue.length > 0) {
                var queueElement = this._emitQueue.shift();
                safeInvoke1Arg(queueElement.target, queueElement.arg);
            }
        };
        return OrderGuaranteeEventEmitter;
    }(EventEmitter));
    exports.OrderGuaranteeEventEmitter = OrderGuaranteeEventEmitter;
    function safeInvokeNoArg(func) {
        try {
            return func();
        }
        catch (e) {
            Errors.onUnexpectedError(e);
        }
        return undefined;
    }
    function safeInvoke1Arg(func, arg1) {
        try {
            return func(arg1);
        }
        catch (e) {
            Errors.onUnexpectedError(e);
        }
    }
});











define(__m[4/*vs/base/browser/dom*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,18/*vs/base/common/async*/,10/*vs/base/common/errors*/,38/*vs/base/common/eventEmitter*/,3/*vs/base/common/lifecycle*/,29/*vs/base/common/types*/,28/*vs/base/browser/browser*/,65/*vs/base/browser/keyboardEvent*/,47/*vs/base/browser/mouseEvent*/]), function (require, exports, winjs_base_1, async_1, errors_1, eventEmitter_1, lifecycle_1, types_1, browser, keyboardEvent_1, mouseEvent_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function clearNode(node) {
        while (node.firstChild) {
            node.removeChild(node.firstChild);
        }
    }
    exports.clearNode = clearNode;
    /**
     * Calls JSON.Stringify with a replacer to break apart any circular references.
     * This prevents JSON.stringify from throwing the exception
     *  "Uncaught TypeError: Converting circular structure to JSON"
     */
    function safeStringifyDOMAware(obj) {
        var seen = [];
        return JSON.stringify(obj, function (key, value) {
            // HTML elements are never going to serialize nicely
            if (value instanceof Element) {
                return '[Element]';
            }
            if (types_1.isObject(value) || Array.isArray(value)) {
                if (seen.indexOf(value) !== -1) {
                    return '[Circular]';
                }
                else {
                    seen.push(value);
                }
            }
            return value;
        });
    }
    exports.safeStringifyDOMAware = safeStringifyDOMAware;
    function isInDOM(node) {
        while (node) {
            if (node === document.body) {
                return true;
            }
            node = node.parentNode;
        }
        return false;
    }
    exports.isInDOM = isInDOM;
    var _manualClassList = new (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.addClass = function (node, className) {
            if (!node.className) {
                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.toggleClass = function (node, className, shouldHaveIt) {
            this._findClassName(node, className);
            if (this._lastStart !== -1 && (shouldHaveIt === void 0 || !shouldHaveIt)) {
                this.removeClass(node, className);
            }
            if (this._lastStart === -1 && (shouldHaveIt === void 0 || shouldHaveIt)) {
                this.addClass(node, className);
            }
        };
        return class_1;
    }());
    var _nativeClassList = new (function () {
        function class_2() {
        }
        class_2.prototype.hasClass = function (node, className) {
            return className && node.classList && node.classList.contains(className);
        };
        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.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.removeClass = _classList.removeClass.bind(_classList);
    exports.toggleClass = _classList.toggleClass.bind(_classList);
    var DomListener = (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.toElement);
            while (toElement && toElement !== node) {
                toElement = toElement.parentNode;
            }
            if (toElement === node) {
                return;
            }
            handler(e);
        });
    }
    exports.addDisposableNonBubblingMouseOutListener = addDisposableNonBubblingMouseOutListener;
    var _animationFrame = (function () {
        var emulatedRequestAnimationFrame = function (callback) {
            return setTimeout(function () { return callback(new Date().getTime()); }, 0);
        };
        var nativeRequestAnimationFrame = self.requestAnimationFrame
            || self.msRequestAnimationFrame
            || self.webkitRequestAnimationFrame
            || self.mozRequestAnimationFrame
            || self.oRequestAnimationFrame;
        var emulatedCancelAnimationFrame = function (id) { };
        var nativeCancelAnimationFrame = self.cancelAnimationFrame || self.cancelRequestAnimationFrame
            || self.msCancelAnimationFrame || self.msCancelRequestAnimationFrame
            || self.webkitCancelAnimationFrame || self.webkitCancelRequestAnimationFrame
            || self.mozCancelAnimationFrame || self.mozCancelRequestAnimationFrame
            || self.oCancelAnimationFrame || self.oCancelRequestAnimationFrame;
        var isNative = !!nativeRequestAnimationFrame;
        var request = nativeRequestAnimationFrame || emulatedRequestAnimationFrame;
        var cancel = nativeCancelAnimationFrame || emulatedCancelAnimationFrame;
        return {
            isNative: isNative,
            request: function (callback) {
                return request(callback);
            },
            cancel: function (id) {
                return cancel(id);
            }
        };
    })();
    var AnimationFrameQueueItem = (function () {
        function AnimationFrameQueueItem(runner, priority) {
            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;
                _animationFrame.request(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 = (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;
    // Adapted from WinJS
    // Converts a CSS positioning string for the specified element to pixels.
    var convertToPixels = (function () {
        return function (element, value) {
            return parseFloat(value) || 0;
        };
    })();
    function getDimension(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 convertToPixels(element, value);
    }
    var sizeUtils = {
        getBorderLeftWidth: function (element) {
            return getDimension(element, 'border-left-width', 'borderLeftWidth');
        },
        getBorderTopWidth: function (element) {
            return getDimension(element, 'border-top-width', 'borderTopWidth');
        },
        getBorderRightWidth: function (element) {
            return getDimension(element, 'border-right-width', 'borderRightWidth');
        },
        getBorderBottomWidth: function (element) {
            return getDimension(element, 'border-bottom-width', 'borderBottomWidth');
        },
        getPaddingLeft: function (element) {
            return getDimension(element, 'padding-left', 'paddingLeft');
        },
        getPaddingTop: function (element) {
            return getDimension(element, 'padding-top', 'paddingTop');
        },
        getPaddingRight: function (element) {
            return getDimension(element, 'padding-right', 'paddingRight');
        },
        getPaddingBottom: function (element) {
            return getDimension(element, 'padding-bottom', 'paddingBottom');
        },
        getMarginLeft: function (element) {
            return getDimension(element, 'margin-left', 'marginLeft');
        },
        getMarginTop: function (element) {
            return getDimension(element, 'margin-top', 'marginTop');
        },
        getMarginRight: function (element) {
            return getDimension(element, 'margin-right', 'marginRight');
        },
        getMarginBottom: function (element) {
            return getDimension(element, 'margin-bottom', 'marginBottom');
        },
        __commaSentinel: false
    };
    // ----------------------------------------------------------------------------------------
    // Position & 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 (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 content of the specified element. The content width does not include borders or padding.
    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 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 getTotalScrollWidth(element) {
        var margin = sizeUtils.getMarginLeft(element) + sizeUtils.getMarginRight(element);
        return element.scrollWidth + margin;
    }
    exports.getTotalScrollWidth = getTotalScrollWidth;
    // 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;
    // Gets the left coordinate of the specified element relative to the specified parent.
    function getRelativeLeft(element, parent) {
        if (element === null) {
            return 0;
        }
        var elementPosition = getTopLeftOffset(element);
        var parentPosition = getTopLeftOffset(parent);
        return elementPosition.left - parentPosition.left;
    }
    function getLargestChildWidth(parent, children) {
        var childWidths = children.map(function (child) {
            return Math.max(getTotalScrollWidth(child), getTotalWidth(child)) + getRelativeLeft(child, parent) || 0;
        });
        var maxWidth = Math.max.apply(Math, childWidths);
        return maxWidth;
    }
    exports.getLargestChildWidth = getLargestChildWidth;
    // ----------------------------------------------------------------------------------------
    function isAncestor(testChild, testAncestor) {
        while (testChild) {
            if (testChild === testAncestor) {
                return true;
            }
            testChild = testChild.parentNode;
        }
        return false;
    }
    exports.isAncestor = isAncestor;
    function findParentWithClass(node, clazz, stopAtClazz) {
        while (node) {
            if (exports.hasClass(node, clazz)) {
                return node;
            }
            if (stopAtClazz && exports.hasClass(node, stopAtClazz)) {
                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 sharedStyle = createStyleSheet();
    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 = sharedStyle; }
        if (!style || !cssText) {
            return;
        }
        style.sheet.insertRule(selector + '{' + cssText + '}', 0);
    }
    exports.createCSSRule = createCSSRule;
    function getCSSRule(selector, style) {
        if (style === void 0) { style = sharedStyle; }
        if (!style) {
            return null;
        }
        var rules = getDynamicStyleSheetRules(style);
        for (var i = 0; i < rules.length; i++) {
            var rule = rules[i];
            var normalizedSelectorText = rule.selectorText.replace(/::/gi, ':');
            if (normalizedSelectorText === selector) {
                return rule;
            }
        }
        return null;
    }
    exports.getCSSRule = getCSSRule;
    function removeCSSRulesContainingSelector(ruleName, style) {
        if (style === void 0) { style = sharedStyle; }
        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',
        AUXCLICK: 'auxclick',
        DBLCLICK: 'dblclick',
        MOUSE_UP: 'mouseup',
        MOUSE_DOWN: 'mousedown',
        MOUSE_OVER: 'mouseover',
        MOUSE_MOVE: 'mousemove',
        MOUSE_OUT: 'mouseout',
        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',
        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 = (function (_super) {
        __extends(FocusTracker, _super);
        function FocusTracker(element) {
            var _this = _super.call(this) || this;
            var hasFocus = false;
            var loosingFocus = false;
            _this._eventEmitter = _this._register(new eventEmitter_1.EventEmitter());
            var onFocus = function (event) {
                loosingFocus = false;
                if (!hasFocus) {
                    hasFocus = true;
                    _this._eventEmitter.emit('focus', {});
                }
            };
            var onBlur = function (event) {
                if (hasFocus) {
                    loosingFocus = true;
                    window.setTimeout(function () {
                        if (loosingFocus) {
                            loosingFocus = false;
                            hasFocus = false;
                            _this._eventEmitter.emit('blur', {});
                        }
                    }, 0);
                }
            };
            _this._register(addDisposableListener(element, exports.EventType.FOCUS, onFocus, true));
            _this._register(addDisposableListener(element, exports.EventType.BLUR, onBlur, true));
            return _this;
        }
        FocusTracker.prototype.addFocusListener = function (fn) {
            return this._eventEmitter.addListener('focus', fn);
        };
        FocusTracker.prototype.addBlurListener = function (fn) {
            return this._eventEmitter.addListener('blur', fn);
        };
        return FocusTracker;
    }(lifecycle_1.Disposable));
    function trackFocus(element) {
        return new FocusTracker(element);
    }
    exports.trackFocus = trackFocus;
    function append(parent) {
        var children = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            children[_i - 1] = arguments[_i];
        }
        children.forEach(function (child) { return parent.appendChild(child); });
        return children[children.length - 1];
    }
    exports.append = append;
    function prepend(parent, child) {
        parent.insertBefore(child, parent.firstChild);
        return child;
    }
    exports.prepend = prepend;
    var SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((.([\w\-]+))*)/;
    // Similar to builder, but much more lightweight
    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();
        }
        Object.keys(attrs || {}).forEach(function (name) {
            if (/^on\w+$/.test(name)) {
                result[name] = attrs[name];
            }
            else if (name === 'selected') {
                var value = attrs[name];
                if (value) {
                    result.setAttribute(name, 'true');
                }
            }
            else {
                result.setAttribute(name, attrs[name]);
            }
        });
        children
            .filter(function (child) { return !!child; })
            .forEach(function (child) {
            if (child instanceof Node) {
                result.appendChild(child);
            }
            else {
                result.appendChild(document.createTextNode(child));
            }
        });
        return result;
    }
    exports.$ = $;
    function join(nodes, separator) {
        var result = [];
        nodes.forEach(function (node, index) {
            if (index > 0) {
                if (separator instanceof Node) {
                    result.push(separator.cloneNode());
                }
                else {
                    result.push(document.createTextNode(separator));
                }
            }
            result.push(node);
        });
        return result;
    }
    exports.join = join;
    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 = '';
        }
    }
    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';
        }
    }
    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 <body> 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;
    function finalHandler(fn) {
        return function (e) {
            e.preventDefault();
            e.stopPropagation();
            fn(e);
        };
    }
    exports.finalHandler = finalHandler;
    function domContentLoaded() {
        return new winjs_base_1.TPromise(function (c, e) {
            var readyState = document.readyState;
            if (readyState === 'complete' || (document && document.body !== null)) {
                window.setImmediate(c);
            }
            else {
                window.addEventListener('DOMContentLoaded', c, false);
            }
        });
    }
    exports.domContentLoaded = domContentLoaded;
    /**
     * 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;
});

define(__m[27/*vs/base/browser/fastDomNode*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/]), function (require, exports, dom) {
    /*---------------------------------------------------------------------------------------------
     *  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 FastDomNode = (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.unsetWidth = function () {
            if (this._width === -1) {
                return;
            }
            this._width = -1;
            this.domNode.style.width = '';
        };
        FastDomNode.prototype.setHeight = function (height) {
            if (this._height === height) {
                return;
            }
            this._height = height;
            this.domNode.style.height = this._height + 'px';
        };
        FastDomNode.prototype.unsetHeight = function () {
            if (this._height === -1) {
                return;
            }
            this._height = -1;
            this.domNode.style.height = '';
        };
        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.addClassName = function (className) {
            dom.addClass(this.domNode, className);
            this._className = this.domNode.className;
        };
        FastDomNode.prototype.removeClassName = function (className) {
            dom.removeClass(this.domNode, className);
            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.getAttribute = function (name) {
            return this.domNode.getAttribute(name);
        };
        FastDomNode.prototype.removeAttribute = function (name) {
            this.domNode.removeAttribute(name);
        };
        FastDomNode.prototype.hasAttribute = function (name) {
            return this.domNode.hasAttribute(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;
});











define(__m[83/*vs/base/browser/globalMouseMoveMonitor*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,4/*vs/base/browser/dom*/,148/*vs/base/browser/iframe*/,47/*vs/base/browser/mouseEvent*/]), function (require, exports, lifecycle_1, dom, iframe_1, mouseEvent_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    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 = (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();
            }
        };
        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; i < windowChain.length; i++) {
                this.hooks.push(dom.addDisposableThrottledListener(windowChain[i].window.document, 'mousemove', function (data) { return _this.mouseMoveCallback(data); }, function (lastEvent, currentEvent) { return _this.mouseMoveEventMerger(lastEvent, currentEvent); }));
                this.hooks.push(dom.addDisposableListener(windowChain[i].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.
 *--------------------------------------------------------------------------------------------*/
define(__m[102/*vs/base/browser/htmlContentRenderer*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,108/*vs/base/common/idGenerator*/,9/*vs/base/common/strings*/,7/*vs/base/common/winjs.base*/,133/*vs/base/common/htmlContent*/,209/*vs/base/common/marked/marked*/]), function (require, exports, DOM, idGenerator_1, strings_1, winjs_base_1, htmlContent_1, marked_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 renderMarkedString(markedString, options) {
        if (options === void 0) { options = {}; }
        // this is sort of legacy given that we have full
        // support for markdown. Turn this into markdown
        // and continue
        var markdown;
        if (typeof markedString === 'string') {
            markdown = markedString;
        }
        else {
            markdown = '```' + markedString.language + '\n' + markedString.value + '\n```';
        }
        return renderMarkdown(markdown, options);
    }
    exports.renderMarkedString = renderMarkedString;
    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.actionCallback);
        return element;
    }
    exports.renderFormattedText = renderFormattedText;
    /**
     * Create html nodes for the given content element.
     *
     * @param content a html element description
     * @param actionCallback a callback function for any action links in the string. Argument is the zero-based index of the clicked action.
     */
    function renderMarkdown(markdown, options) {
        if (options === void 0) { options = {}; }
        var element = createElement(options);
        var codeBlockRenderer = options.codeBlockRenderer, actionCallback = options.actionCallback;
        // signal to code-block render that the
        // element has been created
        var signalInnerHTML;
        var withInnerHTML = new winjs_base_1.TPromise(function (c) { return signalInnerHTML = c; });
        var renderer = new marked_1.marked.Renderer();
        renderer.image = function (href, title, text) {
            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 '<img ' + attributes.join(' ') + '>';
        };
        renderer.link = function (href, title, text) {
            // Remove markdown escapes. Workaround for https://github.com/chjj/marked/issues/829
            if (href === text) {
                text = htmlContent_1.removeMarkdownEscapes(text);
            }
            title = htmlContent_1.removeMarkdownEscapes(title);
            href = htmlContent_1.removeMarkdownEscapes(href);
            if (!href || href.match(/^data:|javascript:/i)) {
                return text;
            }
            return "<a href=\"#\" data-href=\"" + href + "\" title=\"" + (title || text) + "\">" + text + "</a>";
        };
        renderer.paragraph = function (text) {
            return "<p>" + text + "</p>";
        };
        if (options.codeBlockRenderer) {
            renderer.code = function (code, lang) {
                var value = options.codeBlockRenderer(lang, code);
                if (typeof value === 'string') {
                    return value;
                }
                if (winjs_base_1.TPromise.is(value)) {
                    // when code-block rendering is async we return sync
                    // but update the node with the real result later.
                    var id_1 = idGenerator_1.defaultGenerator.nextId();
                    winjs_base_1.TPromise.join([value, withInnerHTML]).done(function (values) {
                        var strValue = values[0];
                        var span = element.querySelector("div[data-code=\"" + id_1 + "\"]");
                        if (span) {
                            span.innerHTML = strValue;
                        }
                    }, function (err) {
                        // ignore
                    });
                    return "<div class=\"code\" data-code=\"" + id_1 + "\">" + strings_1.escape(code) + "</div>";
                }
                return code;
            };
        }
        if (options.actionCallback) {
            DOM.addStandardDisposableListener(element, 'click', function (event) {
                if (event.target.tagName === 'A') {
                    var href = event.target.dataset['href'];
                    if (href) {
                        options.actionCallback(href, event);
                    }
                }
            });
        }
        element.innerHTML = marked_1.marked(markdown, {
            sanitize: true,
            renderer: renderer
        });
        signalInnerHTML();
        return element;
    }
    exports.renderMarkdown = renderMarkdown;
    // --- formatted string parsing
    var StringStream = (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;
    }());
    var FormatType;
    (function (FormatType) {
        FormatType[FormatType["Invalid"] = 0] = "Invalid";
        FormatType[FormatType["Root"] = 1] = "Root";
        FormatType[FormatType["Text"] = 2] = "Text";
        FormatType[FormatType["Bold"] = 3] = "Bold";
        FormatType[FormatType["Italics"] = 4] = "Italics";
        FormatType[FormatType["Action"] = 5] = "Action";
        FormatType[FormatType["ActionClose"] = 6] = "ActionClose";
        FormatType[FormatType["NewLine"] = 7] = "NewLine";
    })(FormatType || (FormatType = {}));
    function _renderFormattedText(element, treeNode, actionCallback) {
        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 */) {
            var a = document.createElement('a');
            a.href = '#';
            DOM.addStandardDisposableListener(a, 'click', function (event) {
                actionCallback(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 (element !== child) {
            element.appendChild(child);
        }
        if (Array.isArray(treeNode.children)) {
            treeNode.children.forEach(function (nodeChild) {
                _renderFormattedText(child, nodeChild, actionCallback);
            });
        }
    }
    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 */;
        }
    }
});

define(__m[74/*vs/base/browser/touch*/], __M([1/*require*/,0/*exports*/,33/*vs/base/common/arrays*/,3/*vs/base/common/lifecycle*/,4/*vs/base/browser/dom*/]), function (require, exports, arrays, lifecycle_1, DomUtils) {
    /*---------------------------------------------------------------------------------------------
     *  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 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 = (function () {
        function Gesture(target) {
            this.callOnTarget = [];
            this.activeTouches = {};
            this.target = target;
            this.handle = null;
        }
        Gesture.prototype.dispose = function () {
            this.target = null;
            if (this.handle) {
                this.handle.dispose();
                this.handle = null;
            }
        };
        Object.defineProperty(Gesture.prototype, "target", {
            set: function (element) {
                var _this = this;
                this.callOnTarget = lifecycle_1.dispose(this.callOnTarget);
                this.activeTouches = {};
                this.targetElement = element;
                if (!this.targetElement) {
                    return;
                }
                this.callOnTarget.push(DomUtils.addDisposableListener(this.targetElement, 'touchstart', function (e) { return _this.onTouchStart(e); }));
                this.callOnTarget.push(DomUtils.addDisposableListener(this.targetElement, 'touchend', function (e) { return _this.onTouchEnd(e); }));
                this.callOnTarget.push(DomUtils.addDisposableListener(this.targetElement, 'touchmove', function (e) { return _this.onTouchMove(e); }));
            },
            enumerable: true,
            configurable: true
        });
        Gesture.newGestureEvent = function (type) {
            var event = document.createEvent('CustomEvent');
            event.initEvent(type, false, true);
            return event;
        };
        Gesture.prototype.onTouchStart = function (e) {
            var timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
            e.preventDefault();
            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 = Gesture.newGestureEvent(EventType.Start);
                evt.pageX = touch.pageX;
                evt.pageY = touch.pageY;
                this.targetElement.dispatchEvent(evt);
            }
        };
        Gesture.prototype.onTouchEnd = function (e) {
            var timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
            e.preventDefault();
            e.stopPropagation();
            var activeTouchCount = Object.keys(this.activeTouches).length;
            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('move of an UNKNOWN touch', touch);
                    continue;
                }
                var data = this.activeTouches[touch.identifier], holdTime = Date.now() - data.initialTimeStamp;
                if (holdTime < Gesture.HOLD_DELAY
                    && Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)) < 30
                    && Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)) < 30) {
                    var evt = Gesture.newGestureEvent(EventType.Tap);
                    evt.initialTarget = data.initialTarget;
                    evt.pageX = arrays.tail(data.rollingPageX);
                    evt.pageY = arrays.tail(data.rollingPageY);
                    this.targetElement.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 = Gesture.newGestureEvent(EventType.Contextmenu);
                    evt.initialTarget = data.initialTarget;
                    evt.pageX = arrays.tail(data.rollingPageX);
                    evt.pageY = arrays.tail(data.rollingPageY);
                    this.targetElement.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];
                    this.inertia(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
                    );
                }
                // forget about this touch
                delete this.activeTouches[touch.identifier];
            }
        };
        Gesture.prototype.inertia = function (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 = Gesture.newGestureEvent(EventType.Change);
                evt.translationX = delta_pos_x;
                evt.translationY = delta_pos_y;
                _this.targetElement.dispatchEvent(evt);
                if (!stopped) {
                    _this.inertia(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.
            e.preventDefault();
            e.stopPropagation();
            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 = Gesture.newGestureEvent(EventType.Change);
                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.targetElement.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);
            }
        };
        Gesture.HOLD_DELAY = 700;
        Gesture.SCROLL_FRICTION = -0.005;
        return Gesture;
    }());
    exports.Gesture = Gesture;
});

define(__m[110/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,4/*vs/base/browser/dom*/,26/*vs/base/common/objects*/,512/*vs/base/browser/ui/octiconLabel/octiconLabel*/]), function (require, exports, strings_1, dom, objects, octiconLabel_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var HighlightedLabel = (function () {
        function HighlightedLabel(container) {
            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) {
            if (highlights === void 0) { highlights = []; }
            if (!text) {
                text = '';
            }
            if (this.didEverRender && this.text === text && objects.equals(this.highlights, highlights)) {
                return;
            }
            if (!Array.isArray(highlights)) {
                highlights = [];
            }
            this.text = text;
            this.highlights = highlights;
            this.render();
        };
        HighlightedLabel.prototype.render = function () {
            dom.clearNode(this.domNode);
            var htmlContent = [], highlight, pos = 0;
            for (var i = 0; i < this.highlights.length; i++) {
                highlight = this.highlights[i];
                if (highlight.end === highlight.start) {
                    continue;
                }
                if (pos < highlight.start) {
                    htmlContent.push('<span>');
                    htmlContent.push(octiconLabel_1.expand(strings_1.escape(this.text.substring(pos, highlight.start))));
                    htmlContent.push('</span>');
                    pos = highlight.end;
                }
                htmlContent.push('<span class="highlight">');
                htmlContent.push(octiconLabel_1.expand(strings_1.escape(this.text.substring(highlight.start, highlight.end))));
                htmlContent.push('</span>');
                pos = highlight.end;
            }
            if (pos < this.text.length) {
                htmlContent.push('<span>');
                htmlContent.push(octiconLabel_1.expand(strings_1.escape(this.text.substring(pos))));
                htmlContent.push('</span>');
            }
            this.domNode.innerHTML = htmlContent.join('');
            this.didEverRender = true;
        };
        HighlightedLabel.prototype.dispose = function () {
            this.text = null;
            this.highlights = null;
        };
        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[416/*vs/base/browser/ui/list/rowCache*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/]), function (require, exports, dom_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 = (function () {
        function RowCache(renderers) {
            this.renderers = renderers;
            this.cache = Object.create(null);
        }
        /**
         * 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.renderers[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;
            dom_1.removeClass(domNode, 'scrolling');
            removeFromParent(domNode);
            var cache = this.getTemplateCache(templateId);
            cache.push(row);
        };
        RowCache.prototype.getTemplateCache = 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) {
                        var renderer = _this.renderers[templateId];
                        renderer.disposeTemplate(cachedRow.templateData);
                        cachedRow.domNode = null;
                        cachedRow.templateData = null;
                    });
                    delete _this.cache[templateId];
                });
            }
        };
        RowCache.prototype.dispose = function () {
            this.garbageCollect();
            this.cache = null;
            this.renderers = null;
        };
        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[41/*vs/base/browser/ui/widget*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,47/*vs/base/browser/mouseEvent*/,65/*vs/base/browser/keyboardEvent*/,4/*vs/base/browser/dom*/]), function (require, exports, lifecycle_1, mouseEvent_1, keyboardEvent_1, DomUtils) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var Widget = (function (_super) {
        __extends(Widget, _super);
        function Widget() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Widget.prototype.onclick = function (domNode, listener) {
            this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.CLICK, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); }));
        };
        Widget.prototype.onmousedown = function (domNode, listener) {
            this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.MOUSE_DOWN, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); }));
        };
        Widget.prototype.onmouseover = function (domNode, listener) {
            this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.MOUSE_OVER, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); }));
        };
        Widget.prototype.onnonbubblingmouseout = function (domNode, listener) {
            this._register(DomUtils.addDisposableNonBubblingMouseOutListener(domNode, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); }));
        };
        Widget.prototype.onkeydown = function (domNode, listener) {
            this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.KEY_DOWN, function (e) { return listener(new keyboardEvent_1.StandardKeyboardEvent(e)); }));
        };
        Widget.prototype.onkeyup = function (domNode, listener) {
            this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.KEY_UP, function (e) { return listener(new keyboardEvent_1.StandardKeyboardEvent(e)); }));
        };
        Widget.prototype.oninput = function (domNode, listener) {
            this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.INPUT, listener));
        };
        Widget.prototype.onblur = function (domNode, listener) {
            this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.BLUR, listener));
        };
        Widget.prototype.onfocus = function (domNode, listener) {
            this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.FOCUS, listener));
        };
        Widget.prototype.onchange = function (domNode, listener) {
            this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.CHANGE, listener));
        };
        return Widget;
    }(lifecycle_1.Disposable));
    exports.Widget = Widget;
});











define(__m[117/*vs/base/browser/ui/scrollbar/scrollbarArrow*/], __M([1/*require*/,0/*exports*/,83/*vs/base/browser/globalMouseMoveMonitor*/,41/*vs/base/browser/ui/widget*/,18/*vs/base/common/async*/]), function (require, exports, globalMouseMoveMonitor_1, widget_1, async_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * The arrow image size.
     */
    exports.ARROW_IMG_SIZE = 11;
    var ScrollbarArrow = (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;
});











define(__m[53/*vs/base/common/actions*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,38/*vs/base/common/eventEmitter*/,79/*vs/base/common/events*/,11/*vs/base/common/event*/]), function (require, exports, winjs_base_1, eventEmitter_1, Events, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * Checks if the provided object is compatible
     * with the IAction interface.
     * @param thing an object
     */
    function isAction(thing) {
        if (!thing) {
            return false;
        }
        else if (thing instanceof Action) {
            return true;
        }
        else if (typeof thing.id !== 'string') {
            return false;
        }
        else if (typeof thing.label !== 'string') {
            return false;
        }
        else if (typeof thing.class !== 'string') {
            return false;
        }
        else if (typeof thing.enabled !== 'boolean') {
            return false;
        }
        else if (typeof thing.checked !== 'boolean') {
            return false;
        }
        else if (typeof thing.run !== 'function') {
            return false;
        }
        else {
            return true;
        }
    }
    exports.isAction = isAction;
    var Action = (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._id = id;
            this._label = label;
            this._cssClass = cssClass;
            this._enabled = enabled;
            this._actionCallback = actionCallback;
        }
        Action.prototype.dispose = function () {
            this._onDidChange.dispose();
        };
        Object.defineProperty(Action.prototype, "onDidChange", {
            get: function () {
                return this._onDidChange.event;
            },
            enumerable: true,
            configurable: true
        });
        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 });
            }
        };
        Object.defineProperty(Action.prototype, "order", {
            get: function () {
                return this._order;
            },
            set: function (value) {
                this._order = value;
            },
            enumerable: true,
            configurable: true
        });
        Action.prototype.run = function (event, data) {
            if (this._actionCallback !== void 0) {
                return this._actionCallback(event);
            }
            return winjs_base_1.TPromise.as(true);
        };
        return Action;
    }());
    exports.Action = Action;
    var ActionRunner = (function (_super) {
        __extends(ActionRunner, _super);
        function ActionRunner() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ActionRunner.prototype.run = function (action, context) {
            var _this = this;
            if (!action.enabled) {
                return winjs_base_1.TPromise.as(null);
            }
            this.emit(Events.EventType.BEFORE_RUN, { action: action });
            return this.runAction(action, context).then(function (result) {
                _this.emit(Events.EventType.RUN, { action: action, result: result });
            }, function (error) {
                _this.emit(Events.EventType.RUN, { action: action, error: error });
            });
        };
        ActionRunner.prototype.runAction = function (action, context) {
            return winjs_base_1.TPromise.as(context ? action.run(context) : action.run());
        };
        return ActionRunner;
    }(eventEmitter_1.EventEmitter));
    exports.ActionRunner = ActionRunner;
});

define(__m[165/*vs/base/common/glob*/], __M([1/*require*/,0/*exports*/,33/*vs/base/common/arrays*/,26/*vs/base/common/objects*/,9/*vs/base/common/strings*/,45/*vs/base/common/paths*/,80/*vs/base/common/map*/,7/*vs/base/common/winjs.base*/]), function (require, exports, arrays, objects, strings, paths, map_1, winjs_base_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function getEmptyExpression() {
        return Object.create(null);
    }
    exports.getEmptyExpression = getEmptyExpression;
    function mergeExpressions() {
        var expressions = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            expressions[_i] = arguments[_i];
        }
        return objects.assign.apply(objects, [getEmptyExpression()].concat(expressions.filter(function (expr) { return !!expr; })));
    }
    exports.mergeExpressions = mergeExpressions;
    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 char;
        var curVal = '';
        for (var i = 0; i < pattern.length; i++) {
            char = pattern[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, '/');
        // Special case where we only have globstars
        if (segments.every(function (s) { return s === '**'; })) {
            regEx = '.*';
        }
        else {
            var previousSegmentWasGlobStar_1 = false;
            segments.forEach(function (segment, index) {
                // Globstar is special
                if (segment === '**') {
                    // 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 = '';
                var char;
                for (var i = 0; i < segment.length; i++) {
                    char = segment[i];
                    // Support brace expansion
                    if (char !== '}' && inBraces) {
                        braceVal += char;
                        continue;
                    }
                    // Support brackets
                    if (char !== ']' && inBrackets) {
                        var res = void 0;
                        switch (char) {
                            case '-':// allow the range operator
                                res = char;
                                break;
                            case '^':// allow the negate operator
                                res = char;
                                break;
                            default:
                                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 next one is not a globstar
                if (index < segments.length - 1 && segments[index + 1] !== '**') {
                    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.BoundedMap(10000); // bounded to 10000 elements
    var FALSE = function () {
        return false;
    };
    var NULL = function () {
        return null;
    };
    function parsePattern(pattern, options) {
        if (!pattern) {
            return NULL;
        }
        // Whitespace trimming
        pattern = pattern.trim();
        // Check cache
        var patternKey = pattern + "_" + !!options.trimForExclusions;
        var parsedPattern = CACHE.get(patternKey);
        if (parsedPattern) {
            return parsedPattern;
        }
        // Check for Trivias
        var match;
        if (T1.test(pattern)) {
            var base_1 = pattern.substr(4); // '**/*'.length === 4
            parsedPattern = function (path, basename) {
                return path && strings.endsWith(path, base_1) ? pattern : null;
            };
        }
        else if (match = T2.exec(trimForExclusions(pattern, options))) {
            parsedPattern = trivia2(match[1], pattern);
        }
        else if ((options.trimForExclusions ? T3_2 : T3).test(pattern)) {
            parsedPattern = trivia3(pattern, options);
        }
        else if (match = T4.exec(trimForExclusions(pattern, options))) {
            parsedPattern = trivia4and5(match[1].substr(1), pattern, true);
        }
        else if (match = T5.exec(trimForExclusions(pattern, options))) {
            parsedPattern = trivia4and5(match[1], pattern, false);
        }
        else {
            parsedPattern = toRegExp(pattern);
        }
        // Cache
        CACHE.set(patternKey, parsedPattern);
        return parsedPattern;
    }
    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 (!path) {
                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.nativeSep !== paths.sep ? path.replace(ALL_FORWARD_SLASHES, paths.nativeSep) : path;
        var nativePathEnd = paths.nativeSep + nativePath;
        var parsedPattern = matchPathEnds ? function (path, basename) {
            return path && (path === nativePath || strings.endsWith(path, nativePathEnd)) ? pattern : null;
        } : function (path, basename) {
            return path && 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 path && regExp_1.test(path) ? pattern : null;
            };
        }
        catch (error) {
            return NULL;
        }
    }
    function match(arg1, path, siblingsFn) {
        if (!arg1 || !path) {
            return false;
        }
        return parse(arg1)(path, undefined, siblingsFn);
    }
    exports.match = match;
    function parse(arg1, options) {
        if (options === void 0) { options = {}; }
        if (!arg1) {
            return FALSE;
        }
        // Glob with String
        if (typeof arg1 === 'string') {
            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;
    /**
     * Same as `parse`, but the ParsedExpression is guaranteed to return a Promise
     */
    function parseToAsync(expression, options) {
        var parsedExpression = parse(expression, options);
        return function (path, basename, siblingsFn) {
            var result = parsedExpression(path, basename, siblingsFn);
            return result instanceof winjs_base_1.TPromise ? result : winjs_base_1.TPromise.as(result);
        };
    }
    exports.parseToAsync = parseToAsync;
    function getBasenameTerms(patternOrExpression) {
        return patternOrExpression.allBasenames || [];
    }
    exports.getBasenameTerms = getBasenameTerms;
    function getPathTerms(patternOrExpression) {
        return patternOrExpression.allPaths || [];
    }
    exports.getPathTerms = getPathTerms;
    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, siblingsFn) {
                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, siblingsFn) {
            var siblingsPattern;
            var siblingsResolved = !siblingsFn;
            function siblingsToSiblingsPattern(siblings) {
                if (siblings && siblings.length) {
                    if (!basename) {
                        basename = paths.basename(path);
                    }
                    var name_1 = basename.substr(0, basename.length - paths.extname(path).length);
                    return { siblings: siblings, name: name_1 };
                }
                return undefined;
            }
            function siblingsPatternFn() {
                // Resolve siblings only once
                if (!siblingsResolved) {
                    siblingsResolved = true;
                    var siblings = siblingsFn();
                    siblingsPattern = winjs_base_1.TPromise.is(siblings) ?
                        siblings.then(siblingsToSiblingsPattern) :
                        siblingsToSiblingsPattern(siblings);
                }
                return siblingsPattern;
            }
            for (var i = 0, n_3 = parsedPatterns.length; i < n_3; i++) {
                // Pattern matches path
                var result = parsedPatterns[i](path, basename, siblingsPatternFn);
                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 <boolean>
        if (typeof value === 'boolean') {
            return parsedPattern;
        }
        // Expression Pattern is <SiblingClause>
        if (value) {
            var when_1 = value.when;
            if (typeof when_1 === 'string') {
                var siblingsPatternToMatchingPattern_1 = function (siblingsPattern) {
                    var clausePattern = when_1.replace('$(basename)', siblingsPattern.name);
                    if (siblingsPattern.siblings.indexOf(clausePattern) !== -1) {
                        return pattern;
                    }
                    else {
                        return null; // pattern does not match in the end because the when clause is not satisfied
                    }
                };
                var result = function (path, basename, siblingsPatternFn) {
                    if (!parsedPattern(path, basename)) {
                        return null;
                    }
                    var siblingsPattern = siblingsPatternFn();
                    if (!siblingsPattern) {
                        return null; // pattern is malformed or we don't have siblings
                    }
                    return winjs_base_1.TPromise.is(siblingsPattern) ?
                        siblingsPattern.then(siblingsPatternToMatchingPattern_1) :
                        siblingsPatternToMatchingPattern_1(siblingsPattern);
                };
                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) { return all.concat(current.basenames); }, []);
        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) { return all.concat(current.patterns); }, []);
        }
        var aggregate = function (path, basename) {
            if (!path) {
                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;
    }
});

define(__m[166/*vs/base/common/mime*/], __M([1/*require*/,0/*exports*/,45/*vs/base/common/paths*/,29/*vs/base/common/types*/,9/*vs/base/common/strings*/,165/*vs/base/common/glob*/]), function (require, exports, paths, types, strings, glob_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MIME_TEXT = 'text/plain';
    exports.MIME_BINARY = 'application/octet-stream';
    exports.MIME_UNKNOWN = 'application/unknown';
    var registeredAssociations = [];
    var nonUserRegisteredAssociations = [];
    var userRegisteredAssociations = [];
    /**
     * Associate a text mime to the registry.
     */
    function registerTextMime(association) {
        // 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 (!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() : void 0,
            extensionLowercase: association.extension ? association.extension.toLowerCase() : void 0,
            filepatternLowercase: association.filepattern ? association.filepattern.toLowerCase() : void 0,
            filepatternOnPath: association.filepattern ? association.filepattern.indexOf(paths.sep) >= 0 : false
        };
    }
    /**
     * Clear text mimes from the registry.
     */
    function clearTextMimes(onlyUserConfigured) {
        if (!onlyUserConfigured) {
            registeredAssociations = [];
            nonUserRegisteredAssociations = [];
            userRegisteredAssociations = [];
        }
        else {
            registeredAssociations = registeredAssociations.filter(function (a) { return !a.userConfigured; });
            userRegisteredAssociations = [];
        }
    }
    exports.clearTextMimes = clearTextMimes;
    /**
     * 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 = paths.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;
        var patternMatch;
        var extensionMatch;
        // 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.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.startsWithUTF8BOM(firstLine)) {
            firstLine = firstLine.substr(1);
        }
        if (firstLine.length > 0) {
            for (var i = 0; i < registeredAssociations.length; ++i) {
                var association = registeredAssociations[i];
                if (!association.firstline) {
                    continue;
                }
                var matches = firstLine.match(association.firstline);
                if (matches && matches.length > 0) {
                    return association.mime;
                }
            }
        }
        return null;
    }
    function isBinaryMime(mimes) {
        if (!mimes) {
            return false;
        }
        var mimeVals;
        if (types.isArray(mimes)) {
            mimeVals = mimes;
        }
        else {
            mimeVals = mimes.split(',').map(function (mime) { return mime.trim(); });
        }
        return mimeVals.indexOf(exports.MIME_BINARY) >= 0;
    }
    exports.isBinaryMime = isBinaryMime;
    function isUnspecific(mime) {
        if (!mime) {
            return true;
        }
        if (typeof mime === 'string') {
            return mime === exports.MIME_BINARY || mime === exports.MIME_TEXT || mime === exports.MIME_UNKNOWN;
        }
        return mime.length === 1 && isUnspecific(mime[0]);
    }
    exports.isUnspecific = isUnspecific;
    function suggestFilename(langId, prefix) {
        for (var i = 0; i < registeredAssociations.length; i++) {
            var association = registeredAssociations[i];
            if (association.userConfigured) {
                continue; // only support registered ones
            }
            if (association.id === langId && association.extension) {
                return prefix + association.extension;
            }
        }
        return prefix; // without any known extension, just return the prefix
    }
    exports.suggestFilename = suggestFilename;
});











define(__m[48/*vs/base/common/scrollable*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,11/*vs/base/common/event*/]), function (require, exports, lifecycle_1, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ScrollbarVisibility;
    (function (ScrollbarVisibility) {
        ScrollbarVisibility[ScrollbarVisibility["Auto"] = 1] = "Auto";
        ScrollbarVisibility[ScrollbarVisibility["Hidden"] = 2] = "Hidden";
        ScrollbarVisibility[ScrollbarVisibility["Visible"] = 3] = "Visible";
    })(ScrollbarVisibility = exports.ScrollbarVisibility || (exports.ScrollbarVisibility = {}));
    var ScrollState = (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.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 = (function (_super) {
        __extends(Scrollable, _super);
        function Scrollable() {
            var _this = _super.call(this) || this;
            _this._onScroll = _this._register(new event_1.Emitter());
            _this.onScroll = _this._onScroll.event;
            _this._state = new ScrollState(0, 0, 0, 0, 0, 0);
            return _this;
        }
        Scrollable.prototype.getState = function () {
            return this._state;
        };
        Scrollable.prototype.validateScrollTop = function (desiredScrollTop) {
            desiredScrollTop = Math.round(desiredScrollTop);
            desiredScrollTop = Math.max(desiredScrollTop, 0);
            desiredScrollTop = Math.min(desiredScrollTop, this._state.scrollHeight - this._state.height);
            return desiredScrollTop;
        };
        Scrollable.prototype.validateScrollLeft = function (desiredScrollLeft) {
            desiredScrollLeft = Math.round(desiredScrollLeft);
            desiredScrollLeft = Math.max(desiredScrollLeft, 0);
            desiredScrollLeft = Math.min(desiredScrollLeft, this._state.scrollWidth - this._state.width);
            return desiredScrollLeft;
        };
        Scrollable.prototype.updateState = function (update) {
            var oldState = this._state;
            var newState = new ScrollState((typeof update.width !== 'undefined' ? update.width : oldState.width), (typeof update.scrollWidth !== 'undefined' ? update.scrollWidth : oldState.scrollWidth), (typeof update.scrollLeft !== 'undefined' ? update.scrollLeft : oldState.scrollLeft), (typeof update.height !== 'undefined' ? update.height : oldState.height), (typeof update.scrollHeight !== 'undefined' ? update.scrollHeight : oldState.scrollHeight), (typeof update.scrollTop !== 'undefined' ? update.scrollTop : oldState.scrollTop));
            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;
});











define(__m[429/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,18/*vs/base/common/async*/,48/*vs/base/common/scrollable*/]), function (require, exports, lifecycle_1, async_1, scrollable_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ScrollbarVisibilityController = (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 === scrollable_1.ScrollbarVisibility.Hidden) {
                return false;
            }
            if (this._visibility === scrollable_1.ScrollbarVisibility.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 () {
                _this._domNode.setClassName(_this._visibleClassName);
            }, 0);
        };
        ScrollbarVisibilityController.prototype._hide = function (withFadeAway) {
            this._revealTimer.cancel();
            if (!this._isVisible) {
                return;
            }
            this._isVisible = false;
            this._domNode.setClassName(this._invisibleClassName + (withFadeAway ? ' fade' : ''));
        };
        return ScrollbarVisibilityController;
    }(lifecycle_1.Disposable));
    exports.ScrollbarVisibilityController = ScrollbarVisibilityController;
});











define(__m[184/*vs/base/browser/ui/scrollbar/abstractScrollbar*/], __M([1/*require*/,0/*exports*/,15/*vs/base/common/platform*/,4/*vs/base/browser/dom*/,83/*vs/base/browser/globalMouseMoveMonitor*/,41/*vs/base/browser/ui/widget*/,27/*vs/base/browser/fastDomNode*/,117/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,429/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/]), function (require, exports, Platform, DomUtils, globalMouseMoveMonitor_1, widget_1, fastDomNode_1, scrollbarArrow_1, scrollbarVisibilityController_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * The orthogonal distance to the slider at which dragging "resets". This implements "snapping"
     */
    var MOUSE_DRAG_RESET_DISTANCE = 140;
    var AbstractScrollbar = (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);
            this.slider.setWidth(width);
            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.delegateSliderMouseDown = function (e, onDragFinished) {
            this._sliderMouseDown(e, onDragFinished);
        };
        AbstractScrollbar.prototype._onMouseDown = function (e) {
            var domNodePosition = DomUtils.getDomNodePagePosition(this.domNode.domNode);
            this.setDesiredScrollPosition(this._scrollbarState.getDesiredScrollPositionFromOffset(this._mouseDownRelativePosition(e, domNodePosition)));
            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.setDesiredScrollPosition(initialScrollbarState.getScrollPosition());
                    return;
                }
                var mousePosition = _this._sliderMousePosition(mouseMoveData);
                var mouseDelta = mousePosition - initialMousePosition;
                _this.setDesiredScrollPosition(initialScrollbarState.getDesiredScrollPositionFromDelta(mouseDelta));
            }, function () {
                _this.slider.toggleClassName('active', false);
                _this._host.onDragEnd();
                onDragFinished();
            });
            this._host.onDragStart();
        };
        AbstractScrollbar.prototype.setDesiredScrollPosition = function (desiredScrollPosition) {
            desiredScrollPosition = this.validateScrollPosition(desiredScrollPosition);
            var oldScrollPosition = this._getScrollPosition();
            this._setScrollPosition(desiredScrollPosition);
            var newScrollPosition = this._getScrollPosition();
            if (oldScrollPosition !== newScrollPosition) {
                this._onElementScrollPosition(this._getScrollPosition());
                return true;
            }
            return false;
        };
        return AbstractScrollbar;
    }(widget_1.Widget));
    exports.AbstractScrollbar = AbstractScrollbar;
});











define(__m[439/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/], __M([1/*require*/,0/*exports*/,184/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,47/*vs/base/browser/mouseEvent*/,48/*vs/base/common/scrollable*/,150/*vs/base/browser/ui/scrollbar/scrollbarState*/,117/*vs/base/browser/ui/scrollbar/scrollbarArrow*/]), function (require, exports, abstractScrollbar_1, mouseEvent_1, scrollable_1, scrollbarState_1, scrollbarArrow_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var HorizontalScrollbar = (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 === scrollable_1.ScrollbarVisibility.Hidden ? 0 : options.horizontalScrollbarSize), (options.vertical === scrollable_1.ScrollbarVisibility.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: void 0,
                    right: void 0,
                    bgWidth: options.arrowSize,
                    bgHeight: options.horizontalScrollbarSize,
                    onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardMouseWheelEvent(null, 1, 0)); },
                });
                _this._createArrow({
                    className: 'right-arrow',
                    top: scrollbarDelta,
                    left: void 0,
                    bottom: void 0,
                    right: arrowDelta,
                    bgWidth: options.arrowSize,
                    bgHeight: options.horizontalScrollbarSize,
                    onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardMouseWheelEvent(null, -1, 0)); },
                });
            }
            _this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, null, 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 (e, domNodePosition) {
            return e.posx - domNodePosition.left;
        };
        HorizontalScrollbar.prototype._sliderMousePosition = function (e) {
            return e.posx;
        };
        HorizontalScrollbar.prototype._sliderOrthogonalMousePosition = function (e) {
            return e.posy;
        };
        HorizontalScrollbar.prototype._getScrollPosition = function () {
            var scrollState = this._scrollable.getState();
            return scrollState.scrollLeft;
        };
        HorizontalScrollbar.prototype._setScrollPosition = function (scrollPosition) {
            this._scrollable.updateState({
                scrollLeft: scrollPosition
            });
        };
        HorizontalScrollbar.prototype.validateScrollPosition = function (desiredScrollPosition) {
            return this._scrollable.validateScrollLeft(desiredScrollPosition);
        };
        return HorizontalScrollbar;
    }(abstractScrollbar_1.AbstractScrollbar));
    exports.HorizontalScrollbar = HorizontalScrollbar;
});











define(__m[440/*vs/base/browser/ui/scrollbar/verticalScrollbar*/], __M([1/*require*/,0/*exports*/,184/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,47/*vs/base/browser/mouseEvent*/,48/*vs/base/common/scrollable*/,150/*vs/base/browser/ui/scrollbar/scrollbarState*/,117/*vs/base/browser/ui/scrollbar/scrollbarArrow*/]), function (require, exports, abstractScrollbar_1, mouseEvent_1, scrollable_1, scrollbarState_1, scrollbarArrow_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var VerticalScrollbar = (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 === scrollable_1.ScrollbarVisibility.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: void 0,
                    right: void 0,
                    bgWidth: options.verticalScrollbarSize,
                    bgHeight: options.arrowSize,
                    onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardMouseWheelEvent(null, 0, 1)); },
                });
                _this._createArrow({
                    className: 'down-arrow',
                    top: void 0,
                    left: scrollbarDelta,
                    bottom: arrowDelta,
                    right: void 0,
                    bgWidth: options.verticalScrollbarSize,
                    bgHeight: options.arrowSize,
                    onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardMouseWheelEvent(null, 0, -1)); },
                });
            }
            _this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, null);
            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 (e, domNodePosition) {
            return e.posy - domNodePosition.top;
        };
        VerticalScrollbar.prototype._sliderMousePosition = function (e) {
            return e.posy;
        };
        VerticalScrollbar.prototype._sliderOrthogonalMousePosition = function (e) {
            return e.posx;
        };
        VerticalScrollbar.prototype._getScrollPosition = function () {
            var scrollState = this._scrollable.getState();
            return scrollState.scrollTop;
        };
        VerticalScrollbar.prototype._setScrollPosition = function (scrollPosition) {
            this._scrollable.updateState({
                scrollTop: scrollPosition
            });
        };
        VerticalScrollbar.prototype.validateScrollPosition = function (desiredScrollPosition) {
            return this._scrollable.validateScrollTop(desiredScrollPosition);
        };
        return VerticalScrollbar;
    }(abstractScrollbar_1.AbstractScrollbar));
    exports.VerticalScrollbar = VerticalScrollbar;
});











define(__m[197/*vs/base/common/worker/simpleWorker*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,3/*vs/base/common/lifecycle*/,7/*vs/base/common/winjs.base*/,18/*vs/base/common/async*/,15/*vs/base/common/platform*/]), function (require, exports, errors_1, lifecycle_1, winjs_base_1, async_1, platform_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var 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 = (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 req = String(++this._lastSentReq);
            var reply = {
                c: null,
                e: null
            };
            var result = new winjs_base_1.TPromise(function (c, e, p) {
                reply.c = c;
                reply.e = e;
            }, function () {
                // Cancel not supported
            });
            this._pendingReplies[req] = reply;
            this._send({
                vsWorker: this._workerId,
                req: req,
                method: method,
                args: args
            });
            return result;
        };
        SimpleWorkerProtocol.prototype.handleMessage = function (serializedMessage) {
            var message;
            try {
                message = JSON.parse(serializedMessage);
            }
            catch (e) {
                // nothing
            }
            if (!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.e(err);
                    return;
                }
                reply.c(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) {
                _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 = (function (_super) {
        __extends(SimpleWorkerClient, _super);
        function SimpleWorkerClient(workerFactory, moduleId) {
            var _this = _super.call(this) || this;
            _this._lastRequestTimestamp = -1;
            var lazyProxyFulfill = null;
            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
                lazyProxyReject(err);
            }));
            _this._protocol = new SimpleWorkerProtocol({
                sendMessage: function (msg) {
                    _this._worker.postMessage(msg);
                },
                handleMessage: function (method, args) {
                    // Intentionally not supporting worker -> main requests
                    return winjs_base_1.TPromise.as(null);
                }
            });
            _this._protocol.setWorkerId(_this._worker.getId());
            // Gather loader configuration
            var loaderConfiguration = null;
            var globalRequire = self.require;
            if (typeof globalRequire.getConfig === 'function') {
                // Get the configuration from the Monaco AMD Loader
                loaderConfiguration = globalRequire.getConfig();
            }
            else if (typeof self.requirejs !== 'undefined') {
                // Get the configuration from requirejs
                loaderConfiguration = self.requirejs.s.contexts._.config;
            }
            _this._lazyProxy = new winjs_base_1.TPromise(function (c, e, p) {
                lazyProxyFulfill = c;
                lazyProxyReject = e;
            }, function () { });
            // Send initialize message
            _this._onModuleLoaded = _this._protocol.sendMessage(INITIALIZE, [
                _this._worker.getId(),
                moduleId,
                loaderConfiguration
            ]);
            _this._onModuleLoaded.then(function (availableMethods) {
                var proxy = {};
                for (var i = 0; i < availableMethods.length; i++) {
                    proxy[availableMethods[i]] = createProxyMethod(availableMethods[i], proxyMethodRequest);
                }
                lazyProxyFulfill(proxy);
            }, function (e) {
                lazyProxyReject(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 () {
            // Do not allow chaining promises to cancel the proxy creation
            return new async_1.ShallowCancelThenPromise(this._lazyProxy);
        };
        SimpleWorkerClient.prototype.getLastRequestTimestamp = function () {
            return this._lastRequestTimestamp;
        };
        SimpleWorkerClient.prototype._request = function (method, args) {
            var _this = this;
            return new winjs_base_1.TPromise(function (c, e, p) {
                _this._onModuleLoaded.then(function () {
                    _this._lastRequestTimestamp = Date.now();
                    _this._protocol.sendMessage(method, args).then(c, e);
                }, e);
            }, function () {
                // Cancel intentionally not supported
            });
        };
        SimpleWorkerClient.prototype._onError = function (message, error) {
            console.error(message);
            console.info(error);
        };
        return SimpleWorkerClient;
    }(lifecycle_1.Disposable));
    exports.SimpleWorkerClient = SimpleWorkerClient;
    /**
     * Worker side
     */
    var SimpleWorkerServer = (function () {
        function SimpleWorkerServer(postSerializedMessage) {
            var _this = this;
            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 winjs_base_1.TPromise.wrapError(new Error('Missing requestHandler or method: ' + method));
            }
            try {
                return winjs_base_1.TPromise.as(this._requestHandler[method].apply(this._requestHandler, args));
            }
            catch (e) {
                return winjs_base_1.TPromise.wrapError(e);
            }
        };
        SimpleWorkerServer.prototype.initialize = function (workerId, moduleId, loaderConfig) {
            var _this = this;
            this._protocol.setWorkerId(workerId);
            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'];
                    }
                }
                var nlsConfig_1 = loaderConfig['vs/nls'];
                // We need to have pseudo translation
                if (nlsConfig_1 && nlsConfig_1.pseudo) {
                    require(['vs/nls'], function (nlsPlugin) {
                        nlsPlugin.setPseudoTranslation(nlsConfig_1.pseudo);
                    });
                }
                // Since this is in a web worker, enable catching errors
                loaderConfig.catchError = true;
                self.require.config(loaderConfig);
            }
            var cc;
            var ee;
            var r = new winjs_base_1.TPromise(function (c, e, p) {
                cc = c;
                ee = e;
            });
            // 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();
                var methods = [];
                for (var prop in _this._requestHandler) {
                    if (typeof _this._requestHandler[prop] === 'function') {
                        methods.push(prop);
                    }
                }
                cc(methods);
            }, ee);
            return r;
        };
        return SimpleWorkerServer;
    }());
    exports.SimpleWorkerServer = SimpleWorkerServer;
    /**
     * Called on the worker side
     */
    function create(postMessage) {
        return new SimpleWorkerServer(postMessage);
    }
    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[445/*vs/base/parts/quickopen/browser/quickOpenViewer*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,29/*vs/base/common/types*/]), function (require, exports, winjs_base_1, types_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var DataSource = (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 winjs_base_1.TPromise.as(model === element ? model.entries : []);
        };
        DataSource.prototype.getParent = function (tree, element) {
            return winjs_base_1.TPromise.as(null);
        };
        return DataSource;
    }());
    exports.DataSource = DataSource;
    var AccessibilityProvider = (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);
        };
        AccessibilityProvider.prototype.getPosInSet = function (tree, element) {
            var model = this.modelProvider.getModel();
            return String(model.entries.indexOf(element) + 1);
        };
        AccessibilityProvider.prototype.getSetSize = function () {
            var model = this.modelProvider.getModel();
            return String(model.entries.length);
        };
        return AccessibilityProvider;
    }());
    exports.AccessibilityProvider = AccessibilityProvider;
    var Filter = (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 = (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;
});

define(__m[100/*vs/base/parts/quickopen/common/quickOpen*/], __M([1/*require*/,0/*exports*/]), 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 Mode;
    (function (Mode) {
        Mode[Mode["PREVIEW"] = 0] = "PREVIEW";
        Mode[Mode["OPEN"] = 1] = "OPEN";
        Mode[Mode["OPEN_IN_BACKGROUND"] = 2] = "OPEN_IN_BACKGROUND";
    })(Mode = exports.Mode || (exports.Mode = {}));
});











define(__m[448/*vs/base/parts/tree/browser/tree*/], __M([1/*require*/,0/*exports*/]), 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 ContextMenuEvent = (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, "posx", {
            get: function () {
                return this._posx;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ContextMenuEvent.prototype, "posy", {
            get: function () {
                return this._posy;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ContextMenuEvent.prototype, "target", {
            get: function () {
                return this._target;
            },
            enumerable: true,
            configurable: true
        });
        return ContextMenuEvent;
    }());
    exports.ContextMenuEvent = ContextMenuEvent;
    var MouseContextMenuEvent = (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 = (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;
    var DragOverEffect;
    (function (DragOverEffect) {
        DragOverEffect[DragOverEffect["COPY"] = 0] = "COPY";
        DragOverEffect[DragOverEffect["MOVE"] = 1] = "MOVE";
    })(DragOverEffect = exports.DragOverEffect || (exports.DragOverEffect = {}));
    var DragOverBubble;
    (function (DragOverBubble) {
        DragOverBubble[DragOverBubble["BUBBLE_DOWN"] = 0] = "BUBBLE_DOWN";
        DragOverBubble[DragOverBubble["BUBBLE_UP"] = 1] = "BUBBLE_UP";
    })(DragOverBubble = exports.DragOverBubble || (exports.DragOverBubble = {}));
    exports.DRAG_OVER_REJECT = { accept: false };
    exports.DRAG_OVER_ACCEPT = { accept: true };
    exports.DRAG_OVER_ACCEPT_BUBBLE_UP = { accept: true, bubble: DragOverBubble.BUBBLE_UP };
    exports.DRAG_OVER_ACCEPT_BUBBLE_DOWN = function (autoExpand) {
        if (autoExpand === void 0) { autoExpand = false; }
        return ({ accept: true, bubble: DragOverBubble.BUBBLE_DOWN, autoExpand: autoExpand });
    };
    exports.DRAG_OVER_ACCEPT_BUBBLE_UP_COPY = { accept: true, bubble: DragOverBubble.BUBBLE_UP, effect: DragOverEffect.COPY };
    exports.DRAG_OVER_ACCEPT_BUBBLE_DOWN_COPY = function (autoExpand) {
        if (autoExpand === void 0) { autoExpand = false; }
        return ({ accept: true, bubble: DragOverBubble.BUBBLE_DOWN, effect: DragOverEffect.COPY, autoExpand: autoExpand });
    };
});

define(__m[461/*vs/base/parts/tree/browser/treeDnd*/], __M([1/*require*/,0/*exports*/]), 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 ElementsDragAndDropData = (function () {
        function ElementsDragAndDropData(elements) {
            this.elements = elements;
        }
        ElementsDragAndDropData.prototype.update = function (event) {
            // no-op
        };
        ElementsDragAndDropData.prototype.getData = function () {
            return this.elements;
        };
        return ElementsDragAndDropData;
    }());
    exports.ElementsDragAndDropData = ElementsDragAndDropData;
    var ExternalElementsDragAndDropData = (function () {
        function ExternalElementsDragAndDropData(elements) {
            this.elements = elements;
        }
        ExternalElementsDragAndDropData.prototype.update = function (event) {
            // no-op
        };
        ExternalElementsDragAndDropData.prototype.getData = function () {
            return this.elements;
        };
        return ExternalElementsDragAndDropData;
    }());
    exports.ExternalElementsDragAndDropData = ExternalElementsDragAndDropData;
    var DesktopDragAndDropData = (function () {
        function DesktopDragAndDropData() {
            this.types = [];
            this.files = [];
        }
        DesktopDragAndDropData.prototype.update = function (event) {
            if (event.dataTransfer.types) {
                this.types = [];
                Array.prototype.push.apply(this.types, event.dataTransfer.types);
            }
            if (event.dataTransfer.files) {
                this.files = [];
                Array.prototype.push.apply(this.files, event.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;
});











define(__m[466/*vs/base/parts/tree/browser/treeModel*/], __M([1/*require*/,0/*exports*/,72/*vs/base/common/assert*/,10/*vs/base/common/errors*/,3/*vs/base/common/lifecycle*/,33/*vs/base/common/arrays*/,38/*vs/base/common/eventEmitter*/,7/*vs/base/common/winjs.base*/]), function (require, exports, Assert, errors_1, lifecycle_1, arrays, Events, WinJS) {
    /*---------------------------------------------------------------------------------------------
     *  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 LockData = (function (_super) {
        __extends(LockData, _super);
        function LockData(item) {
            var _this = _super.call(this) || this;
            _this._item = item;
            return _this;
        }
        Object.defineProperty(LockData.prototype, "item", {
            get: function () {
                return this._item;
            },
            enumerable: true,
            configurable: true
        });
        LockData.prototype.dispose = function () {
            this.emit('unlock');
            _super.prototype.dispose.call(this);
        };
        return LockData;
    }(Events.EventEmitter));
    exports.LockData = LockData;
    var Lock = (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) {
                var unbindListener;
                return new WinJS.TPromise(function (c, e) {
                    unbindListener = lock.addOneTimeListener('unlock', function () {
                        return _this.run(item, fn).then(c, e);
                    });
                }, function () { unbindListener.dispose(); });
            }
            var result;
            return new WinJS.TPromise(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;
            }, function () { return result.cancel(); });
        };
        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 = (function (_super) {
        __extends(ItemRegistry, _super);
        function ItemRegistry() {
            var _this = _super.call(this) || this;
            _this._isDisposed = false;
            _this.items = {};
            return _this;
        }
        ItemRegistry.prototype.register = function (item) {
            Assert.ok(!this.isRegistered(item.id), 'item already registered: ' + item.id);
            this.items[item.id] = { item: item, disposable: this.addEmitter(item) };
        };
        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 () {
            _super.prototype.dispose.call(this);
            this.items = null;
            this._isDisposed = true;
        };
        ItemRegistry.prototype.isDisposed = function () {
            return this._isDisposed;
        };
        return ItemRegistry;
    }(Events.EventEmitter));
    exports.ItemRegistry = ItemRegistry;
    var Item = (function (_super) {
        __extends(Item, _super);
        function Item(id, registry, context, lock, element) {
            var _this = _super.call(this) || this;
            _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.userContent = null;
            _this.traits = {};
            _this.depth = 0;
            _this.expanded = _this.context.dataSource.shouldAutoexpand && _this.context.dataSource.shouldAutoexpand(_this.context.tree, element);
            _this.emit('item:create', { item: _this });
            _this.visible = _this._isVisible();
            _this.height = _this._getHeight();
            _this._isDisposed = false;
            return _this;
        }
        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.emit('item:reveal', eventData);
        };
        Item.prototype.expand = function () {
            var _this = this;
            if (this.isExpanded() || !this.doesHaveChildren || this.lock.isLocked(this)) {
                return WinJS.TPromise.as(false);
            }
            var result = this.lock.run(this, function () {
                var eventData = { item: _this };
                var result;
                _this.emit('item:expanding', eventData);
                if (_this.needsChildrenRefresh) {
                    result = _this.refreshChildren(false, true, true);
                }
                else {
                    result = WinJS.TPromise.as(null);
                }
                return result.then(function () {
                    _this._setExpanded(true);
                    _this.emit('item:expanded', 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 = WinJS.TPromise.as(null);
                this.forEachChild(function (child) {
                    collapseChildrenPromise = collapseChildrenPromise.then(function () { return child.collapse(true); });
                });
                return collapseChildrenPromise.then(function () {
                    return _this.collapse(false);
                });
            }
            else {
                if (!this.isExpanded() || this.lock.isLocked(this)) {
                    return WinJS.TPromise.as(false);
                }
                return this.lock.run(this, function () {
                    var eventData = { item: _this };
                    _this.emit('item:collapsing', eventData);
                    _this._setExpanded(false);
                    _this.emit('item:collapsed', eventData);
                    return WinJS.TPromise.as(true);
                });
            }
        };
        Item.prototype.addTrait = function (trait) {
            var eventData = { item: this, trait: trait };
            this.traits[trait] = true;
            this.emit('item:addTrait', eventData);
        };
        Item.prototype.removeTrait = function (trait) {
            var eventData = { item: this, trait: trait };
            delete this.traits[trait];
            this.emit('item:removeTrait', 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()) {
                this.needsChildrenRefresh = true;
                return WinJS.TPromise.as(this);
            }
            this.needsChildrenRefresh = false;
            var doRefresh = function () {
                var eventData = { item: _this, isNested: safe };
                _this.emit('item:childrenRefreshing', eventData);
                var childrenPromise;
                if (_this.doesHaveChildren) {
                    childrenPromise = _this.context.dataSource.getChildren(_this.context.tree, _this.element);
                }
                else {
                    childrenPromise = WinJS.TPromise.as([]);
                }
                var result = childrenPromise.then(function (elements) {
                    if (_this.isDisposed() || _this.registry.isDisposed()) {
                        return WinJS.TPromise.as(null);
                    }
                    if (!Array.isArray(elements)) {
                        return WinJS.TPromise.wrapError(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 WinJS.Promise.join(_this.mapEachChild(function (child) {
                            return child.doRefresh(recursive, true);
                        }));
                    }
                    else {
                        return WinJS.TPromise.as(null);
                    }
                });
                return result
                    .then(null, errors_1.onUnexpectedError)
                    .then(function () { return _this.emit('item:childrenRefreshed', eventData); });
            };
            return safe ? doRefresh() : this.lock.run(this, doRefresh);
        };
        Item.prototype.doRefresh = function (recursive, safe) {
            if (safe === void 0) { safe = false; }
            var eventData = { item: this };
            this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element);
            this.height = this._getHeight();
            this.setVisible(this._isVisible());
            this.emit('item:refresh', eventData);
            return this.refreshChildren(recursive, safe);
        };
        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.getHierarchy = function () {
            var result = [];
            var node = this;
            do {
                result.push(node);
                node = node.parent;
            } while (node);
            result.reverse();
            return result;
        };
        Item.prototype.isAncestorOf = function (item) {
            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) {
                this.firstChild.previous = item;
                item.next = this.firstChild;
                item.previous = null;
                this.firstChild = item;
            }
            else if (atTail) {
                this.lastChild.next = item;
                item.next = null;
                item.previous = this.lastChild;
                this.lastChild = item;
            }
            else {
                item.previous = afterItem;
                item.next = afterItem.next;
                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) {
                item.next.previous = null;
                this.firstChild = item.next;
            }
            else if (isLastChild) {
                item.previous.next = null;
                this.lastChild = item.previous;
            }
            else {
                item.next.previous = item.previous;
                item.previous.next = item.next;
            }
            item.parent = null;
            item.depth = null;
        };
        Item.prototype.forEachChild = function (fn) {
            var child = this.firstChild, 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;
            if (this.context.sorter) {
                return elements.sort(function (element, otherElement) {
                    return _this.context.sorter.compare(_this.context.tree, element, otherElement);
                });
            }
            return elements;
        };
        /* protected */ Item.prototype._getHeight = function () {
            return this.context.renderer.getHeight(this.context.tree, this.element);
        };
        /* protected */ Item.prototype._isVisible = function () {
            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;
            var eventData = { item: this };
            this.emit('item:dispose', eventData);
            this.registry.deregister(this);
            _super.prototype.dispose.call(this);
            this._isDisposed = true;
        };
        return Item;
    }(Events.EventEmitter));
    exports.Item = Item;
    var RootItem = (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
        };
        RootItem.prototype.render = function () {
            // no-op
        };
        /* protected */ RootItem.prototype._getHeight = function () {
            return 0;
        };
        /* protected */ RootItem.prototype._isVisible = function () {
            return false;
        };
        return RootItem;
    }(Item));
    var TreeNavigator = (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;
            }
            else {
                if (!(item instanceof RootItem) && (!item.isVisible() || !item.isExpanded() || item.lastChild === null)) {
                    return item;
                }
                else {
                    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 = this.item.parent;
                if (parent && parent !== this.start && parent.isVisible()) {
                    this.item = parent;
                }
                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;
    function getRange(one, other) {
        var oneHierarchy = one.getHierarchy();
        var otherHierarchy = other.getHierarchy();
        var length = arrays.commonPrefixLength(oneHierarchy, otherHierarchy);
        var item = oneHierarchy[length - 1];
        var nav = item.getNavigator();
        var oneIndex = null;
        var otherIndex = null;
        var index = 0;
        var result = [];
        while (item && (oneIndex === null || otherIndex === null)) {
            result.push(item);
            if (item === one) {
                oneIndex = index;
            }
            if (item === other) {
                otherIndex = index;
            }
            index++;
            item = nav.next();
        }
        if (oneIndex === null || otherIndex === null) {
            return [];
        }
        var min = Math.min(oneIndex, otherIndex);
        var max = Math.max(oneIndex, otherIndex);
        return result.slice(min, max + 1);
    }
    var TreeModel = (function (_super) {
        __extends(TreeModel, _super);
        function TreeModel(context) {
            var _this = _super.call(this) || this;
            _this.context = context;
            _this.input = null;
            _this.traitsToItems = {};
            return _this;
        }
        TreeModel.prototype.setInput = function (element) {
            var _this = this;
            var eventData = { item: this.input };
            this.emit('clearingInput', 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.registryDisposable = lifecycle_1.combinedDisposable([
                this.addEmitter(this.registry),
                this.registry.addListener('item:dispose', function (event) {
                    event.item.getAllTraits()
                        .forEach(function (trait) { return delete _this.traitsToItems[trait][event.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.emit('setInput', 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 WinJS.TPromise.as(null);
            }
            var eventData = { item: item, recursive: recursive };
            this.emit('refreshing', eventData);
            return item.refresh(recursive).then(function () {
                _this.emit('refreshed', eventData);
            });
        };
        TreeModel.prototype.expand = function (element) {
            var item = this.getItem(element);
            if (!item) {
                return WinJS.TPromise.as(false);
            }
            return item.expand();
        };
        TreeModel.prototype.expandAll = function (elements) {
            if (!elements) {
                elements = [];
                var item;
                var nav = this.getNavigator();
                while (item = nav.next()) {
                    elements.push(item);
                }
            }
            var promises = [];
            for (var i = 0, len = elements.length; i < len; i++) {
                promises.push(this.expand(elements[i]));
            }
            return WinJS.Promise.join(promises);
        };
        TreeModel.prototype.collapse = function (element, recursive) {
            if (recursive === void 0) { recursive = false; }
            var item = this.getItem(element);
            if (!item) {
                return WinJS.TPromise.as(false);
            }
            return item.collapse(recursive);
        };
        TreeModel.prototype.collapseAll = function (elements, recursive) {
            if (elements === void 0) { elements = null; }
            if (recursive === void 0) { recursive = false; }
            if (!elements) {
                elements = [this.input];
                recursive = true;
            }
            var promises = [];
            for (var i = 0, len = elements.length; i < len; i++) {
                promises.push(this.collapse(elements[i], recursive));
            }
            return WinJS.Promise.join(promises);
        };
        TreeModel.prototype.toggleExpansion = function (element) {
            return this.isExpanded(element) ? this.collapse(element) : this.expand(element);
        };
        TreeModel.prototype.toggleExpansionAll = function (elements) {
            var promises = [];
            for (var i = 0, len = elements.length; i < len; i++) {
                promises.push(this.toggleExpansion(elements[i]));
            }
            return WinJS.Promise.join(promises);
        };
        TreeModel.prototype.isExpanded = function (element) {
            var item = this.getItem(element);
            if (!item) {
                return false;
            }
            return item.isExpanded();
        };
        TreeModel.prototype.getExpandedElements = function () {
            var result = [];
            var item;
            var nav = this.getNavigator();
            while (item = nav.next()) {
                if (item.isExpanded()) {
                    result.push(item.getElement());
                }
            }
            return result;
        };
        TreeModel.prototype.reveal = function (element, relativeTop) {
            var _this = this;
            if (relativeTop === void 0) { relativeTop = null; }
            return this.resolveUnknownParentChain(element).then(function (chain) {
                var result = WinJS.TPromise.as(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 WinJS.TPromise.as([]);
                }
                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.emit('highlight', eventData);
        };
        TreeModel.prototype.getHighlight = function (includeHidden) {
            var result = this.getElementsWithTrait('highlighted', includeHidden);
            return result.length === 0 ? null : result[0];
        };
        TreeModel.prototype.isHighlighted = function (element) {
            var item = this.getItem(element);
            if (!item) {
                return false;
            }
            return item.hasTrait('highlighted');
        };
        TreeModel.prototype.select = function (element, eventPayload) {
            this.selectAll([element], eventPayload);
        };
        TreeModel.prototype.selectRange = function (fromElement, toElement, eventPayload) {
            var fromItem = this.getItem(fromElement);
            var toItem = this.getItem(toElement);
            if (!fromItem || !toItem) {
                return;
            }
            this.selectAll(getRange(fromItem, toItem), eventPayload);
        };
        TreeModel.prototype.deselectRange = function (fromElement, toElement, eventPayload) {
            var fromItem = this.getItem(fromElement);
            var toItem = this.getItem(toElement);
            if (!fromItem || !toItem) {
                return;
            }
            this.deselectAll(getRange(fromItem, toItem), eventPayload);
        };
        TreeModel.prototype.selectAll = function (elements, eventPayload) {
            this.addTraits('selected', elements);
            var eventData = { selection: this.getSelection(), payload: eventPayload };
            this.emit('selection', eventData);
        };
        TreeModel.prototype.deselect = function (element, eventPayload) {
            this.deselectAll([element], eventPayload);
        };
        TreeModel.prototype.deselectAll = function (elements, eventPayload) {
            this.removeTraits('selected', elements);
            var eventData = { selection: this.getSelection(), payload: eventPayload };
            this.emit('selection', eventData);
        };
        TreeModel.prototype.setSelection = function (elements, eventPayload) {
            this.setTraits('selected', elements);
            var eventData = { selection: this.getSelection(), payload: eventPayload };
            this.emit('selection', eventData);
        };
        TreeModel.prototype.toggleSelection = function (element, eventPayload) {
            this.toggleTrait('selected', element);
            var eventData = { selection: this.getSelection(), payload: eventPayload };
            this.emit('selection', eventData);
        };
        TreeModel.prototype.isSelected = function (element) {
            var item = this.getItem(element);
            if (!item) {
                return false;
            }
            return item.hasTrait('selected');
        };
        TreeModel.prototype.getSelection = function (includeHidden) {
            return this.getElementsWithTrait('selected', includeHidden);
        };
        TreeModel.prototype.selectNext = function (count, clearSelection, eventPayload) {
            if (count === void 0) { count = 1; }
            if (clearSelection === void 0) { clearSelection = true; }
            var selection = this.getSelection();
            var item = selection.length > 0 ? selection[0] : 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;
            }
            if (clearSelection) {
                this.setSelection([item], eventPayload);
            }
            else {
                this.select(item, eventPayload);
            }
        };
        TreeModel.prototype.selectPrevious = function (count, clearSelection, eventPayload) {
            if (count === void 0) { count = 1; }
            if (clearSelection === void 0) { clearSelection = true; }
            var selection = this.getSelection(), item = null, previousItem = null;
            if (selection.length === 0) {
                var nav = this.getNavigator(this.input);
                while (item = nav.next()) {
                    previousItem = item;
                }
                item = previousItem;
            }
            else {
                item = selection[0];
                var nav = this.getNavigator(item, false);
                for (var i = 0; i < count; i++) {
                    previousItem = nav.previous();
                    if (!previousItem) {
                        break;
                    }
                    item = previousItem;
                }
            }
            if (clearSelection) {
                this.setSelection([item], eventPayload);
            }
            else {
                this.select(item, eventPayload);
            }
        };
        TreeModel.prototype.selectParent = function (eventPayload, clearSelection) {
            if (clearSelection === void 0) { clearSelection = true; }
            var selection = this.getSelection();
            var item = selection.length > 0 ? selection[0] : this.input;
            var nav = this.getNavigator(item, false);
            var parent = nav.parent();
            if (parent) {
                if (clearSelection) {
                    this.setSelection([parent], eventPayload);
                }
                else {
                    this.select(parent, eventPayload);
                }
            }
        };
        TreeModel.prototype.setFocus = function (element, eventPayload) {
            this.setTraits('focused', element ? [element] : []);
            var eventData = { focus: this.getFocus(), payload: eventPayload };
            this.emit('focus', eventData);
        };
        TreeModel.prototype.isFocused = function (element) {
            var item = this.getItem(element);
            if (!item) {
                return false;
            }
            return item.hasTrait('focused');
        };
        TreeModel.prototype.getFocus = function (includeHidden) {
            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) {
                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.addTraits = function (trait, elements) {
            var items = this.traitsToItems[trait] || {};
            var item;
            for (var i = 0, len = elements.length; i < len; i++) {
                item = this.getItem(elements[i]);
                if (item) {
                    item.addTrait(trait);
                    items[item.id] = item;
                }
            }
            this.traitsToItems[trait] = items;
        };
        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.hasTrait = function (trait, element) {
            var item = this.getItem(element);
            return item && item.hasTrait(trait);
        };
        TreeModel.prototype.toggleTrait = function (trait, element) {
            var item = this.getItem(element);
            if (!item) {
                return;
            }
            if (item.hasTrait(trait)) {
                this.removeTraits(trait, [element]);
            }
            else {
                this.addTraits(trait, [element]);
            }
        };
        TreeModel.prototype.setTraits = function (trait, elements) {
            if (elements.length === 0) {
                this.removeTraits(trait, elements);
            }
            else {
                var items = {};
                var item;
                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;
                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;
            }
            _super.prototype.dispose.call(this);
        };
        return TreeModel;
    }(Events.EventEmitter));
    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[472/*vs/base/parts/tree/browser/treeViewModel*/], __M([1/*require*/,0/*exports*/,38/*vs/base/common/eventEmitter*/,107/*vs/base/common/iterator*/]), function (require, exports, eventEmitter_1, iterator_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var HeightMap = (function (_super) {
        __extends(HeightMap, _super);
        function HeightMap() {
            var _this = _super.call(this) || this;
            _this.heightMap = [];
            _this.indexes = {};
            return _this;
        }
        HeightMap.prototype.getTotalHeight = 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;
            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.emit('viewItem:create', { item: viewItem.model });
                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;
            var viewItem;
            var startIndex = null;
            var i;
            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) {
                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;
            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.itemsCount = function () {
            return this.heightMap.length;
        };
        HeightMap.prototype.itemAt = function (position) {
            return this.heightMap[this.indexAt(position)].model.id;
        };
        HeightMap.prototype.withItemsInRange = function (start, end, fn) {
            start = this.indexAt(start);
            end = this.indexAt(end);
            for (var i = start; i <= end; i++) {
                fn(this.heightMap[i].model.id);
            }
        };
        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 = null;
            this.indexes = null;
        };
        return HeightMap;
    }(eventEmitter_1.EventEmitter));
    exports.HeightMap = HeightMap;
});

define(__m[473/*vs/base/worker/defaultWorkerFactory*/], __M([1/*require*/,0/*exports*/,15/*vs/base/common/platform*/,197/*vs/base/common/worker/simpleWorker*/]), function (require, exports, platform_1, simpleWorker_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    // Option for hosts to overwrite the worker script url (used in the standalone editor)
    var getCrossOriginWorkerScriptUrl = environment('getWorkerUrl', null);
    function environment(name, fallback) {
        if (fallback === void 0) { fallback = false; }
        if (platform_1.globals.MonacoEnvironment && platform_1.globals.MonacoEnvironment.hasOwnProperty(name)) {
            return platform_1.globals.MonacoEnvironment[name];
        }
        return fallback;
    }
    function defaultGetWorkerUrl(workerId, label) {
        return require.toUrl('./' + workerId) + '#' + label;
    }
    var getWorkerUrl = getCrossOriginWorkerScriptUrl || defaultGetWorkerUrl;
    /**
     * A worker that uses HTML5 web workers so that is has
     * its own global scope and its own thread.
     */
    var WebWorker = (function () {
        function WebWorker(moduleId, id, label, onMessageCallback, onErrorCallback) {
            this.id = id;
            this.worker = new Worker(getWorkerUrl('workerMain.js', label));
            this.postMessage(moduleId);
            this.worker.onmessage = function (ev) {
                onMessageCallback(ev.data);
            };
            if (typeof this.worker.addEventListener === 'function') {
                this.worker.addEventListener('error', onErrorCallback);
            }
        }
        WebWorker.prototype.getId = function () {
            return this.id;
        };
        WebWorker.prototype.postMessage = function (msg) {
            if (this.worker) {
                this.worker.postMessage(msg);
            }
        };
        WebWorker.prototype.dispose = function () {
            this.worker.terminate();
            this.worker = null;
        };
        return WebWorker;
    }());
    var DefaultWorkerFactory = (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[484/*vs/css!vs/base/browser/builder*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});










define(__m[52/*vs/base/browser/builder*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,29/*vs/base/common/types*/,3/*vs/base/common/lifecycle*/,9/*vs/base/common/strings*/,72/*vs/base/common/assert*/,4/*vs/base/browser/dom*/,484/*vs/css!vs/base/browser/builder*/]), function (require, exports, winjs_base_1, types, lifecycle_1, strings, assert, DOM) {
    /*---------------------------------------------------------------------------------------------
     *  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 });
    /**
     * Create a new builder from the element that is uniquely identified by the given identifier. If the
     *  second parameter "offdom" is set to true, the created elements will only be added to the provided
     *  element when the build() method is called.
     */
    function withElementById(id, offdom) {
        assert.ok(types.isString(id), 'Expected String as parameter');
        var element = document.getElementById(id);
        if (element) {
            return new Builder(element, offdom);
        }
        return null;
    }
    exports.withElementById = withElementById;
    exports.Build = {
        withElementById: withElementById
    };
    // --- Implementation starts here
    var MS_DATA_KEY = '_msDataKey';
    var DATA_BINDING_ID = '__$binding';
    var LISTENER_BINDING_ID = '__$listeners';
    var VISIBILITY_BINDING_ID = '__$visibility';
    var Position = (function () {
        function Position(x, y) {
            this.x = x;
            this.y = y;
        }
        return Position;
    }());
    exports.Position = Position;
    var Box = (function () {
        function Box(top, right, bottom, left) {
            this.top = top;
            this.right = right;
            this.bottom = bottom;
            this.left = left;
        }
        return Box;
    }());
    exports.Box = Box;
    var Dimension = (function () {
        function Dimension(width, height) {
            this.width = width;
            this.height = height;
        }
        Dimension.prototype.substract = function (box) {
            return new Dimension(this.width - box.left - box.right, this.height - box.top - box.bottom);
        };
        return Dimension;
    }());
    exports.Dimension = Dimension;
    function data(element) {
        if (!element[MS_DATA_KEY]) {
            element[MS_DATA_KEY] = {};
        }
        return element[MS_DATA_KEY];
    }
    function hasData(element) {
        return !!element[MS_DATA_KEY];
    }
    /**
     *  Wraps around the provided element to manipulate it and add more child elements.
     */
    var Builder = (function () {
        function Builder(element, offdom) {
            this.offdom = offdom;
            this.container = element;
            this.currentElement = element;
            this.createdElements = [];
            this.toUnbind = {};
            this.captureToUnbind = {};
        }
        /**
         *  Returns a new builder that lets the current HTML Element of this builder be the container
         *  for future additions on the builder.
         */
        Builder.prototype.asContainer = function () {
            return withBuilder(this, this.offdom);
        };
        /**
         *  Clones the builder providing the same properties as this one.
         */
        Builder.prototype.clone = function () {
            var builder = new Builder(this.container, this.offdom);
            builder.currentElement = this.currentElement;
            builder.createdElements = this.createdElements;
            builder.captureToUnbind = this.captureToUnbind;
            builder.toUnbind = this.toUnbind;
            return builder;
        };
        Builder.prototype.and = function (obj) {
            // Convert HTMLElement to Builder as necessary
            if (!(obj instanceof Builder) && !(obj instanceof MultiBuilder)) {
                obj = new Builder(obj, this.offdom);
            }
            // Wrap Builders into MultiBuilder
            var builders = [this];
            if (obj instanceof MultiBuilder) {
                for (var i = 0; i < obj.length; i++) {
                    builders.push(obj.item(i));
                }
            }
            else {
                builders.push(obj);
            }
            return new MultiBuilder(builders);
        };
        Builder.prototype.build = function (container, index) {
            assert.ok(this.offdom, 'This builder was not created off-dom, so build() can not be called.');
            // Use builders own container if present
            if (!container) {
                container = this.container;
            }
            else if (container instanceof Builder) {
                container = container.getHTMLElement();
            }
            assert.ok(container, 'Builder can only be build() with a container provided.');
            assert.ok(DOM.isHTMLElement(container), 'The container must either be a HTMLElement or a Builder.');
            var htmlContainer = container;
            // Append
            var i, len;
            var childNodes = htmlContainer.childNodes;
            if (types.isNumber(index) && index < childNodes.length) {
                for (i = 0, len = this.createdElements.length; i < len; i++) {
                    htmlContainer.insertBefore(this.createdElements[i], childNodes[index++]);
                }
            }
            else {
                for (i = 0, len = this.createdElements.length; i < len; i++) {
                    htmlContainer.appendChild(this.createdElements[i]);
                }
            }
            return this;
        };
        Builder.prototype.appendTo = function (container, index) {
            // Use builders own container if present
            if (!container) {
                container = this.container;
            }
            else if (container instanceof Builder) {
                container = container.getHTMLElement();
            }
            assert.ok(container, 'Builder can only be build() with a container provided.');
            assert.ok(DOM.isHTMLElement(container), 'The container must either be a HTMLElement or a Builder.');
            var htmlContainer = container;
            // Remove node from parent, if needed
            if (this.currentElement.parentNode) {
                this.currentElement.parentNode.removeChild(this.currentElement);
            }
            var childNodes = htmlContainer.childNodes;
            if (types.isNumber(index) && index < childNodes.length) {
                htmlContainer.insertBefore(this.currentElement, childNodes[index]);
            }
            else {
                htmlContainer.appendChild(this.currentElement);
            }
            return this;
        };
        Builder.prototype.append = function (child, index) {
            assert.ok(child, 'Need a child to append');
            if (DOM.isHTMLElement(child)) {
                child = withElement(child);
            }
            assert.ok(child instanceof Builder || child instanceof MultiBuilder, 'Need a child to append');
            child.appendTo(this, index);
            return this;
        };
        /**
         *  Removes the current element of this builder from its parent node.
         */
        Builder.prototype.offDOM = function () {
            if (this.currentElement.parentNode) {
                this.currentElement.parentNode.removeChild(this.currentElement);
            }
            return this;
        };
        /**
         *  Returns the HTML Element the builder is currently active on.
         */
        Builder.prototype.getHTMLElement = function () {
            return this.currentElement;
        };
        /**
         *  Returns the HTML Element the builder is building in.
         */
        Builder.prototype.getContainer = function () {
            return this.container;
        };
        // HTML Elements
        /**
         *  Creates a new element of this kind as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.div = function (attributes, fn) {
            return this.doElement('div', attributes, fn);
        };
        /**
         *  Creates a new element of this kind as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.p = function (attributes, fn) {
            return this.doElement('p', attributes, fn);
        };
        /**
         *  Creates a new element of this kind as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.ul = function (attributes, fn) {
            return this.doElement('ul', attributes, fn);
        };
        /**
         *  Creates a new element of this kind as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.ol = function (attributes, fn) {
            return this.doElement('ol', attributes, fn);
        };
        /**
         *  Creates a new element of this kind as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.li = function (attributes, fn) {
            return this.doElement('li', attributes, fn);
        };
        /**
         *  Creates a new element of this kind as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.span = function (attributes, fn) {
            return this.doElement('span', attributes, fn);
        };
        /**
         *  Creates a new element of this kind as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.img = function (attributes, fn) {
            return this.doElement('img', attributes, fn);
        };
        /**
         *  Creates a new element of this kind as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.a = function (attributes, fn) {
            return this.doElement('a', attributes, fn);
        };
        /**
         *  Creates a new element of this kind as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.header = function (attributes, fn) {
            return this.doElement('header', attributes, fn);
        };
        /**
         *  Creates a new element of this kind as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.section = function (attributes, fn) {
            return this.doElement('section', attributes, fn);
        };
        /**
         *  Creates a new element of this kind as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.footer = function (attributes, fn) {
            return this.doElement('footer', attributes, fn);
        };
        /**
         *  Creates a new element of given tag name as child of the current element or parent.
         *  Accepts an object literal as first parameter that can be used to describe the
         *  attributes of the element.
         *  Accepts a function as second parameter that can be used to create child elements
         *  of the element. The function will be called with a new builder created with the
         *  provided element.
         */
        Builder.prototype.element = function (name, attributes, fn) {
            return this.doElement(name, attributes, fn);
        };
        Builder.prototype.doElement = function (name, attributesOrFn, fn) {
            // Create Element
            var element = document.createElement(name);
            this.currentElement = element;
            // Off-DOM: Remember in array of created elements
            if (this.offdom) {
                this.createdElements.push(element);
            }
            // Object (apply properties as attributes to HTML element)
            if (types.isObject(attributesOrFn)) {
                this.attr(attributesOrFn);
            }
            // Support second argument being function
            if (types.isFunction(attributesOrFn)) {
                fn = attributesOrFn;
            }
            // Apply Functions (Elements created in Functions will be added as child to current element)
            if (types.isFunction(fn)) {
                var builder = new Builder(element);
                fn.call(builder, builder); // Set both 'this' and the first parameter to the new builder
            }
            // Add to parent
            if (!this.offdom) {
                this.container.appendChild(element);
            }
            return this;
        };
        /**
         *  Calls focus() on the current HTML element;
         */
        Builder.prototype.domFocus = function () {
            this.currentElement.focus();
            return this;
        };
        /**
         *  Returns true if the current element of this builder is the active element.
         */
        Builder.prototype.hasFocus = function () {
            var activeElement = document.activeElement;
            return (activeElement === this.currentElement);
        };
        /**
         *  Calls select() on the current HTML element;
         */
        Builder.prototype.domSelect = function (range) {
            if (range === void 0) { range = null; }
            var input = this.currentElement;
            input.select();
            if (range) {
                input.setSelectionRange(range.start, range.end);
            }
            return this;
        };
        /**
         *  Calls blur() on the current HTML element;
         */
        Builder.prototype.domBlur = function () {
            this.currentElement.blur();
            return this;
        };
        /**
         *  Calls click() on the current HTML element;
         */
        Builder.prototype.domClick = function () {
            this.currentElement.click();
            return this;
        };
        Builder.prototype.on = function (arg1, fn, listenerToUnbindContainer, useCapture) {
            var _this = this;
            // Event Type Array
            if (types.isArray(arg1)) {
                arg1.forEach(function (type) {
                    _this.on(type, fn, listenerToUnbindContainer, useCapture);
                });
            }
            else {
                var type = arg1;
                // Add Listener
                var unbind_1 = DOM.addDisposableListener(this.currentElement, type, function (e) {
                    fn(e, _this, unbind_1); // Pass in Builder as Second Argument
                }, useCapture || false);
                // Remember for off() use
                if (useCapture) {
                    if (!this.captureToUnbind[type]) {
                        this.captureToUnbind[type] = [];
                    }
                    this.captureToUnbind[type].push(unbind_1);
                }
                else {
                    if (!this.toUnbind[type]) {
                        this.toUnbind[type] = [];
                    }
                    this.toUnbind[type].push(unbind_1);
                }
                // Bind to Element
                var listenerBinding = this.getProperty(LISTENER_BINDING_ID, []);
                listenerBinding.push(unbind_1);
                this.setProperty(LISTENER_BINDING_ID, listenerBinding);
                // Add to Array if passed in
                if (listenerToUnbindContainer && types.isArray(listenerToUnbindContainer)) {
                    listenerToUnbindContainer.push(unbind_1);
                }
            }
            return this;
        };
        Builder.prototype.off = function (arg1, useCapture) {
            var _this = this;
            // Event Type Array
            if (types.isArray(arg1)) {
                arg1.forEach(function (type) {
                    _this.off(type);
                });
            }
            else {
                var type = arg1;
                if (useCapture) {
                    if (this.captureToUnbind[type]) {
                        this.captureToUnbind[type] = lifecycle_1.dispose(this.captureToUnbind[type]);
                    }
                }
                else {
                    if (this.toUnbind[type]) {
                        this.toUnbind[type] = lifecycle_1.dispose(this.toUnbind[type]);
                    }
                }
            }
            return this;
        };
        Builder.prototype.once = function (arg1, fn, listenerToUnbindContainer, useCapture) {
            var _this = this;
            // Event Type Array
            if (types.isArray(arg1)) {
                arg1.forEach(function (type) {
                    _this.once(type, fn);
                });
            }
            else {
                var type = arg1;
                // Add Listener
                var unbind_2 = DOM.addDisposableListener(this.currentElement, type, function (e) {
                    fn(e, _this, unbind_2); // Pass in Builder as Second Argument
                    unbind_2.dispose();
                }, useCapture || false);
                // Add to Array if passed in
                if (listenerToUnbindContainer && types.isArray(listenerToUnbindContainer)) {
                    listenerToUnbindContainer.push(unbind_2);
                }
            }
            return this;
        };
        Builder.prototype.preventDefault = function (arg1, cancelBubble, listenerToUnbindContainer, useCapture) {
            var fn = function (e) {
                e.preventDefault();
                if (cancelBubble) {
                    if (e.stopPropagation) {
                        e.stopPropagation();
                    }
                    else {
                        e.cancelBubble = true;
                    }
                }
            };
            return this.on(arg1, fn, listenerToUnbindContainer, useCapture);
        };
        Builder.prototype.attr = function (firstP, secondP) {
            // Apply Object Literal to Attributes of Element
            if (types.isObject(firstP)) {
                for (var prop in firstP) {
                    if (firstP.hasOwnProperty(prop)) {
                        var value = firstP[prop];
                        this.doSetAttr(prop, value);
                    }
                }
                return this;
            }
            // Get Attribute Value
            if (types.isString(firstP) && !types.isString(secondP)) {
                return this.currentElement.getAttribute(firstP);
            }
            // Set Attribute Value
            if (types.isString(firstP)) {
                if (!types.isString(secondP)) {
                    secondP = String(secondP);
                }
                this.doSetAttr(firstP, secondP);
            }
            return this;
        };
        Builder.prototype.doSetAttr = function (prop, value) {
            if (prop === 'class') {
                prop = 'addClass'; // Workaround for the issue that a function name can not be 'class' in ES
            }
            if (this[prop]) {
                if (types.isArray(value)) {
                    this[prop].apply(this, value);
                }
                else {
                    this[prop].call(this, value);
                }
            }
            else {
                this.currentElement.setAttribute(prop, value);
            }
        };
        /**
         * Removes an attribute by the given name.
         */
        Builder.prototype.removeAttribute = function (prop) {
            this.currentElement.removeAttribute(prop);
        };
        /**
         *  Sets the id attribute to the value provided for the current HTML element of the builder.
         */
        Builder.prototype.id = function (id) {
            this.currentElement.setAttribute('id', id);
            return this;
        };
        /**
         *  Sets the src attribute to the value provided for the current HTML element of the builder.
         */
        Builder.prototype.src = function (src) {
            this.currentElement.setAttribute('src', src);
            return this;
        };
        /**
         *  Sets the href attribute to the value provided for the current HTML element of the builder.
         */
        Builder.prototype.href = function (href) {
            this.currentElement.setAttribute('href', href);
            return this;
        };
        /**
         *  Sets the title attribute to the value provided for the current HTML element of the builder.
         */
        Builder.prototype.title = function (title) {
            this.currentElement.setAttribute('title', title);
            return this;
        };
        /**
         *  Sets the name attribute to the value provided for the current HTML element of the builder.
         */
        Builder.prototype.name = function (name) {
            this.currentElement.setAttribute('name', name);
            return this;
        };
        /**
         *  Sets the type attribute to the value provided for the current HTML element of the builder.
         */
        Builder.prototype.type = function (type) {
            this.currentElement.setAttribute('type', type);
            return this;
        };
        /**
         *  Sets the value attribute to the value provided for the current HTML element of the builder.
         */
        Builder.prototype.value = function (value) {
            this.currentElement.setAttribute('value', value);
            return this;
        };
        /**
         *  Sets the alt attribute to the value provided for the current HTML element of the builder.
         */
        Builder.prototype.alt = function (alt) {
            this.currentElement.setAttribute('alt', alt);
            return this;
        };
        /**
         *  Sets the name draggable to the value provided for the current HTML element of the builder.
         */
        Builder.prototype.draggable = function (isDraggable) {
            this.currentElement.setAttribute('draggable', isDraggable ? 'true' : 'false');
            return this;
        };
        /**
         *  Sets the tabindex attribute to the value provided for the current HTML element of the builder.
         */
        Builder.prototype.tabindex = function (index) {
            this.currentElement.setAttribute('tabindex', index.toString());
            return this;
        };
        Builder.prototype.style = function (firstP, secondP) {
            // Apply Object Literal to Styles of Element
            if (types.isObject(firstP)) {
                for (var prop in firstP) {
                    if (firstP.hasOwnProperty(prop)) {
                        var value = firstP[prop];
                        this.doSetStyle(prop, value);
                    }
                }
                return this;
            }
            var hasFirstP = types.isString(firstP);
            // Get Style Value
            if (hasFirstP && types.isUndefined(secondP)) {
                return this.currentElement.style[this.cssKeyToJavaScriptProperty(firstP)];
            }
            else if (hasFirstP) {
                this.doSetStyle(firstP, secondP);
            }
            return this;
        };
        Builder.prototype.doSetStyle = function (key, value) {
            if (key.indexOf('-') >= 0) {
                var segments = key.split('-');
                key = segments[0];
                for (var i = 1; i < segments.length; i++) {
                    var segment = segments[i];
                    key = key + segment.charAt(0).toUpperCase() + segment.substr(1);
                }
            }
            this.currentElement.style[this.cssKeyToJavaScriptProperty(key)] = value;
        };
        Builder.prototype.cssKeyToJavaScriptProperty = function (key) {
            // Automagically convert dashes as they are not allowed when programmatically
            // setting a CSS style property
            if (key.indexOf('-') >= 0) {
                var segments = key.split('-');
                key = segments[0];
                for (var i = 1; i < segments.length; i++) {
                    var segment = segments[i];
                    key = key + segment.charAt(0).toUpperCase() + segment.substr(1);
                }
            }
            else if (key === 'float') {
                key = 'cssFloat';
            }
            return key;
        };
        /**
         *  Returns the computed CSS style for the current HTML element of the builder.
         */
        Builder.prototype.getComputedStyle = function () {
            return DOM.getComputedStyle(this.currentElement);
        };
        /**
         *  Adds the variable list of arguments as class names to the current HTML element of the builder.
         */
        Builder.prototype.addClass = function () {
            var _this = this;
            var classes = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                classes[_i] = arguments[_i];
            }
            classes.forEach(function (nameValue) {
                var names = nameValue.split(' ');
                names.forEach(function (name) {
                    DOM.addClass(_this.currentElement, name);
                });
            });
            return this;
        };
        /**
         *  Sets the class name of the current HTML element of the builder to the provided className.
         *  If shouldAddClass is provided - for true class is added, for false class is removed.
         */
        Builder.prototype.setClass = function (className, shouldAddClass) {
            if (shouldAddClass === void 0) { shouldAddClass = null; }
            if (shouldAddClass === null) {
                this.currentElement.className = className;
            }
            else if (shouldAddClass) {
                this.addClass(className);
            }
            else {
                this.removeClass(className);
            }
            return this;
        };
        /**
         *  Returns whether the current HTML element of the builder has the provided class assigned.
         */
        Builder.prototype.hasClass = function (className) {
            return DOM.hasClass(this.currentElement, className);
        };
        /**
         *  Removes the variable list of arguments as class names from the current HTML element of the builder.
         */
        Builder.prototype.removeClass = function () {
            var _this = this;
            var classes = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                classes[_i] = arguments[_i];
            }
            classes.forEach(function (nameValue) {
                var names = nameValue.split(' ');
                names.forEach(function (name) {
                    DOM.removeClass(_this.currentElement, name);
                });
            });
            return this;
        };
        /**
         *  Sets the first class to the current HTML element of the builder if the second class is currently set
         *  and vice versa otherwise.
         */
        Builder.prototype.swapClass = function (classA, classB) {
            if (this.hasClass(classA)) {
                this.removeClass(classA);
                this.addClass(classB);
            }
            else {
                this.removeClass(classB);
                this.addClass(classA);
            }
            return this;
        };
        /**
         *  Adds or removes the provided className for the current HTML element of the builder.
         */
        Builder.prototype.toggleClass = function (className) {
            if (this.hasClass(className)) {
                this.removeClass(className);
            }
            else {
                this.addClass(className);
            }
            return this;
        };
        /**
         *  Sets the CSS property color.
         */
        Builder.prototype.color = function (color) {
            this.currentElement.style.color = color;
            return this;
        };
        /**
         *  Sets the CSS property background.
         */
        Builder.prototype.background = function (color) {
            this.currentElement.style.backgroundColor = color;
            return this;
        };
        Builder.prototype.padding = function (top, right, bottom, left) {
            if (types.isString(top) && top.indexOf(' ') >= 0) {
                return this.padding.apply(this, top.split(' '));
            }
            if (!types.isUndefinedOrNull(top)) {
                this.currentElement.style.paddingTop = this.toPixel(top);
            }
            if (!types.isUndefinedOrNull(right)) {
                this.currentElement.style.paddingRight = this.toPixel(right);
            }
            if (!types.isUndefinedOrNull(bottom)) {
                this.currentElement.style.paddingBottom = this.toPixel(bottom);
            }
            if (!types.isUndefinedOrNull(left)) {
                this.currentElement.style.paddingLeft = this.toPixel(left);
            }
            return this;
        };
        Builder.prototype.margin = function (top, right, bottom, left) {
            if (types.isString(top) && top.indexOf(' ') >= 0) {
                return this.margin.apply(this, top.split(' '));
            }
            if (!types.isUndefinedOrNull(top)) {
                this.currentElement.style.marginTop = this.toPixel(top);
            }
            if (!types.isUndefinedOrNull(right)) {
                this.currentElement.style.marginRight = this.toPixel(right);
            }
            if (!types.isUndefinedOrNull(bottom)) {
                this.currentElement.style.marginBottom = this.toPixel(bottom);
            }
            if (!types.isUndefinedOrNull(left)) {
                this.currentElement.style.marginLeft = this.toPixel(left);
            }
            return this;
        };
        Builder.prototype.position = function (top, right, bottom, left, position) {
            if (types.isString(top) && top.indexOf(' ') >= 0) {
                return this.position.apply(this, top.split(' '));
            }
            if (!types.isUndefinedOrNull(top)) {
                this.currentElement.style.top = this.toPixel(top);
            }
            if (!types.isUndefinedOrNull(right)) {
                this.currentElement.style.right = this.toPixel(right);
            }
            if (!types.isUndefinedOrNull(bottom)) {
                this.currentElement.style.bottom = this.toPixel(bottom);
            }
            if (!types.isUndefinedOrNull(left)) {
                this.currentElement.style.left = this.toPixel(left);
            }
            if (!position) {
                position = 'absolute';
            }
            this.currentElement.style.position = position;
            return this;
        };
        Builder.prototype.size = function (width, height) {
            if (types.isString(width) && width.indexOf(' ') >= 0) {
                return this.size.apply(this, width.split(' '));
            }
            if (!types.isUndefinedOrNull(width)) {
                this.currentElement.style.width = this.toPixel(width);
            }
            if (!types.isUndefinedOrNull(height)) {
                this.currentElement.style.height = this.toPixel(height);
            }
            return this;
        };
        Builder.prototype.minSize = function (width, height) {
            if (types.isString(width) && width.indexOf(' ') >= 0) {
                return this.minSize.apply(this, width.split(' '));
            }
            if (!types.isUndefinedOrNull(width)) {
                this.currentElement.style.minWidth = this.toPixel(width);
            }
            if (!types.isUndefinedOrNull(height)) {
                this.currentElement.style.minHeight = this.toPixel(height);
            }
            return this;
        };
        Builder.prototype.maxSize = function (width, height) {
            if (types.isString(width) && width.indexOf(' ') >= 0) {
                return this.maxSize.apply(this, width.split(' '));
            }
            if (!types.isUndefinedOrNull(width)) {
                this.currentElement.style.maxWidth = this.toPixel(width);
            }
            if (!types.isUndefinedOrNull(height)) {
                this.currentElement.style.maxHeight = this.toPixel(height);
            }
            return this;
        };
        /**
         *  Sets the CSS property float.
         */
        Builder.prototype.float = function (float) {
            this.currentElement.style.cssFloat = float;
            return this;
        };
        /**
         *  Sets the CSS property clear.
         */
        Builder.prototype.clear = function (clear) {
            this.currentElement.style.clear = clear;
            return this;
        };
        /**
         *  Sets the CSS property for fonts back to default.
         */
        Builder.prototype.normal = function () {
            this.currentElement.style.fontStyle = 'normal';
            this.currentElement.style.fontWeight = 'normal';
            this.currentElement.style.textDecoration = 'none';
            return this;
        };
        /**
         *  Sets the CSS property font-style to italic.
         */
        Builder.prototype.italic = function () {
            this.currentElement.style.fontStyle = 'italic';
            return this;
        };
        /**
         *  Sets the CSS property font-weight to bold.
         */
        Builder.prototype.bold = function () {
            this.currentElement.style.fontWeight = 'bold';
            return this;
        };
        /**
         *  Sets the CSS property text-decoration to underline.
         */
        Builder.prototype.underline = function () {
            this.currentElement.style.textDecoration = 'underline';
            return this;
        };
        /**
         *  Sets the CSS property overflow.
         */
        Builder.prototype.overflow = function (overflow) {
            this.currentElement.style.overflow = overflow;
            return this;
        };
        /**
         *  Sets the CSS property display.
         */
        Builder.prototype.display = function (display) {
            this.currentElement.style.display = display;
            return this;
        };
        Builder.prototype.disable = function () {
            this.currentElement.setAttribute('disabled', 'disabled');
            return this;
        };
        Builder.prototype.enable = function () {
            this.currentElement.removeAttribute('disabled');
            return this;
        };
        /**
         *  Shows the current element of the builder.
         */
        Builder.prototype.show = function () {
            if (this.hasClass('builder-hidden')) {
                this.removeClass('builder-hidden');
            }
            this.attr('aria-hidden', 'false');
            // Cancel any pending showDelayed() invocation
            this.cancelVisibilityPromise();
            return this;
        };
        /**
         *  Shows the current builder element after the provided delay. If the builder
         *  was set to hidden using the hide() method before this method executed, the
         *  function will return without showing the current element. This is useful to
         *  only show the element when a specific delay is reached (e.g. for a long running
         *  operation.
         */
        Builder.prototype.showDelayed = function (delay) {
            var _this = this;
            // Cancel any pending showDelayed() invocation
            this.cancelVisibilityPromise();
            var promise = winjs_base_1.TPromise.timeout(delay);
            this.setProperty(VISIBILITY_BINDING_ID, promise);
            promise.done(function () {
                _this.removeProperty(VISIBILITY_BINDING_ID);
                _this.show();
            });
            return this;
        };
        /**
         *  Hides the current element of the builder.
         */
        Builder.prototype.hide = function () {
            if (!this.hasClass('builder-hidden')) {
                this.addClass('builder-hidden');
            }
            this.attr('aria-hidden', 'true');
            // Cancel any pending showDelayed() invocation
            this.cancelVisibilityPromise();
            return this;
        };
        /**
         *  Returns true if the current element of the builder is hidden.
         */
        Builder.prototype.isHidden = function () {
            return this.hasClass('builder-hidden') || this.currentElement.style.display === 'none';
        };
        /**
         *  Toggles visibility of the current element of the builder.
         */
        Builder.prototype.toggleVisibility = function () {
            // Cancel any pending showDelayed() invocation
            this.cancelVisibilityPromise();
            this.swapClass('builder-visible', 'builder-hidden');
            if (this.isHidden()) {
                this.attr('aria-hidden', 'true');
            }
            else {
                this.attr('aria-hidden', 'false');
            }
            return this;
        };
        Builder.prototype.cancelVisibilityPromise = function () {
            var promise = this.getProperty(VISIBILITY_BINDING_ID);
            if (promise) {
                promise.cancel();
                this.removeProperty(VISIBILITY_BINDING_ID);
            }
        };
        Builder.prototype.border = function (width, style, color) {
            if (types.isString(width) && width.indexOf(' ') >= 0) {
                return this.border.apply(this, width.split(' '));
            }
            this.currentElement.style.borderWidth = this.toPixel(width);
            if (color) {
                this.currentElement.style.borderColor = color;
            }
            if (style) {
                this.currentElement.style.borderStyle = style;
            }
            return this;
        };
        Builder.prototype.borderTop = function (width, style, color) {
            if (types.isString(width) && width.indexOf(' ') >= 0) {
                return this.borderTop.apply(this, width.split(' '));
            }
            this.currentElement.style.borderTopWidth = this.toPixel(width);
            if (color) {
                this.currentElement.style.borderTopColor = color;
            }
            if (style) {
                this.currentElement.style.borderTopStyle = style;
            }
            return this;
        };
        Builder.prototype.borderBottom = function (width, style, color) {
            if (types.isString(width) && width.indexOf(' ') >= 0) {
                return this.borderBottom.apply(this, width.split(' '));
            }
            this.currentElement.style.borderBottomWidth = this.toPixel(width);
            if (color) {
                this.currentElement.style.borderBottomColor = color;
            }
            if (style) {
                this.currentElement.style.borderBottomStyle = style;
            }
            return this;
        };
        Builder.prototype.borderLeft = function (width, style, color) {
            if (types.isString(width) && width.indexOf(' ') >= 0) {
                return this.borderLeft.apply(this, width.split(' '));
            }
            this.currentElement.style.borderLeftWidth = this.toPixel(width);
            if (color) {
                this.currentElement.style.borderLeftColor = color;
            }
            if (style) {
                this.currentElement.style.borderLeftStyle = style;
            }
            return this;
        };
        Builder.prototype.borderRight = function (width, style, color) {
            if (types.isString(width) && width.indexOf(' ') >= 0) {
                return this.borderRight.apply(this, width.split(' '));
            }
            this.currentElement.style.borderRightWidth = this.toPixel(width);
            if (color) {
                this.currentElement.style.borderRightColor = color;
            }
            if (style) {
                this.currentElement.style.borderRightStyle = style;
            }
            return this;
        };
        /**
         *  Sets the CSS property text-align.
         */
        Builder.prototype.textAlign = function (textAlign) {
            this.currentElement.style.textAlign = textAlign;
            return this;
        };
        /**
         *  Sets the CSS property vertical-align.
         */
        Builder.prototype.verticalAlign = function (valign) {
            this.currentElement.style.verticalAlign = valign;
            return this;
        };
        Builder.prototype.toPixel = function (obj) {
            if (obj.toString().indexOf('px') === -1) {
                return obj.toString() + 'px';
            }
            return obj;
        };
        /**
         *  Sets the innerHTML attribute.
         */
        Builder.prototype.innerHtml = function (html, append) {
            if (append) {
                this.currentElement.innerHTML += html;
            }
            else {
                this.currentElement.innerHTML = html;
            }
            return this;
        };
        /**
         *  Sets the textContent property of the element.
         *  All HTML special characters will be escaped.
         */
        Builder.prototype.text = function (text, append) {
            if (append) {
                // children is child Elements versus childNodes includes textNodes
                if (this.currentElement.children.length === 0) {
                    this.currentElement.textContent += text;
                }
                else {
                    // if there are elements inside this node, append the string as a new text node
                    // to avoid wiping out the innerHTML and replacing it with only text content
                    this.currentElement.appendChild(document.createTextNode(text));
                }
            }
            else {
                this.currentElement.textContent = text;
            }
            return this;
        };
        /**
         *  Sets the innerHTML attribute in escaped form.
         */
        Builder.prototype.safeInnerHtml = function (html, append) {
            return this.innerHtml(strings.escape(html), append);
        };
        /**
         *  Adds the provided object as property to the current element. Call getBinding()
         *  to retrieve it again.
         */
        Builder.prototype.bind = function (object) {
            bindElement(this.currentElement, object);
            return this;
        };
        /**
         *  Removes the binding of the current element.
         */
        Builder.prototype.unbind = function () {
            unbindElement(this.currentElement);
            return this;
        };
        /**
         *  Returns the object that was passed into the bind() call.
         */
        Builder.prototype.getBinding = function () {
            return getBindingFromElement(this.currentElement);
        };
        /**
         *  Allows to store arbritary data into the current element.
         */
        Builder.prototype.setProperty = function (key, value) {
            setPropertyOnElement(this.currentElement, key, value);
            return this;
        };
        /**
         *  Allows to get arbritary data from the current element.
         */
        Builder.prototype.getProperty = function (key, fallback) {
            return getPropertyFromElement(this.currentElement, key, fallback);
        };
        /**
         *  Removes a property from the current element that is stored under the given key.
         */
        Builder.prototype.removeProperty = function (key) {
            if (hasData(this.currentElement)) {
                delete data(this.currentElement)[key];
            }
            return this;
        };
        /**
         *  Returns a new builder with the parent element of the current element of the builder.
         */
        Builder.prototype.parent = function (offdom) {
            assert.ok(!this.offdom, 'Builder was created with offdom = true and thus has no parent set');
            return withElement(this.currentElement.parentNode, offdom);
        };
        /**
         *  Returns a new builder with all child elements of the current element of the builder.
         */
        Builder.prototype.children = function (offdom) {
            var children = this.currentElement.children;
            var builders = [];
            for (var i = 0; i < children.length; i++) {
                builders.push(withElement(children.item(i), offdom));
            }
            return new MultiBuilder(builders);
        };
        /**
         * Returns a new builder with the child at the given index.
         */
        Builder.prototype.child = function (index) {
            if (index === void 0) { index = 0; }
            var children = this.currentElement.children;
            return withElement(children.item(index));
        };
        /**
         *  Removes the current HTMLElement from the given builder from this builder if this builders
         *  current HTMLElement is the direct parent.
         */
        Builder.prototype.removeChild = function (builder) {
            if (this.currentElement === builder.parent().getHTMLElement()) {
                this.currentElement.removeChild(builder.getHTMLElement());
            }
            return this;
        };
        /**
         *  Returns a new builder with all elements matching the provided selector scoped to the
         *  current element of the builder. Use Build.withElementsBySelector() to run the selector
         *  over the entire DOM.
         *  The returned builder is an instance of array that can have 0 elements if the selector does not match any
         *  elements.
         */
        Builder.prototype.select = function (selector, offdom) {
            assert.ok(types.isString(selector), 'Expected String as parameter');
            var elements = this.currentElement.querySelectorAll(selector);
            var builders = [];
            for (var i = 0; i < elements.length; i++) {
                builders.push(withElement(elements.item(i), offdom));
            }
            return new MultiBuilder(builders);
        };
        /**
         *  Returns true if the current element of the builder matches the given selector and false otherwise.
         */
        Builder.prototype.matches = function (selector) {
            var element = this.currentElement;
            var matches = element.webkitMatchesSelector || element.mozMatchesSelector || element.msMatchesSelector || element.oMatchesSelector;
            return matches && matches.call(element, selector);
        };
        /**
         *  Returns true if the current element of the builder has no children.
         */
        Builder.prototype.isEmpty = function () {
            return !this.currentElement.childNodes || this.currentElement.childNodes.length === 0;
        };
        /**
         * Recurse through all descendant nodes and remove their data binding.
         */
        Builder.prototype.unbindDescendants = function (current) {
            if (current && current.children) {
                for (var i = 0, length_1 = current.children.length; i < length_1; i++) {
                    var element = current.children.item(i);
                    // Unbind
                    if (hasData(element)) {
                        // Listeners
                        var listeners = data(element)[LISTENER_BINDING_ID];
                        if (types.isArray(listeners)) {
                            while (listeners.length) {
                                listeners.pop().dispose();
                            }
                        }
                        // Delete Data Slot
                        delete element[MS_DATA_KEY];
                    }
                    // Recurse
                    this.unbindDescendants(element);
                }
            }
        };
        /**
         *  Removes all HTML elements from the current element of the builder. Will also clean up any
         *  event listners registered and also clear any data binding and properties stored
         *  to any child element.
         */
        Builder.prototype.empty = function () {
            this.unbindDescendants(this.currentElement);
            this.clearChildren();
            if (this.offdom) {
                this.createdElements = [];
            }
            return this;
        };
        /**
         *  Removes all HTML elements from the current element of the builder.
         */
        Builder.prototype.clearChildren = function () {
            // Remove Elements
            if (this.currentElement) {
                DOM.clearNode(this.currentElement);
            }
            return this;
        };
        /**
         *  Removes the current HTML element and all its children from its parent and unbinds
         *  all listeners and properties set to the data slots.
         */
        Builder.prototype.destroy = function () {
            if (this.currentElement) {
                // Remove from parent
                if (this.currentElement.parentNode) {
                    this.currentElement.parentNode.removeChild(this.currentElement);
                }
                // Empty to clear listeners and bindings from children
                this.empty();
                // Unbind
                if (hasData(this.currentElement)) {
                    // Listeners
                    var listeners = data(this.currentElement)[LISTENER_BINDING_ID];
                    if (types.isArray(listeners)) {
                        while (listeners.length) {
                            listeners.pop().dispose();
                        }
                    }
                    // Delete Data Slot
                    delete this.currentElement[MS_DATA_KEY];
                }
            }
            var type;
            for (type in this.toUnbind) {
                if (this.toUnbind.hasOwnProperty(type) && types.isArray(this.toUnbind[type])) {
                    this.toUnbind[type] = lifecycle_1.dispose(this.toUnbind[type]);
                }
            }
            for (type in this.captureToUnbind) {
                if (this.captureToUnbind.hasOwnProperty(type) && types.isArray(this.captureToUnbind[type])) {
                    this.captureToUnbind[type] = lifecycle_1.dispose(this.captureToUnbind[type]);
                }
            }
            // Nullify fields
            this.currentElement = null;
            this.container = null;
            this.offdom = null;
            this.createdElements = null;
            this.captureToUnbind = null;
            this.toUnbind = null;
        };
        /**
         *  Removes the current HTML element and all its children from its parent and unbinds
         *  all listeners and properties set to the data slots.
         */
        Builder.prototype.dispose = function () {
            this.destroy();
        };
        /**
         *  Gets the size (in pixels) of an element, including the margin.
         */
        Builder.prototype.getTotalSize = function () {
            var totalWidth = DOM.getTotalWidth(this.currentElement);
            var totalHeight = DOM.getTotalHeight(this.currentElement);
            return new Dimension(totalWidth, totalHeight);
        };
        /**
         *  Gets the size (in pixels) of the inside of the element, excluding the border and padding.
         */
        Builder.prototype.getContentSize = function () {
            var contentWidth = DOM.getContentWidth(this.currentElement);
            var contentHeight = DOM.getContentHeight(this.currentElement);
            return new Dimension(contentWidth, contentHeight);
        };
        /**
         *  Another variant of getting the inner dimensions of an element.
         */
        Builder.prototype.getClientArea = function () {
            // 0.) Try with DOM clientWidth / clientHeight
            if (this.currentElement !== document.body) {
                return new Dimension(this.currentElement.clientWidth, this.currentElement.clientHeight);
            }
            // 1.) Try innerWidth / innerHeight
            if (window.innerWidth && window.innerHeight) {
                return new Dimension(window.innerWidth, window.innerHeight);
            }
            // 2.) Try with document.body.clientWidth / document.body.clientHeigh
            if (document.body && document.body.clientWidth && document.body.clientWidth) {
                return new Dimension(document.body.clientWidth, document.body.clientHeight);
            }
            // 3.) Try with document.documentElement.clientWidth / document.documentElement.clientHeight
            if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) {
                return new Dimension(document.documentElement.clientWidth, document.documentElement.clientHeight);
            }
            throw new Error('Unable to figure out browser width and height');
        };
        return Builder;
    }());
    exports.Builder = Builder;
    /**
     *  The multi builder provides the same methods as the builder, but allows to call
     *  them on an array of builders.
     */
    var MultiBuilder = (function (_super) {
        __extends(MultiBuilder, _super);
        function MultiBuilder(builders) {
            var _this = this;
            assert.ok(types.isArray(builders) || builders instanceof MultiBuilder, 'Expected Array or MultiBuilder as parameter');
            _this = _super.call(this) || this;
            _this.length = 0;
            _this.builders = [];
            // Add Builders to Array
            if (types.isArray(builders)) {
                for (var i = 0; i < builders.length; i++) {
                    if (builders[i] instanceof HTMLElement) {
                        _this.push(withElement(builders[i]));
                    }
                    else {
                        _this.push(builders[i]);
                    }
                }
            }
            else {
                for (var i = 0; i < builders.length; i++) {
                    _this.push(builders.item(i));
                }
            }
            // Mixin Builder functions to operate on all builders
            var $outer = _this;
            var propertyFn = function (prop) {
                $outer[prop] = function () {
                    var args = Array.prototype.slice.call(arguments);
                    var returnValues;
                    var mergeBuilders = false;
                    for (var i = 0; i < $outer.length; i++) {
                        var res = $outer.item(i)[prop].apply($outer.item(i), args);
                        // Merge MultiBuilders into one
                        if (res instanceof MultiBuilder) {
                            if (!returnValues) {
                                returnValues = [];
                            }
                            mergeBuilders = true;
                            for (var j = 0; j < res.length; j++) {
                                returnValues.push(res.item(j));
                            }
                        }
                        else if (!types.isUndefined(res) && !(res instanceof Builder)) {
                            if (!returnValues) {
                                returnValues = [];
                            }
                            returnValues.push(res);
                        }
                    }
                    if (returnValues && mergeBuilders) {
                        return new MultiBuilder(returnValues);
                    }
                    return returnValues || $outer;
                };
            };
            for (var prop in Builder.prototype) {
                if (prop !== 'clone' && prop !== 'and') {
                    if (Builder.prototype.hasOwnProperty(prop) && types.isFunction(Builder.prototype[prop])) {
                        propertyFn(prop);
                    }
                }
            }
            return _this;
        }
        MultiBuilder.prototype.item = function (i) {
            return this.builders[i];
        };
        MultiBuilder.prototype.push = function () {
            var items = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                items[_i] = arguments[_i];
            }
            for (var i = 0; i < items.length; i++) {
                this.builders.push(items[i]);
            }
            this.length = this.builders.length;
        };
        MultiBuilder.prototype.pop = function () {
            var element = this.builders.pop();
            this.length = this.builders.length;
            return element;
        };
        MultiBuilder.prototype.concat = function (items) {
            var elements = this.builders.concat(items);
            this.length = this.builders.length;
            return elements;
        };
        MultiBuilder.prototype.shift = function () {
            var element = this.builders.shift();
            this.length = this.builders.length;
            return element;
        };
        MultiBuilder.prototype.unshift = function (item) {
            var res = this.builders.unshift(item);
            this.length = this.builders.length;
            return res;
        };
        MultiBuilder.prototype.slice = function (start, end) {
            var elements = this.builders.slice(start, end);
            this.length = this.builders.length;
            return elements;
        };
        MultiBuilder.prototype.splice = function (start, deleteCount) {
            var elements = this.builders.splice(start, deleteCount);
            this.length = this.builders.length;
            return elements;
        };
        MultiBuilder.prototype.clone = function () {
            return new MultiBuilder(this);
        };
        MultiBuilder.prototype.and = function (obj) {
            // Convert HTMLElement to Builder as necessary
            if (!(obj instanceof Builder) && !(obj instanceof MultiBuilder)) {
                obj = new Builder(obj);
            }
            var builders = [];
            if (obj instanceof MultiBuilder) {
                for (var i = 0; i < obj.length; i++) {
                    builders.push(obj.item(i));
                }
            }
            else {
                builders.push(obj);
            }
            this.push.apply(this, builders);
            return this;
        };
        return MultiBuilder;
    }(Builder));
    exports.MultiBuilder = MultiBuilder;
    function withBuilder(builder, offdom) {
        if (builder instanceof MultiBuilder) {
            return new MultiBuilder(builder);
        }
        return new Builder(builder.getHTMLElement(), offdom);
    }
    function withElement(element, offdom) {
        return new Builder(element, offdom);
    }
    function offDOM() {
        return new Builder(null, true);
    }
    // Binding functions
    /**
     *  Allows to store arbritary data into element.
     */
    function setPropertyOnElement(element, key, value) {
        data(element)[key] = value;
    }
    exports.setPropertyOnElement = setPropertyOnElement;
    /**
     *  Allows to get arbritary data from element.
     */
    function getPropertyFromElement(element, key, fallback) {
        if (hasData(element)) {
            var value = data(element)[key];
            if (!types.isUndefined(value)) {
                return value;
            }
        }
        return fallback;
    }
    exports.getPropertyFromElement = getPropertyFromElement;
    /**
     *  Removes a property from an element.
     */
    function removePropertyFromElement(element, key) {
        if (hasData(element)) {
            delete data(element)[key];
        }
    }
    exports.removePropertyFromElement = removePropertyFromElement;
    /**
     *  Adds the provided object as property to the given element. Call getBinding()
     *  to retrieve it again.
     */
    function bindElement(element, object) {
        setPropertyOnElement(element, DATA_BINDING_ID, object);
    }
    exports.bindElement = bindElement;
    /**
     *  Removes the binding of the given element.
     */
    function unbindElement(element) {
        removePropertyFromElement(element, DATA_BINDING_ID);
    }
    exports.unbindElement = unbindElement;
    /**
     *  Returns the object that was passed into the bind() call for the element.
     */
    function getBindingFromElement(element) {
        return getPropertyFromElement(element, DATA_BINDING_ID);
    }
    exports.getBindingFromElement = getBindingFromElement;
    exports.Binding = {
        setPropertyOnElement: setPropertyOnElement,
        getPropertyFromElement: getPropertyFromElement,
        removePropertyFromElement: removePropertyFromElement,
        bindElement: bindElement,
        unbindElement: unbindElement,
        getBindingFromElement: getBindingFromElement
    };
    var SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((.([\w\-]+))*)/;
    exports.$ = function (arg) {
        // Off-DOM use
        if (types.isUndefined(arg)) {
            return offDOM();
        }
        // Falsified values cause error otherwise
        if (!arg) {
            throw new Error('Bad use of $');
        }
        // Wrap the given element
        if (DOM.isHTMLElement(arg) || arg === window) {
            return withElement(arg);
        }
        // Wrap the given builders
        if (types.isArray(arg)) {
            return new MultiBuilder(arg);
        }
        // Wrap the given builder
        if (arg instanceof Builder) {
            return withBuilder(arg);
        }
        if (types.isString(arg)) {
            // Use the argument as HTML code
            if (arg[0] === '<') {
                var element = void 0;
                var container = document.createElement('div');
                container.innerHTML = strings.format.apply(strings, arguments);
                if (container.children.length === 0) {
                    throw new Error('Bad use of $');
                }
                if (container.children.length === 1) {
                    element = container.firstChild;
                    container.removeChild(element);
                    return withElement(element);
                }
                var builders = [];
                while (container.firstChild) {
                    element = container.firstChild;
                    container.removeChild(element);
                    builders.push(withElement(element));
                }
                return new MultiBuilder(builders);
            }
            else if (arguments.length === 1) {
                var match = SELECTOR_REGEX.exec(arg);
                if (!match) {
                    throw new Error('Bad use of $');
                }
                var tag = match[1] || 'div';
                var id = match[3] || undefined;
                var classes = (match[4] || '').replace(/\./g, ' ');
                var props = {};
                if (id) {
                    props['id'] = id;
                }
                if (classes) {
                    props['class'] = classes;
                }
                return offDOM().element(tag, props);
            }
            else {
                var result = offDOM();
                result.element.apply(result, arguments);
                return result;
            }
        }
        else {
            throw new Error('Bad use of $');
        }
    };
    exports.$.Box = Box;
    exports.$.Dimension = Dimension;
    exports.$.Position = Position;
    exports.$.Builder = Builder;
    exports.$.MultiBuilder = MultiBuilder;
    exports.$.Build = exports.Build;
    exports.$.Binding = exports.Binding;
});

define(__m[496/*vs/css!vs/base/browser/ui/actionbar/actionbar*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[500/*vs/css!vs/base/browser/ui/aria/aria*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[505/*vs/css!vs/base/browser/ui/checkbox/checkbox*/], __M([5/*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[506/*vs/base/browser/ui/checkbox/checkbox*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,26/*vs/base/common/objects*/,41/*vs/base/browser/ui/widget*/,32/*vs/base/common/color*/,505/*vs/css!vs/base/browser/ui/checkbox/checkbox*/]), function (require, exports, DOM, objects, widget_1, color_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var defaultOpts = {
        inputActiveOptionBorder: color_1.Color.fromHex('#007ACC')
    };
    var Checkbox = (function (_super) {
        __extends(Checkbox, _super);
        function Checkbox(opts) {
            var _this = _super.call(this) || this;
            _this._opts = objects.clone(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 = _this._className();
            _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._opts.onChange(false);
                ev.preventDefault();
            });
            _this.onkeydown(_this.domNode, function (keyboardEvent) {
                if (keyboardEvent.keyCode === 10 /* Space */ || keyboardEvent.keyCode === 3 /* Enter */) {
                    _this.checked = !_this._checked;
                    _this._opts.onChange(true);
                    keyboardEvent.preventDefault();
                    return;
                }
                if (_this._opts.onKeyDown) {
                    _this._opts.onKeyDown(keyboardEvent);
                }
            });
            return _this;
        }
        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));
                this.domNode.className = this._className();
                this.applyStyles();
            },
            enumerable: true,
            configurable: true
        });
        Checkbox.prototype._className = function () {
            return 'custom-checkbox ' + this._opts.actionClassName + ' ' + (this._checked ? 'checked' : 'unchecked');
        };
        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[510/*vs/css!vs/base/browser/ui/contextview/contextview*/], __M([5/*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[160/*vs/base/browser/ui/contextview/contextview*/], __M([1/*require*/,0/*exports*/,52/*vs/base/browser/builder*/,4/*vs/base/browser/dom*/,3/*vs/base/common/lifecycle*/,38/*vs/base/common/eventEmitter*/,510/*vs/css!vs/base/browser/ui/contextview/contextview*/]), function (require, exports, builder_1, DOM, lifecycle_1, eventEmitter_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var AnchorAlignment;
    (function (AnchorAlignment) {
        AnchorAlignment[AnchorAlignment["LEFT"] = 0] = "LEFT";
        AnchorAlignment[AnchorAlignment["RIGHT"] = 1] = "RIGHT";
    })(AnchorAlignment = exports.AnchorAlignment || (exports.AnchorAlignment = {}));
    var AnchorPosition;
    (function (AnchorPosition) {
        AnchorPosition[AnchorPosition["BELOW"] = 0] = "BELOW";
        AnchorPosition[AnchorPosition["ABOVE"] = 1] = "ABOVE";
    })(AnchorPosition = exports.AnchorPosition || (exports.AnchorPosition = {}));
    function layout(view, around, viewport, anchorPosition, anchorAlignment) {
        var chooseBiased = function (a, aIsGood, b, bIsGood) {
            if (aIsGood) {
                return a;
            }
            if (bIsGood) {
                return b;
            }
            return a;
        };
        var chooseOne = function (a, aIsGood, b, bIsGood, aIsPreferred) {
            if (aIsPreferred) {
                return chooseBiased(a, aIsGood, b, bIsGood);
            }
            else {
                return chooseBiased(b, bIsGood, a, aIsGood);
            }
        };
        var top = (function () {
            // Compute both options (putting the segment above and below)
            var posAbove = around.top - view.height;
            var posBelow = around.top + around.height;
            // Check for both options if they are good
            var aboveIsGood = (posAbove >= viewport.top && posAbove + view.height <= viewport.top + viewport.height);
            var belowIsGood = (posBelow >= viewport.top && posBelow + view.height <= viewport.top + viewport.height);
            return chooseOne(posAbove, aboveIsGood, posBelow, belowIsGood, anchorPosition === AnchorPosition.ABOVE);
        })();
        var left = (function () {
            // Compute both options (aligning left and right)
            var posLeft = around.left;
            var posRight = around.left + around.width - view.width;
            // Check for both options if they are good
            var leftIsGood = (posLeft >= viewport.left && posLeft + view.width <= viewport.left + viewport.width);
            var rightIsGood = (posRight >= viewport.left && posRight + view.width <= viewport.left + viewport.width);
            return chooseOne(posLeft, leftIsGood, posRight, rightIsGood, anchorAlignment === AnchorAlignment.LEFT);
        })();
        return { top: top, left: left };
    }
    var ContextView = (function (_super) {
        __extends(ContextView, _super);
        function ContextView(container) {
            var _this = _super.call(this) || this;
            _this.$view = builder_1.$('.context-view').hide();
            _this.setContainer(container);
            _this.toDispose = [{
                    dispose: function () {
                        _this.setContainer(null);
                    }
                }];
            _this.toDisposeOnClean = null;
            return _this;
        }
        ContextView.prototype.setContainer = function (container) {
            var _this = this;
            if (this.$container) {
                this.$container.off(ContextView.BUBBLE_UP_EVENTS);
                this.$container.off(ContextView.BUBBLE_DOWN_EVENTS, true);
                this.$container = null;
            }
            if (container) {
                this.$container = builder_1.$(container);
                this.$view.appendTo(this.$container);
                this.$container.on(ContextView.BUBBLE_UP_EVENTS, function (e) {
                    _this.onDOMEvent(e, document.activeElement, false);
                });
                this.$container.on(ContextView.BUBBLE_DOWN_EVENTS, function (e) {
                    _this.onDOMEvent(e, document.activeElement, true);
                }, null, true);
            }
        };
        ContextView.prototype.show = function (delegate) {
            if (this.isVisible()) {
                this.hide();
            }
            // Show static box
            this.$view.setClass('context-view').empty().style({ top: '0px', left: '0px' }).show();
            // Render content
            this.toDisposeOnClean = delegate.render(this.$view.getHTMLElement());
            // Set active delegate
            this.delegate = delegate;
            // Layout
            this.doLayout();
        };
        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 () {
            // 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 || 0,
                    height: realAnchor.height || 0
                };
            }
            var viewport = {
                top: DOM.StandardWindow.scrollY,
                left: DOM.StandardWindow.scrollX,
                height: window.innerHeight,
                width: window.innerWidth
            };
            // Get the view's size
            var viewSize = this.$view.getTotalSize();
            var view = { width: viewSize.width, height: viewSize.height };
            var anchorPosition = this.delegate.anchorPosition || AnchorPosition.BELOW;
            var anchorAlignment = this.delegate.anchorAlignment || AnchorAlignment.LEFT;
            var result = layout(view, around, viewport, anchorPosition, anchorAlignment);
            var containerPosition = DOM.getDomNodePagePosition(this.$container.getHTMLElement());
            result.top -= containerPosition.top;
            result.left -= containerPosition.left;
            this.$view.removeClass('top', 'bottom', 'left', 'right');
            this.$view.addClass(anchorPosition === AnchorPosition.BELOW ? 'bottom' : 'top');
            this.$view.addClass(anchorAlignment === AnchorAlignment.LEFT ? 'left' : 'right');
            this.$view.style({ top: result.top + 'px', left: result.left + 'px', 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;
            }
            this.$view.hide();
        };
        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.getHTMLElement())) {
                    this.hide();
                }
            }
        };
        ContextView.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this.hide();
            this.toDispose = lifecycle_1.dispose(this.toDispose);
        };
        ContextView.BUBBLE_UP_EVENTS = ['click', 'keydown', 'focus', 'blur'];
        ContextView.BUBBLE_DOWN_EVENTS = ['click'];
        return ContextView;
    }(eventEmitter_1.EventEmitter));
    exports.ContextView = ContextView;
});

define(__m[201/*vs/css!vs/base/browser/ui/countBadge/countBadge*/], __M([5/*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[204/*vs/base/browser/ui/countBadge/countBadge*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,9/*vs/base/common/strings*/,32/*vs/base/common/color*/,26/*vs/base/common/objects*/,201/*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 = (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.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 = '' + 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[205/*vs/css!vs/base/browser/ui/findinput/findInput*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[206/*vs/css!vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[208/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/], __M([5/*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[162/*vs/base/browser/ui/iconLabel/iconLabel*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,110/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,45/*vs/base/common/paths*/,174/*vs/base/common/labels*/,208/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/]), function (require, exports, dom, highlightedLabel_1, paths, labels_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var IconLabel = (function () {
        function IconLabel(container, options) {
            this.domNode = dom.append(container, dom.$('.monaco-icon-label'));
            if (options && options.supportHighlights) {
                this.labelNode = new highlightedLabel_1.HighlightedLabel(dom.append(this.domNode, dom.$('a.label-name')));
            }
            else {
                this.labelNode = dom.append(this.domNode, dom.$('a.label-name'));
            }
            this.descriptionNode = dom.append(this.domNode, dom.$('span.label-description'));
        }
        Object.defineProperty(IconLabel.prototype, "element", {
            get: function () {
                return this.domNode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(IconLabel.prototype, "labelElement", {
            get: function () {
                var labelNode = this.labelNode;
                if (labelNode instanceof highlightedLabel_1.HighlightedLabel) {
                    return labelNode.element;
                }
                else {
                    return labelNode;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(IconLabel.prototype, "descriptionElement", {
            get: function () {
                return this.descriptionNode;
            },
            enumerable: true,
            configurable: true
        });
        IconLabel.prototype.setValue = function (label, description, options) {
            var labelNode = this.labelNode;
            if (labelNode instanceof highlightedLabel_1.HighlightedLabel) {
                labelNode.set(label || '', options ? options.matches : void 0);
            }
            else {
                labelNode.textContent = label || '';
            }
            this.descriptionNode.textContent = description || '';
            if (!description) {
                dom.addClass(this.descriptionNode, 'empty');
            }
            else {
                dom.removeClass(this.descriptionNode, 'empty');
            }
            this.domNode.title = options && options.title ? options.title : '';
            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(' ');
        };
        IconLabel.prototype.dispose = function () {
            var labelNode = this.labelNode;
            if (labelNode instanceof highlightedLabel_1.HighlightedLabel) {
                labelNode.dispose();
            }
        };
        return IconLabel;
    }());
    exports.IconLabel = IconLabel;
    var FileLabel = (function (_super) {
        __extends(FileLabel, _super);
        function FileLabel(container, file, provider, userHome) {
            var _this = _super.call(this, container) || this;
            _this.setFile(file, provider, userHome);
            return _this;
        }
        FileLabel.prototype.setFile = function (file, provider, userHome) {
            var parent = paths.dirname(file.fsPath);
            this.setValue(paths.basename(file.fsPath), parent && parent !== '.' ? labels_1.getPathLabel(parent, provider, userHome) : '', { title: file.fsPath });
        };
        return FileLabel;
    }(IconLabel));
    exports.FileLabel = FileLabel;
});

define(__m[211/*vs/css!vs/base/browser/ui/inputbox/inputBox*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[212/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[213/*vs/css!vs/base/browser/ui/list/list*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[218/*vs/css!vs/base/browser/ui/menu/menu*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[219/*vs/css!vs/base/browser/ui/progressbar/progressbar*/], __M([5/*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[220/*vs/base/browser/ui/progressbar/progressbar*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,72/*vs/base/common/assert*/,52/*vs/base/browser/builder*/,4/*vs/base/browser/dom*/,3/*vs/base/common/lifecycle*/,32/*vs/base/common/color*/,26/*vs/base/common/objects*/,219/*vs/css!vs/base/browser/ui/progressbar/progressbar*/]), function (require, exports, winjs_base_1, assert, builder_1, DOM, lifecycle_1, color_1, objects_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 = '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 = (function () {
        function ProgressBar(builder, options) {
            this.options = options || Object.create(null);
            objects_1.mixin(this.options, defaultOpts, false);
            this.toUnbind = [];
            this.workedVal = 0;
            this.progressBarBackground = this.options.progressBarBackground;
            this.create(builder);
        }
        ProgressBar.prototype.create = function (parent) {
            var _this = this;
            parent.div({ 'class': css_progress_container }, function (builder) {
                _this.element = builder.clone();
                builder.div({ 'class': css_progress_bit }).on([DOM.EventType.ANIMATION_START, DOM.EventType.ANIMATION_END, DOM.EventType.ANIMATION_ITERATION], function (e) {
                    switch (e.type) {
                        case DOM.EventType.ANIMATION_START:
                        case DOM.EventType.ANIMATION_END:
                            _this.animationRunning = e.type === DOM.EventType.ANIMATION_START;
                            break;
                        case DOM.EventType.ANIMATION_ITERATION:
                            if (_this.animationStopToken) {
                                _this.animationStopToken(null);
                            }
                            break;
                    }
                }, _this.toUnbind);
                _this.bit = builder.getHTMLElement();
            });
            this.applyStyles();
        };
        ProgressBar.prototype.off = function () {
            this.bit.style.width = 'inherit';
            this.bit.style.opacity = '1';
            this.element.removeClass(css_active);
            this.element.removeClass(css_infinite);
            this.element.removeClass(css_discrete);
            this.workedVal = 0;
            this.totalWork = undefined;
        };
        /**
         * Indicates to the progress bar that all work is done.
         */
        ProgressBar.prototype.done = function () {
            return this.doDone(true);
        };
        /**
         * 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;
            this.element.addClass(css_done);
            // let it grow to 100% width and hide afterwards
            if (!this.element.hasClass(css_infinite)) {
                this.bit.style.width = 'inherit';
                if (delayed) {
                    winjs_base_1.TPromise.timeout(200).then(function () { return _this.off(); });
                }
                else {
                    this.off();
                }
            }
            else {
                this.bit.style.opacity = '0';
                if (delayed) {
                    winjs_base_1.TPromise.timeout(200).then(function () { return _this.off(); });
                }
                else {
                    this.off();
                }
            }
            return this;
        };
        /**
         * Use this mode to indicate progress that has no total number of work units.
         */
        ProgressBar.prototype.infinite = function () {
            this.bit.style.width = '2%';
            this.bit.style.opacity = '1';
            this.element.removeClass(css_discrete);
            this.element.removeClass(css_done);
            this.element.addClass(css_active);
            this.element.addClass(css_infinite);
            return this;
        };
        /**
         * Tells the progress bar the total number of work. Use in combination with workedVal() to let
         * the progress bar show the actual progress based on the work that is done.
         */
        ProgressBar.prototype.total = function (value) {
            this.workedVal = 0;
            this.totalWork = value;
            return this;
        };
        /**
         * Finds out if this progress bar is configured with total work
         */
        ProgressBar.prototype.hasTotal = function () {
            return !isNaN(this.totalWork);
        };
        /**
         * Tells the progress bar that an amount of work has been completed.
         */
        ProgressBar.prototype.worked = function (value) {
            assert.ok(!isNaN(this.totalWork), 'Total work not set');
            value = Number(value);
            assert.ok(!isNaN(value), 'Value is not a number');
            value = Math.max(1, value);
            this.workedVal += value;
            this.workedVal = Math.min(this.totalWork, this.workedVal);
            if (this.element.hasClass(css_infinite)) {
                this.element.removeClass(css_infinite);
            }
            if (this.element.hasClass(css_done)) {
                this.element.removeClass(css_done);
            }
            if (!this.element.hasClass(css_active)) {
                this.element.addClass(css_active);
            }
            if (!this.element.hasClass(css_discrete)) {
                this.element.addClass(css_discrete);
            }
            this.bit.style.width = 100 * (this.workedVal / this.totalWork) + '%';
            return this;
        };
        /**
         * Returns the builder this progress bar is building in.
         */
        ProgressBar.prototype.getContainer = function () {
            return builder_1.$(this.element);
        };
        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;
            }
        };
        ProgressBar.prototype.dispose = function () {
            this.toUnbind = lifecycle_1.dispose(this.toUnbind);
        };
        return ProgressBar;
    }());
    exports.ProgressBar = ProgressBar;
});

define(__m[224/*vs/css!vs/base/browser/ui/sash/sash*/], __M([5/*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[99/*vs/base/browser/ui/sash/sash*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,52/*vs/base/browser/builder*/,28/*vs/base/browser/browser*/,15/*vs/base/common/platform*/,29/*vs/base/common/types*/,4/*vs/base/browser/dom*/,74/*vs/base/browser/touch*/,38/*vs/base/common/eventEmitter*/,47/*vs/base/browser/mouseEvent*/,11/*vs/base/common/event*/,224/*vs/css!vs/base/browser/ui/sash/sash*/]), function (require, exports, lifecycle_1, builder_1, browser_1, platform_1, types, DOM, touch_1, eventEmitter_1, mouseEvent_1, event_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var Orientation;
    (function (Orientation) {
        Orientation[Orientation["VERTICAL"] = 0] = "VERTICAL";
        Orientation[Orientation["HORIZONTAL"] = 1] = "HORIZONTAL";
    })(Orientation = exports.Orientation || (exports.Orientation = {}));
    var Sash = (function (_super) {
        __extends(Sash, _super);
        function Sash(container, layoutProvider, options) {
            if (options === void 0) { options = {}; }
            var _this = _super.call(this) || this;
            _this.$e = builder_1.$('.monaco-sash').appendTo(container);
            if (platform_1.isMacintosh) {
                _this.$e.addClass('mac');
            }
            _this.gesture = new touch_1.Gesture(_this.$e.getHTMLElement());
            _this.$e.on(DOM.EventType.MOUSE_DOWN, function (e) { _this.onMouseDown(e); });
            _this.$e.on(DOM.EventType.DBLCLICK, function (e) { _this.emit('reset', e); });
            _this.$e.on(touch_1.EventType.Start, function (e) { _this.onTouchStart(e); });
            _this.size = options.baseSize || 5;
            if (browser_1.isIPad) {
                _this.size *= 4; // see also http://ux.stackexchange.com/questions/39023/what-is-the-optimum-button-size-of-touch-screen-applications
                _this.$e.addClass('touch');
            }
            _this.setOrientation(options.orientation || Orientation.VERTICAL);
            _this.isDisabled = false;
            _this.hidden = false;
            _this.layoutProvider = layoutProvider;
            return _this;
        }
        Sash.prototype.getHTMLElement = function () {
            return this.$e.getHTMLElement();
        };
        Sash.prototype.setOrientation = function (orientation) {
            this.orientation = orientation;
            this.$e.removeClass('horizontal', 'vertical');
            this.$e.addClass(this.getOrientation());
            if (this.orientation === Orientation.HORIZONTAL) {
                this.$e.size(null, this.size);
            }
            else {
                this.$e.size(this.size);
            }
            if (this.layoutProvider) {
                this.layout();
            }
        };
        Sash.prototype.getOrientation = function () {
            return this.orientation === Orientation.HORIZONTAL ? 'horizontal' : 'vertical';
        };
        Sash.prototype.onMouseDown = function (e) {
            var _this = this;
            DOM.EventHelper.stop(e, false);
            if (this.isDisabled) {
                return;
            }
            var iframes = builder_1.$(DOM.getElementsByTagName('iframe'));
            if (iframes) {
                iframes.style('pointer-events', '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 startEvent = {
                startX: startX,
                currentX: startX,
                startY: startY,
                currentY: startY
            };
            this.$e.addClass('active');
            this.emit('start', startEvent);
            var $window = builder_1.$(window);
            var containerCSSClass = this.getOrientation() + "-cursor-container" + (platform_1.isMacintosh ? '-mac' : '');
            var lastCurrentX = startX;
            var lastCurrentY = startY;
            $window.on('mousemove', function (e) {
                DOM.EventHelper.stop(e, false);
                var mouseMoveEvent = new mouseEvent_1.StandardMouseEvent(e);
                var event = {
                    startX: startX,
                    currentX: mouseMoveEvent.posx,
                    startY: startY,
                    currentY: mouseMoveEvent.posy
                };
                lastCurrentX = mouseMoveEvent.posx;
                lastCurrentY = mouseMoveEvent.posy;
                _this.emit('change', event);
            }).once('mouseup', function (e) {
                DOM.EventHelper.stop(e, false);
                _this.$e.removeClass('active');
                _this.emit('end');
                $window.off('mousemove');
                document.body.classList.remove(containerCSSClass);
                var iframes = builder_1.$(DOM.getElementsByTagName('iframe'));
                if (iframes) {
                    iframes.style('pointer-events', 'auto');
                }
            });
            document.body.classList.add(containerCSSClass);
        };
        Sash.prototype.onTouchStart = function (event) {
            var _this = this;
            DOM.EventHelper.stop(event);
            var listeners = [];
            var startX = event.pageX;
            var startY = event.pageY;
            this.emit('start', {
                startX: startX,
                currentX: startX,
                startY: startY,
                currentY: startY
            });
            var lastCurrentX = startX;
            var lastCurrentY = startY;
            listeners.push(DOM.addDisposableListener(this.$e.getHTMLElement(), touch_1.EventType.Change, function (event) {
                if (types.isNumber(event.pageX) && types.isNumber(event.pageY)) {
                    _this.emit('change', {
                        startX: startX,
                        currentX: event.pageX,
                        startY: startY,
                        currentY: event.pageY
                    });
                    lastCurrentX = event.pageX;
                    lastCurrentY = event.pageY;
                }
            }));
            listeners.push(DOM.addDisposableListener(this.$e.getHTMLElement(), touch_1.EventType.End, function (event) {
                _this.emit('end');
                lifecycle_1.dispose(listeners);
            }));
        };
        Sash.prototype.layout = function () {
            var style;
            if (this.orientation === Orientation.VERTICAL) {
                var verticalProvider = this.layoutProvider;
                style = { left: verticalProvider.getVerticalSashLeft(this) - (this.size / 2) + 'px' };
                if (verticalProvider.getVerticalSashTop) {
                    style.top = verticalProvider.getVerticalSashTop(this) + 'px';
                }
                if (verticalProvider.getVerticalSashHeight) {
                    style.height = verticalProvider.getVerticalSashHeight(this) + 'px';
                }
            }
            else {
                var horizontalProvider = this.layoutProvider;
                style = { top: horizontalProvider.getHorizontalSashTop(this) - (this.size / 2) + 'px' };
                if (horizontalProvider.getHorizontalSashLeft) {
                    style.left = horizontalProvider.getHorizontalSashLeft(this) + 'px';
                }
                if (horizontalProvider.getHorizontalSashWidth) {
                    style.width = horizontalProvider.getHorizontalSashWidth(this) + 'px';
                }
            }
            this.$e.style(style);
        };
        Sash.prototype.show = function () {
            this.hidden = false;
            this.$e.show();
        };
        Sash.prototype.hide = function () {
            this.hidden = true;
            this.$e.hide();
        };
        Sash.prototype.isHidden = function () {
            return this.hidden;
        };
        Sash.prototype.enable = function () {
            this.$e.removeClass('disabled');
            this.isDisabled = false;
        };
        Sash.prototype.disable = function () {
            this.$e.addClass('disabled');
            this.isDisabled = true;
        };
        Sash.prototype.dispose = function () {
            if (this.$e) {
                this.$e.destroy();
                this.$e = null;
            }
            _super.prototype.dispose.call(this);
        };
        return Sash;
    }(eventEmitter_1.EventEmitter));
    exports.Sash = Sash;
    /**
     * A simple Vertical Sash that computes the position of the sash when it is moved between the given dimension.
     * Triggers onPositionChange event when the position is changed
     */
    var VSash = (function (_super) {
        __extends(VSash, _super);
        function VSash(container, minWidth) {
            var _this = _super.call(this) || this;
            _this.minWidth = minWidth;
            _this._onPositionChange = new event_1.Emitter();
            _this.ratio = 0.5;
            _this.sash = new Sash(container, _this);
            _this._register(_this.sash.addListener('start', function () { return _this.onSashDragStart(); }));
            _this._register(_this.sash.addListener('change', function (e) { return _this.onSashDrag(e); }));
            _this._register(_this.sash.addListener('end', function () { return _this.onSashDragEnd(); }));
            _this._register(_this.sash.addListener('reset', function () { return _this.onSashReset(); }));
            return _this;
        }
        Object.defineProperty(VSash.prototype, "onPositionChange", {
            get: function () { return this._onPositionChange.event; },
            enumerable: true,
            configurable: true
        });
        VSash.prototype.getVerticalSashTop = function () {
            return 0;
        };
        VSash.prototype.getVerticalSashLeft = function () {
            return this.position;
        };
        VSash.prototype.getVerticalSashHeight = function () {
            return this.dimension.height;
        };
        VSash.prototype.setDimenesion = function (dimension) {
            this.dimension = dimension;
            this.compute(this.ratio);
        };
        VSash.prototype.onSashDragStart = function () {
            this.startPosition = this.position;
        };
        VSash.prototype.onSashDrag = function (e) {
            this.compute((this.startPosition + (e.currentX - e.startX)) / this.dimension.width);
        };
        VSash.prototype.compute = function (ratio) {
            this.computeSashPosition(ratio);
            this.ratio = this.position / this.dimension.width;
            this._onPositionChange.fire(this.position);
        };
        VSash.prototype.onSashDragEnd = function () {
            this.sash.layout();
        };
        VSash.prototype.onSashReset = function () {
            this.ratio = 0.5;
            this._onPositionChange.fire(this.position);
            this.sash.layout();
        };
        VSash.prototype.computeSashPosition = function (sashRatio) {
            if (sashRatio === void 0) { sashRatio = this.ratio; }
            var contentWidth = this.dimension.width;
            var sashPosition = Math.floor((sashRatio || 0.5) * contentWidth);
            var midPoint = Math.floor(0.5 * contentWidth);
            if (contentWidth > this.minWidth * 2) {
                if (sashPosition < this.minWidth) {
                    sashPosition = this.minWidth;
                }
                if (sashPosition > contentWidth - this.minWidth) {
                    sashPosition = contentWidth - this.minWidth;
                }
            }
            else {
                sashPosition = midPoint;
            }
            if (this.position !== sashPosition) {
                this.position = sashPosition;
                this.sash.layout();
            }
        };
        return VSash;
    }(lifecycle_1.Disposable));
    exports.VSash = VSash;
});

define(__m[228/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});










define(__m[63/*vs/base/browser/ui/scrollbar/scrollableElement*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,15/*vs/base/common/platform*/,47/*vs/base/browser/mouseEvent*/,439/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/,440/*vs/base/browser/ui/scrollbar/verticalScrollbar*/,3/*vs/base/common/lifecycle*/,48/*vs/base/common/scrollable*/,41/*vs/base/browser/ui/widget*/,18/*vs/base/common/async*/,27/*vs/base/browser/fastDomNode*/,11/*vs/base/common/event*/,228/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/]), function (require, exports, DomUtils, Platform, mouseEvent_1, horizontalScrollbar_1, verticalScrollbar_1, lifecycle_1, scrollable_1, widget_1, async_1, fastDomNode_1, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var HIDE_TIMEOUT = 500;
    var SCROLL_WHEEL_SENSITIVITY = 50;
    var ScrollableElement = (function (_super) {
        __extends(ScrollableElement, _super);
        function ScrollableElement(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);
            if (typeof scrollable === 'undefined') {
                _this._scrollable = _this._register(new scrollable_1.Scrollable());
            }
            else {
                _this._scrollable = scrollable;
            }
            _this._register(_this._scrollable.onScroll(function (e) {
                _this._onDidScroll(e);
                _this._onScroll.fire(e);
            }));
            // this._scrollable = this._register(new DelegateScrollable(scrollable, () => this._onScroll()));
            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;
            return _this;
        }
        ScrollableElement.prototype.dispose = function () {
            this._mouseWheelToDispose = lifecycle_1.dispose(this._mouseWheelToDispose);
            _super.prototype.dispose.call(this);
        };
        /**
         * Get the generated 'scrollable' dom node
         */
        ScrollableElement.prototype.getDomNode = function () {
            return this._domNode;
        };
        ScrollableElement.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.
         */
        ScrollableElement.prototype.delegateVerticalScrollbarMouseDown = function (browserEvent) {
            this._verticalScrollbar.delegateMouseDown(browserEvent);
        };
        /**
         * Delegate a mouse down event to the vertical scrollbar (directly to the slider!).
         * This is to help with clicking somewhere else and having the scrollbar react.
         */
        ScrollableElement.prototype.delegateSliderMouseDown = function (e, onDragFinished) {
            this._verticalScrollbar.delegateSliderMouseDown(e, onDragFinished);
        };
        ScrollableElement.prototype.updateState = function (newState) {
            this._scrollable.updateState(newState);
        };
        ScrollableElement.prototype.getScrollState = function () {
            return this._scrollable.getState();
        };
        /**
         * Update the class name of the scrollable element.
         */
        ScrollableElement.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.
         */
        ScrollableElement.prototype.updateOptions = function (newOptions) {
            var massagedOptions = resolveOptions(newOptions);
            this._options.handleMouseWheel = massagedOptions.handleMouseWheel;
            this._options.mouseWheelScrollSensitivity = massagedOptions.mouseWheelScrollSensitivity;
            this._setListeningToMouseWheel(this._options.handleMouseWheel);
            if (!this._options.lazyRender) {
                this._render();
            }
        };
        // -------------------- mouse wheel scrolling --------------------
        ScrollableElement.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) {
                    var e = new mouseEvent_1.StandardMouseWheelEvent(browserEvent);
                    _this._onMouseWheel(e);
                };
                this._mouseWheelToDispose.push(DomUtils.addDisposableListener(this._listenOnDomNode, 'mousewheel', onMouseWheel));
                this._mouseWheelToDispose.push(DomUtils.addDisposableListener(this._listenOnDomNode, 'DOMMouseScroll', onMouseWheel));
            }
        };
        ScrollableElement.prototype._onMouseWheel = function (e) {
            var desiredScrollTop = -1;
            var desiredScrollLeft = -1;
            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.shiftKey;
                if ((this._options.scrollYToX || shiftConvert) && !deltaX) {
                    deltaX = deltaY;
                    deltaY = 0;
                }
                if (Platform.isMacintosh) {
                    // Give preference to vertical scrolling
                    if (deltaY && Math.abs(deltaX) < 0.2) {
                        deltaX = 0;
                    }
                    if (Math.abs(deltaY) > Math.abs(deltaX) * 0.5) {
                        deltaX = 0;
                    }
                }
                var scrollState = this._scrollable.getState();
                if (deltaY) {
                    var currentScrollTop = scrollState.scrollTop;
                    desiredScrollTop = this._verticalScrollbar.validateScrollPosition((desiredScrollTop !== -1 ? desiredScrollTop : currentScrollTop) - SCROLL_WHEEL_SENSITIVITY * deltaY);
                    if (desiredScrollTop === currentScrollTop) {
                        desiredScrollTop = -1;
                    }
                }
                if (deltaX) {
                    var currentScrollLeft = scrollState.scrollLeft;
                    desiredScrollLeft = this._horizontalScrollbar.validateScrollPosition((desiredScrollLeft !== -1 ? desiredScrollLeft : currentScrollLeft) - SCROLL_WHEEL_SENSITIVITY * deltaX);
                    if (desiredScrollLeft === currentScrollLeft) {
                        desiredScrollLeft = -1;
                    }
                }
                if (desiredScrollTop !== -1 || desiredScrollLeft !== -1) {
                    if (desiredScrollTop !== -1) {
                        this._shouldRender = this._verticalScrollbar.setDesiredScrollPosition(desiredScrollTop) || this._shouldRender;
                        desiredScrollTop = -1;
                    }
                    if (desiredScrollLeft !== -1) {
                        this._shouldRender = this._horizontalScrollbar.setDesiredScrollPosition(desiredScrollLeft) || this._shouldRender;
                        desiredScrollLeft = -1;
                    }
                }
            }
            if (this._options.alwaysConsumeMouseWheel || this._shouldRender) {
                e.preventDefault();
                e.stopPropagation();
            }
            var _a;
        };
        ScrollableElement.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;
            }
            this._reveal();
            if (!this._options.lazyRender) {
                this._render();
            }
        };
        /**
         * Render / mutate the DOM now.
         * Should be used together with the ctor option `lazyRender`.
         */
        ScrollableElement.prototype.renderNow = function () {
            if (!this._options.lazyRender) {
                throw new Error('Please use `lazyRender` together with `renderNow`!');
            }
            this._render();
        };
        ScrollableElement.prototype._render = function () {
            if (!this._shouldRender) {
                return;
            }
            this._shouldRender = false;
            this._horizontalScrollbar.render();
            this._verticalScrollbar.render();
            if (this._options.useShadows) {
                var scrollState = this._scrollable.getState();
                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 --------------------
        ScrollableElement.prototype._onDragStart = function () {
            this._isDragging = true;
            this._reveal();
        };
        ScrollableElement.prototype._onDragEnd = function () {
            this._isDragging = false;
            this._hide();
        };
        ScrollableElement.prototype._onMouseOut = function (e) {
            this._mouseIsOver = false;
            this._hide();
        };
        ScrollableElement.prototype._onMouseOver = function (e) {
            this._mouseIsOver = true;
            this._reveal();
        };
        ScrollableElement.prototype._reveal = function () {
            this._verticalScrollbar.beginReveal();
            this._horizontalScrollbar.beginReveal();
            this._scheduleHide();
        };
        ScrollableElement.prototype._hide = function () {
            if (!this._mouseIsOver && !this._isDragging) {
                this._verticalScrollbar.beginHide();
                this._horizontalScrollbar.beginHide();
            }
        };
        ScrollableElement.prototype._scheduleHide = function () {
            var _this = this;
            if (!this._mouseIsOver && !this._isDragging) {
                this._hideTimeout.cancelAndSet(function () { return _this._hide(); }, HIDE_TIMEOUT);
            }
        };
        return ScrollableElement;
    }(widget_1.Widget));
    exports.ScrollableElement = ScrollableElement;
    var DomScrollableElement = (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 () {
            // widh, scrollLeft, scrollWidth, height, scrollTop, scrollHeight
            this.updateState({
                width: this._element.clientWidth,
                scrollWidth: this._element.scrollWidth,
                scrollLeft: this._element.scrollLeft,
                height: this._element.clientHeight,
                scrollHeight: this._element.scrollHeight,
                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),
            arrowSize: (typeof opts.arrowSize !== 'undefined' ? opts.arrowSize : 11),
            listenOnDomNode: (typeof opts.listenOnDomNode !== 'undefined' ? opts.listenOnDomNode : null),
            horizontal: (typeof opts.horizontal !== 'undefined' ? opts.horizontal : scrollable_1.ScrollbarVisibility.Auto),
            horizontalScrollbarSize: (typeof opts.horizontalScrollbarSize !== 'undefined' ? opts.horizontalScrollbarSize : 10),
            horizontalSliderSize: (typeof opts.horizontalSliderSize !== 'undefined' ? opts.horizontalSliderSize : 0),
            horizontalHasArrows: (typeof opts.horizontalHasArrows !== 'undefined' ? opts.horizontalHasArrows : false),
            vertical: (typeof opts.vertical !== 'undefined' ? opts.vertical : scrollable_1.ScrollbarVisibility.Auto),
            verticalScrollbarSize: (typeof opts.verticalScrollbarSize !== 'undefined' ? opts.verticalScrollbarSize : 10),
            verticalHasArrows: (typeof opts.verticalHasArrows !== 'undefined' ? opts.verticalHasArrows : false),
            verticalSliderSize: (typeof opts.verticalSliderSize !== 'undefined' ? opts.verticalSliderSize : 0)
        };
        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[232/*vs/base/browser/ui/list/listView*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/objects*/,3/*vs/base/common/lifecycle*/,74/*vs/base/browser/touch*/,4/*vs/base/browser/dom*/,124/*vs/base/browser/event*/,63/*vs/base/browser/ui/scrollbar/scrollableElement*/,48/*vs/base/common/scrollable*/,415/*vs/base/browser/ui/list/rangeMap*/,416/*vs/base/browser/ui/list/rowCache*/,15/*vs/base/common/platform*/,28/*vs/base/browser/browser*/]), function (require, exports, objects_1, lifecycle_1, touch_1, DOM, event_1, scrollableElement_1, scrollable_1, rangeMap_1, rowCache_1, platform_1, browser_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var MouseEventTypes = [
        'click',
        'dblclick',
        'mouseup',
        'mousedown',
        'mouseover',
        'mousemove',
        'mouseout',
        'contextmenu',
        'touchstart'
    ];
    var DefaultOptions = {
        useShadows: true
    };
    var ListView = (function () {
        function ListView(container, delegate, renderers, options) {
            if (options === void 0) { options = DefaultOptions; }
            this.delegate = delegate;
            this.items = [];
            this.itemId = 0;
            this.rangeMap = new rangeMap_1.RangeMap();
            this.renderers = objects_1.toObject(renderers, function (r) { return r.templateId; });
            this.cache = new rowCache_1.RowCache(this.renderers);
            this.lastRenderTop = 0;
            this.lastRenderHeight = 0;
            this._domNode = document.createElement('div');
            this._domNode.className = 'monaco-list';
            this.rowsContainer = document.createElement('div');
            this.rowsContainer.className = 'monaco-list-rows';
            this.gesture = new touch_1.Gesture(this.rowsContainer);
            this.scrollableElement = new scrollableElement_1.ScrollableElement(this.rowsContainer, {
                alwaysConsumeMouseWheel: true,
                horizontal: scrollable_1.ScrollbarVisibility.Hidden,
                vertical: scrollable_1.ScrollbarVisibility.Auto,
                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.scrollableElement.onScroll(this.onScroll, this, this.disposables);
            event_1.domEvent(this.rowsContainer, touch_1.EventType.Change)(this.onTouchChange, this, this.disposables);
            this.layout();
        }
        Object.defineProperty(ListView.prototype, "domNode", {
            get: function () {
                return this._domNode;
            },
            enumerable: true,
            configurable: true
        });
        ListView.prototype.splice = function (start, deleteCount, elements) {
            var _this = this;
            if (elements === void 0) { elements = []; }
            var previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
            rangeMap_1.each(previousRenderRange, function (i) { return _this.removeItemFromDOM(_this.items[i]); });
            var inserted = elements.map(function (element) { return ({
                id: String(_this.itemId++),
                element: element,
                size: _this.delegate.getHeight(element),
                templateId: _this.delegate.getTemplateId(element),
                row: null
            }); });
            (_a = this.rangeMap).splice.apply(_a, [start, deleteCount].concat(inserted));
            var deleted = (_b = this.items).splice.apply(_b, [start, deleteCount].concat(inserted));
            var renderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
            rangeMap_1.each(renderRange, function (i) { return _this.insertItemInDOM(_this.items[i], i); });
            var scrollHeight = this.getContentHeight();
            this.rowsContainer.style.height = scrollHeight + "px";
            this.scrollableElement.updateState({ scrollHeight: scrollHeight });
            return deleted.map(function (i) { return i.element; });
            var _a, _b;
        };
        Object.defineProperty(ListView.prototype, "length", {
            get: function () {
                return this.items.length;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ListView.prototype, "renderHeight", {
            get: function () {
                var scrollState = this.scrollableElement.getScrollState();
                return scrollState.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) {
            this.scrollableElement.updateState({
                height: height || DOM.getContentHeight(this._domNode)
            });
        };
        // Render
        ListView.prototype.render = function (renderTop, renderHeight) {
            var _this = this;
            var previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
            var renderRange = this.getRenderRange(renderTop, renderHeight);
            var rangesToInsert = rangeMap_1.relativeComplement(renderRange, previousRenderRange);
            var rangesToRemove = rangeMap_1.relativeComplement(previousRenderRange, renderRange);
            rangesToInsert.forEach(function (range) { return rangeMap_1.each(range, function (i) { return _this.insertItemInDOM(_this.items[i], i); }); });
            rangesToRemove.forEach(function (range) { return rangeMap_1.each(range, function (i) { return _this.removeItemFromDOM(_this.items[i]); }); });
            if (browser_1.canUseTranslate3d() && !platform_1.isWindows /* Windows: translate3d breaks subpixel-antialias (ClearType) unless a background is defined */) {
                var transform = "translate3d(0px, -" + renderTop + "px, 0px)";
                this.rowsContainer.style.transform = transform;
                this.rowsContainer.style.webkitTransform = transform;
            }
            else {
                this.rowsContainer.style.top = "-" + renderTop + "px";
            }
            this.lastRenderTop = renderTop;
            this.lastRenderHeight = renderHeight;
        };
        // DOM operations
        ListView.prototype.insertItemInDOM = function (item, index) {
            if (!item.row) {
                item.row = this.cache.alloc(item.templateId);
            }
            if (!item.row.domNode.parentElement) {
                this.rowsContainer.appendChild(item.row.domNode);
            }
            var renderer = this.renderers[item.templateId];
            item.row.domNode.style.top = this.elementTop(index) + "px";
            item.row.domNode.style.height = item.size + "px";
            item.row.domNode.setAttribute('data-index', "" + index);
            renderer.renderElement(item.element, index, item.row.templateData);
        };
        ListView.prototype.removeItemFromDOM = function (item) {
            this.cache.release(item.row);
            item.row = null;
        };
        ListView.prototype.getContentHeight = function () {
            return this.rangeMap.size;
        };
        ListView.prototype.getScrollTop = function () {
            var scrollState = this.scrollableElement.getScrollState();
            return scrollState.scrollTop;
        };
        ListView.prototype.setScrollTop = function (scrollTop) {
            this.scrollableElement.updateState({ scrollTop: scrollTop });
        };
        Object.defineProperty(ListView.prototype, "scrollTop", {
            get: function () {
                return this.getScrollTop();
            },
            set: function (scrollTop) {
                this.setScrollTop(scrollTop);
            },
            enumerable: true,
            configurable: true
        });
        // Events
        ListView.prototype.addListener = function (type, handler, useCapture) {
            var _this = this;
            var userHandler = handler;
            var domNode = this.domNode;
            if (MouseEventTypes.indexOf(type) > -1) {
                handler = function (e) { return _this.fireScopedEvent(e, userHandler, _this.getItemIndexFromMouseEvent(e)); };
            }
            else if (type === touch_1.EventType.Tap) {
                domNode = this.rowsContainer;
                handler = function (e) { return _this.fireScopedEvent(e, userHandler, _this.getItemIndexFromGestureEvent(e)); };
            }
            return DOM.addDisposableListener(domNode, type, handler, useCapture);
        };
        ListView.prototype.fireScopedEvent = function (event, handler, index) {
            if (index < 0) {
                return;
            }
            var element = this.items[index].element;
            handler(objects_1.assign(event, { element: element, index: index }));
        };
        ListView.prototype.onScroll = function (e) {
            this.render(e.scrollTop, e.height);
        };
        ListView.prototype.onTouchChange = function (event) {
            event.preventDefault();
            event.stopPropagation();
            this.scrollTop -= event.translationY;
        };
        // Util
        ListView.prototype.getItemIndexFromMouseEvent = function (event) {
            return this.getItemIndexFromEventTarget(event.target);
        };
        ListView.prototype.getItemIndexFromGestureEvent = function (event) {
            return this.getItemIndexFromEventTarget(event.initialTarget);
        };
        ListView.prototype.getItemIndexFromEventTarget = function (target) {
            while (target instanceof HTMLElement && target !== this.rowsContainer) {
                var element = target;
                var rawIndex = element.getAttribute('data-index');
                if (rawIndex) {
                    var index = Number(rawIndex);
                    if (!isNaN(index)) {
                        return index;
                    }
                }
                target = element.parentElement;
            }
            return -1;
        };
        ListView.prototype.getRenderRange = function (renderTop, renderHeight) {
            return {
                start: this.rangeMap.indexAt(renderTop),
                end: this.rangeMap.indexAfter(renderTop + renderHeight - 1)
            };
        };
        // Dispose
        ListView.prototype.dispose = function () {
            this.items = null;
            if (this._domNode && this._domNode.parentElement) {
                this._domNode.parentNode.removeChild(this._domNode);
                this._domNode = null;
            }
            this.disposables = lifecycle_1.dispose(this.disposables);
        };
        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.
 *--------------------------------------------------------------------------------------------*/










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[234/*vs/base/browser/ui/list/listWidget*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,29/*vs/base/common/types*/,33/*vs/base/common/arrays*/,136/*vs/base/common/functional*/,446/*vs/base/common/decorators*/,4/*vs/base/browser/dom*/,15/*vs/base/common/platform*/,74/*vs/base/browser/touch*/,65/*vs/base/browser/keyboardEvent*/,11/*vs/base/common/event*/,124/*vs/base/browser/event*/,232/*vs/base/browser/ui/list/listView*/,32/*vs/base/common/color*/,26/*vs/base/common/objects*/,213/*vs/css!vs/base/browser/ui/list/list*/]), function (require, exports, lifecycle_1, types_1, arrays_1, functional_1, decorators_1, DOM, platform, touch_1, keyboardEvent_1, event_1, event_2, listView_1, color_1, objects_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var CombinedSpliceable = (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;
    }());
    var TraitRenderer = (function () {
        function TraitRenderer(trait) {
            this.trait = trait;
            this.rendered = [];
        }
        Object.defineProperty(TraitRenderer.prototype, "templateId", {
            get: function () {
                return "template:" + this.trait.trait;
            },
            enumerable: true,
            configurable: true
        });
        TraitRenderer.prototype.renderTemplate = function (container) {
            var elementDisposable = lifecycle_1.empty;
            return { container: container, elementDisposable: elementDisposable };
        };
        TraitRenderer.prototype.renderElement = function (element, index, templateData) {
            var _this = this;
            templateData.elementDisposable.dispose();
            var rendered = { index: index, templateData: templateData };
            this.rendered.push(rendered);
            templateData.elementDisposable = lifecycle_1.toDisposable(functional_1.once(function () { return _this.rendered.splice(_this.rendered.indexOf(rendered), 1); }));
            this.trait.renderIndex(index, templateData.container);
        };
        TraitRenderer.prototype.renderIndexes = function (indexes) {
            var _this = this;
            this.rendered
                .filter(function (_a) {
                var index = _a.index;
                return indexes.indexOf(index) > -1;
            })
                .forEach(function (_a) {
                var index = _a.index, templateData = _a.templateData;
                return _this.trait.renderIndex(index, templateData.container);
            });
        };
        TraitRenderer.prototype.splice = function (start, deleteCount) {
            for (var i = 0; i < deleteCount; i++) {
                var key = "key_" + (start + i);
                var data = this.rendered[key];
                if (data) {
                    data.elementDisposable.dispose();
                }
            }
        };
        TraitRenderer.prototype.disposeTemplate = function (templateData) {
            templateData.elementDisposable.dispose();
        };
        return TraitRenderer;
    }());
    var Trait = (function () {
        function Trait(_trait) {
            this._trait = _trait;
            this._onChange = new event_1.Emitter();
            this.indexes = [];
        }
        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.indexes.filter(function (i) { return i < start; }).concat(elements.reduce(function (r, hasTrait, i) { return hasTrait ? r.concat([i + start]) : r; }, []), this.indexes.filter(function (i) { return i >= end; }).map(function (i) { return i + diff; }));
            this.renderer.splice(start, deleteCount);
            this.set(indexes);
        };
        Trait.prototype.renderIndex = function (index, container) {
            DOM.toggleClass(container, this._trait, this.contains(index));
        };
        /**
         * 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) {
            var result = this.indexes;
            this.indexes = indexes;
            var toRender = disjunction(result, indexes);
            this.renderer.renderIndexes(toRender);
            this._onChange.fire({ indexes: indexes });
            return result;
        };
        Trait.prototype.get = function () {
            return this.indexes;
        };
        Trait.prototype.contains = function (index) {
            return this.indexes.some(function (i) { return i === index; });
        };
        Trait.prototype.dispose = function () {
            this.indexes = null;
            this._onChange = lifecycle_1.dispose(this._onChange);
        };
        __decorate([
            decorators_1.memoize
        ], Trait.prototype, "renderer", null);
        return Trait;
    }());
    var FocusTrait = (function (_super) {
        __extends(FocusTrait, _super);
        function FocusTrait(getDomId) {
            var _this = _super.call(this, 'focused') || this;
            _this.getDomId = getDomId;
            return _this;
        }
        FocusTrait.prototype.renderIndex = function (index, container) {
            _super.prototype.renderIndex.call(this, index, container);
            container.setAttribute('role', 'treeitem');
            container.setAttribute('id', this.getDomId(index));
        };
        return FocusTrait;
    }(Trait));
    var Aria = (function () {
        function Aria() {
            this.length = 0;
        }
        Object.defineProperty(Aria.prototype, "templateId", {
            get: function () {
                return 'aria';
            },
            enumerable: true,
            configurable: true
        });
        Aria.prototype.splice = function (start, deleteCount, elements) {
            this.length += elements.length - deleteCount;
        };
        Aria.prototype.renderTemplate = function (container) {
            return container;
        };
        Aria.prototype.renderElement = function (element, index, container) {
            container.setAttribute('aria-setsize', "" + this.length);
            container.setAttribute('aria-posinset', "" + (index + 1));
        };
        Aria.prototype.disposeTemplate = function (container) {
            // noop
        };
        return Aria;
    }());
    /**
     * The TraitSpliceable is used as a util class to be able
     * to preserve traits across splice calls, given an identity
     * provider.
     */
    var TraitSpliceable = (function () {
        function TraitSpliceable(trait, view, getId) {
            this.trait = trait;
            this.view = view;
            this.getId = getId;
        }
        TraitSpliceable.prototype.splice = function (start, deleteCount, elements) {
            var _this = this;
            if (!this.getId) {
                return this.trait.splice(start, deleteCount, elements.map(function (e) { return false; }));
            }
            var pastElementsWithTrait = this.trait.get().map(function (i) { return _this.getId(_this.view.element(i)); });
            var elementsWithTrait = elements.map(function (e) { return pastElementsWithTrait.indexOf(_this.getId(e)) > -1; });
            this.trait.splice(start, deleteCount, elementsWithTrait);
        };
        return TraitSpliceable;
    }());
    var KeyboardController = (function () {
        function KeyboardController(list, view) {
            this.list = list;
            this.view = view;
            this.disposables = [];
            var onKeyDown = event_1.chain(event_2.domEvent(view.domNode, 'keydown'))
                .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);
        }
        KeyboardController.prototype.onEnter = function (e) {
            e.preventDefault();
            e.stopPropagation();
            this.list.setSelection(this.list.getFocus());
            this.list.open(this.list.getFocus());
        };
        KeyboardController.prototype.onUpArrow = function (e) {
            e.preventDefault();
            e.stopPropagation();
            this.list.focusPrevious();
            this.list.reveal(this.list.getFocus()[0]);
            this.view.domNode.focus();
        };
        KeyboardController.prototype.onDownArrow = function (e) {
            e.preventDefault();
            e.stopPropagation();
            this.list.focusNext();
            this.list.reveal(this.list.getFocus()[0]);
            this.view.domNode.focus();
        };
        KeyboardController.prototype.onPageUpArrow = function (e) {
            e.preventDefault();
            e.stopPropagation();
            this.list.focusPreviousPage();
            this.list.reveal(this.list.getFocus()[0]);
            this.view.domNode.focus();
        };
        KeyboardController.prototype.onPageDownArrow = function (e) {
            e.preventDefault();
            e.stopPropagation();
            this.list.focusNextPage();
            this.list.reveal(this.list.getFocus()[0]);
            this.view.domNode.focus();
        };
        KeyboardController.prototype.dispose = function () {
            this.disposables = lifecycle_1.dispose(this.disposables);
        };
        return KeyboardController;
    }());
    function isSelectionSingleChangeEvent(event) {
        return platform.isMacintosh ? event.metaKey : event.ctrlKey;
    }
    function isSelectionRangeChangeEvent(event) {
        return event.shiftKey;
    }
    function isSelectionChangeEvent(event) {
        return isSelectionSingleChangeEvent(event) || isSelectionRangeChangeEvent(event);
    }
    var MouseController = (function () {
        function MouseController(list, view, options) {
            if (options === void 0) { options = {}; }
            var _this = this;
            this.list = list;
            this.view = view;
            this.options = options;
            this.disposables = [];
            this.disposables.push(view.addListener('mousedown', function (e) { return _this.onMouseDown(e); }));
            this.disposables.push(view.addListener('click', function (e) { return _this.onPointer(e); }));
            this.disposables.push(view.addListener('dblclick', function (e) { return _this.onDoubleClick(e); }));
            this.disposables.push(view.addListener('touchstart', function (e) { return _this.onMouseDown(e); }));
            this.disposables.push(view.addListener(touch_1.EventType.Tap, function (e) { return _this.onPointer(e); }));
        }
        Object.defineProperty(MouseController.prototype, "onContextMenu", {
            get: function () {
                var _this = this;
                var fromKeyboard = event_1.chain(event_2.domEvent(this.view.domNode, 'keydown'))
                    .map(function (e) { return new keyboardEvent_1.StandardKeyboardEvent(e); })
                    .filter(function (e) { return _this.list.getFocus().length > 0; })
                    .filter(function (e) { return e.keyCode === 58 /* ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* F10 */); })
                    .map(function (e) {
                    var index = _this.list.getFocus()[0];
                    var element = _this.view.element(index);
                    var anchor = _this.view.domElement(index);
                    return { index: index, element: element, anchor: anchor };
                })
                    .filter(function (_a) {
                    var anchor = _a.anchor;
                    return !!anchor;
                })
                    .event;
                var fromMouse = event_1.chain(event_1.fromCallback(function (handler) { return _this.view.addListener('contextmenu', handler); }))
                    .map(function (_a) {
                    var element = _a.element, index = _a.index, clientX = _a.clientX, clientY = _a.clientY;
                    return ({ element: element, index: index, anchor: { x: clientX + 1, y: clientY } });
                })
                    .event;
                return event_1.any(fromKeyboard, fromMouse);
            },
            enumerable: true,
            configurable: true
        });
        MouseController.prototype.onMouseDown = function (e) {
            e.preventDefault();
            e.stopPropagation();
            this.view.domNode.focus();
            var reference = this.list.getFocus()[0];
            reference = reference === undefined ? this.list.getSelection()[0] : reference;
            if (isSelectionRangeChangeEvent(e)) {
                return this.changeSelection(e, reference);
            }
            var focus = e.index;
            this.list.setFocus([focus]);
            if (isSelectionChangeEvent(e)) {
                return this.changeSelection(e, reference);
            }
            if (this.options.selectOnMouseDown) {
                this.list.setSelection([focus]);
                this.list.open([focus]);
            }
        };
        MouseController.prototype.onPointer = function (e) {
            e.preventDefault();
            e.stopPropagation();
            if (isSelectionChangeEvent(e)) {
                return;
            }
            var focus = this.list.getFocus();
            this.list.setSelection(focus);
            this.list.open(focus);
        };
        MouseController.prototype.onDoubleClick = function (e) {
            e.preventDefault();
            e.stopPropagation();
            if (isSelectionChangeEvent(e)) {
                return;
            }
            var focus = this.list.getFocus();
            this.list.setSelection(focus);
            this.list.pin(focus);
        };
        MouseController.prototype.changeSelection = function (e, reference) {
            var focus = e.index;
            if (isSelectionRangeChangeEvent(e) && reference !== undefined) {
                var min = Math.min(reference, focus);
                var max = Math.max(reference, focus);
                var rangeSelection = arrays_1.range(max + 1, min);
                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);
            }
            else if (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]));
                }
                else {
                    this.list.setSelection(newSelection);
                }
            }
        };
        MouseController.prototype.dispose = function () {
            this.disposables = lifecycle_1.dispose(this.disposables);
        };
        __decorate([
            decorators_1.memoize
        ], MouseController.prototype, "onContextMenu", null);
        return MouseController;
    }());
    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
    };
    // 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
     * betweem 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 = (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) {
            this.renderers.forEach(function (r, i) { return r.renderElement(element, index, templateData[i]); });
        };
        PipelineRenderer.prototype.disposeTemplate = function (templateData) {
            this.renderers.forEach(function (r, i) { return r.disposeTemplate(templateData[i]); });
        };
        return PipelineRenderer;
    }());
    var List = (function () {
        function List(container, delegate, renderers, options) {
            if (options === void 0) { options = DefaultOptions; }
            var _this = this;
            this.idPrefix = "list_id_" + ++List.InstanceCount;
            this._onContextMenu = event_1.default.None;
            this._onOpen = new event_1.Emitter();
            this._onPin = new event_1.Emitter();
            this._onDispose = new event_1.Emitter();
            var aria = new Aria();
            this.focus = new FocusTrait(function (i) { return _this.getElementDomId(i); });
            this.selection = new Trait('selected');
            this.eventBufferer = new event_1.EventBufferer();
            objects_1.mixin(options, defaultStyles, false);
            renderers = renderers.map(function (r) { return new PipelineRenderer(r.templateId, [aria, _this.focus.renderer, _this.selection.renderer, r]); });
            this.view = new listView_1.ListView(container, delegate, renderers, options);
            this.view.domNode.setAttribute('role', 'tree');
            DOM.addClass(this.view.domNode, this.idPrefix);
            this.view.domNode.tabIndex = 0;
            this.styleElement = DOM.createStyleSheet(this.view.domNode);
            this.spliceable = new CombinedSpliceable([
                aria,
                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._onDispose];
            this.onDOMFocus = event_1.mapEvent(event_2.domEvent(this.view.domNode, 'focus', true), function () { return null; });
            this.onDOMBlur = event_1.mapEvent(event_2.domEvent(this.view.domNode, 'blur', true), function () { return null; });
            if (typeof options.keyboardSupport !== 'boolean' || options.keyboardSupport) {
                var controller = new KeyboardController(this, this.view);
                this.disposables.push(controller);
            }
            if (typeof options.mouseSupport !== 'boolean' || options.mouseSupport) {
                var controller = new MouseController(this, this.view, options);
                this.disposables.push(controller);
                this._onContextMenu = controller.onContextMenu;
            }
            this.onFocusChange(this._onFocusChange, this, this.disposables);
            this.onSelectionChange(this._onSelectionChange, this, this.disposables);
            if (options.ariaLabel) {
                this.view.domNode.setAttribute('aria-label', options.ariaLabel);
            }
            this.style(options);
        }
        Object.defineProperty(List.prototype, "onFocusChange", {
            get: function () {
                var _this = this;
                return event_1.mapEvent(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.mapEvent(this.eventBufferer.wrapEvent(this.selection.onChange), function (e) { return _this.toListEvent(e); });
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(List.prototype, "onContextMenu", {
            get: function () {
                return this._onContextMenu;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(List.prototype, "onOpen", {
            get: function () {
                var _this = this;
                return event_1.mapEvent(this._onOpen.event, function (indexes) { return _this.toListEvent({ indexes: indexes }); });
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(List.prototype, "onPin", {
            get: function () {
                var _this = this;
                return event_1.mapEvent(this._onPin.event, function (indexes) { return _this.toListEvent({ indexes: indexes }); });
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(List.prototype, "onDispose", {
            get: function () { return this._onDispose.event; },
            enumerable: true,
            configurable: true
        });
        List.prototype.splice = function (start, deleteCount, elements) {
            var _this = this;
            if (elements === void 0) { elements = []; }
            this.eventBufferer.bufferEvents(function () { return _this.spliceable.splice(start, deleteCount, elements); });
        };
        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.getContentHeight();
            },
            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.layout = function (height) {
            this.view.layout(height);
        };
        List.prototype.setSelection = function (indexes) {
            indexes = indexes.sort(numericSort);
            this.selection.set(indexes);
        };
        List.prototype.selectNext = function (n, loop) {
            if (n === void 0) { n = 1; }
            if (loop === void 0) { loop = false; }
            if (this.length === 0) {
                return;
            }
            var selection = this.selection.get();
            var index = selection.length > 0 ? selection[0] + n : 0;
            this.setSelection(loop ? [index % this.length] : [Math.min(index, this.length - 1)]);
        };
        List.prototype.selectPrevious = function (n, loop) {
            if (n === void 0) { n = 1; }
            if (loop === void 0) { loop = false; }
            if (this.length === 0) {
                return;
            }
            var selection = this.selection.get();
            var index = selection.length > 0 ? selection[0] - n : 0;
            if (loop && index < 0) {
                index = this.length + (index % this.length);
            }
            this.setSelection([Math.max(index, 0)]);
        };
        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) {
            indexes = indexes.sort(numericSort);
            this.focus.set(indexes);
        };
        List.prototype.focusNext = function (n, loop) {
            if (n === void 0) { n = 1; }
            if (loop === void 0) { loop = false; }
            if (this.length === 0) {
                return;
            }
            var focus = this.focus.get();
            var index = focus.length > 0 ? focus[0] + n : 0;
            this.setFocus(loop ? [index % this.length] : [Math.min(index, this.length - 1)]);
        };
        List.prototype.focusPrevious = function (n, loop) {
            if (n === void 0) { n = 1; }
            if (loop === void 0) { loop = false; }
            if (this.length === 0) {
                return;
            }
            var focus = this.focus.get();
            var index = focus.length > 0 ? focus[0] - n : 0;
            if (loop && index < 0) {
                index = (this.length + (index % this.length)) % this.length;
            }
            this.setFocus([Math.max(index, 0)]);
        };
        List.prototype.focusNextPage = function () {
            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) {
                this.setFocus([lastPageIndex]);
            }
            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(); }, 0);
                }
            }
        };
        List.prototype.focusPreviousPage = function () {
            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) {
                this.setFocus([firstPageIndex]);
            }
            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(); }, 0);
                }
            }
        };
        List.prototype.focusLast = function () {
            if (this.length === 0) {
                return;
            }
            this.setFocus([this.length - 1]);
        };
        List.prototype.focusFirst = function () {
            if (this.length === 0) {
                return;
            }
            this.setFocus([0]);
        };
        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) {
            var scrollTop = this.view.getScrollTop();
            var elementTop = this.view.elementTop(index);
            var elementHeight = this.view.elementHeight(index);
            if (types_1.isNumber(relativeTop)) {
                relativeTop = relativeTop < 0 ? 0 : relativeTop;
                relativeTop = relativeTop > 1 ? 1 : relativeTop;
                // y = mx + b
                var m = elementHeight - this.view.renderHeight;
                this.view.setScrollTop(m * relativeTop + 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);
                }
            }
        };
        List.prototype.getElementDomId = function (index) {
            return this.idPrefix + "_" + index;
        };
        List.prototype.isDOMFocused = function () {
            return this.view.domNode === document.activeElement;
        };
        List.prototype.getHTMLElement = function () {
            return this.view.domNode;
        };
        List.prototype.open = function (indexes) {
            this._onOpen.fire(indexes);
        };
        List.prototype.pin = function (indexes) {
            this._onPin.fire(indexes);
        };
        List.prototype.style = function (styles) {
            var content = [];
            if (styles.listFocusBackground) {
                content.push(".monaco-list." + this.idPrefix + ":focus .monaco-list-row.focused { background-color: " + styles.listFocusBackground + "; }");
            }
            if (styles.listFocusForeground) {
                content.push(".monaco-list." + this.idPrefix + ":focus .monaco-list-row.focused { color: " + styles.listFocusForeground + "; }");
            }
            if (styles.listActiveSelectionBackground) {
                content.push(".monaco-list." + this.idPrefix + ":focus .monaco-list-row.selected { background-color: " + styles.listActiveSelectionBackground + "; }");
                content.push(".monaco-list." + this.idPrefix + ":focus .monaco-list-row.selected:hover { background-color: " + styles.listActiveSelectionBackground + "; }"); // overwrite :hover style in this case!
            }
            if (styles.listActiveSelectionForeground) {
                content.push(".monaco-list." + this.idPrefix + ":focus .monaco-list-row.selected { color: " + styles.listActiveSelectionForeground + "; }");
            }
            if (styles.listFocusAndSelectionBackground) {
                content.push(".monaco-list." + this.idPrefix + ":focus .monaco-list-row.selected.focused { background-color: " + styles.listFocusAndSelectionBackground + "; }");
            }
            if (styles.listFocusAndSelectionForeground) {
                content.push(".monaco-list." + this.idPrefix + ":focus .monaco-list-row.selected.focused { color: " + styles.listFocusAndSelectionForeground + "; }");
            }
            if (styles.listInactiveFocusBackground) {
                content.push(".monaco-list." + this.idPrefix + " .monaco-list-row.focused { background-color:  " + styles.listInactiveFocusBackground + "; }");
                content.push(".monaco-list." + this.idPrefix + " .monaco-list-row.focused:hover { background-color:  " + styles.listInactiveFocusBackground + "; }"); // overwrite :hover style in this case!
            }
            if (styles.listInactiveSelectionBackground) {
                content.push(".monaco-list." + this.idPrefix + " .monaco-list-row.selected { background-color:  " + styles.listInactiveSelectionBackground + "; }");
                content.push(".monaco-list." + this.idPrefix + " .monaco-list-row.selected:hover { background-color:  " + styles.listInactiveSelectionBackground + "; }"); // overwrite :hover style in this case!
            }
            if (styles.listInactiveSelectionForeground) {
                content.push(".monaco-list." + this.idPrefix + " .monaco-list-row.selected { color: " + styles.listInactiveSelectionForeground + "; }");
            }
            if (styles.listHoverBackground) {
                content.push(".monaco-list." + this.idPrefix + " .monaco-list-row:hover { background-color:  " + styles.listHoverBackground + "; }");
            }
            if (styles.listHoverForeground) {
                content.push(".monaco-list." + this.idPrefix + " .monaco-list-row:hover { color:  " + styles.listHoverForeground + "; }");
            }
            if (styles.listSelectionOutline) {
                content.push(".monaco-list." + this.idPrefix + " .monaco-list-row.selected { outline: 1px dotted " + styles.listSelectionOutline + "; outline-offset: -1px; }");
            }
            if (styles.listFocusOutline) {
                content.push(".monaco-list." + this.idPrefix + ":focus .monaco-list-row.focused { outline: 1px solid " + styles.listFocusOutline + "; outline-offset: -1px; }");
            }
            if (styles.listInactiveFocusOutline) {
                content.push(".monaco-list." + this.idPrefix + " .monaco-list-row.focused { outline: 1px dotted " + styles.listInactiveFocusOutline + "; outline-offset: -1px; }");
            }
            if (styles.listHoverOutline) {
                content.push(".monaco-list." + this.idPrefix + " .monaco-list-row:hover { outline: 1px dashed " + styles.listHoverOutline + "; outline-offset: -1px; }");
            }
            this.styleElement.innerHTML = content.join('\n');
        };
        List.prototype.toListEvent = function (_a) {
            var _this = this;
            var indexes = _a.indexes;
            return { indexes: indexes, elements: indexes.map(function (i) { return _this.view.element(i); }) };
        };
        List.prototype._onFocusChange = function () {
            var focus = this.focus.get();
            if (focus.length > 0) {
                this.view.domNode.setAttribute('aria-activedescendant', this.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._onDispose.fire();
            this.disposables = lifecycle_1.dispose(this.disposables);
        };
        List.InstanceCount = 0;
        __decorate([
            decorators_1.memoize
        ], List.prototype, "onFocusChange", null);
        __decorate([
            decorators_1.memoize
        ], List.prototype, "onSelectionChange", null);
        __decorate([
            decorators_1.memoize
        ], List.prototype, "onOpen", null);
        __decorate([
            decorators_1.memoize
        ], List.prototype, "onPin", null);
        return List;
    }());
    exports.List = List;
});











define(__m[238/*vs/base/parts/tree/browser/treeView*/], __M([1/*require*/,0/*exports*/,15/*vs/base/common/platform*/,28/*vs/base/browser/browser*/,7/*vs/base/common/winjs.base*/,3/*vs/base/common/lifecycle*/,4/*vs/base/browser/dom*/,139/*vs/base/common/diff/diff*/,74/*vs/base/browser/touch*/,9/*vs/base/common/strings*/,47/*vs/base/browser/mouseEvent*/,65/*vs/base/browser/keyboardEvent*/,461/*vs/base/parts/tree/browser/treeDnd*/,107/*vs/base/common/iterator*/,63/*vs/base/browser/ui/scrollbar/scrollableElement*/,48/*vs/base/common/scrollable*/,472/*vs/base/parts/tree/browser/treeViewModel*/,448/*vs/base/parts/tree/browser/tree*/,11/*vs/base/common/event*/]), function (require, exports, Platform, Browser, WinJS, Lifecycle, DOM, Diff, Touch, strings, Mouse, Keyboard, dnd, iterator_1, scrollableElement_1, scrollable_1, treeViewModel_1, _, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    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 = (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);
                result = {
                    element: row,
                    templateId: templateId,
                    templateData: this.context.renderer.renderTemplate(this.context.tree, templateId, content)
                };
            }
            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;
            this.context = null;
        };
        return RowCache;
    }());
    exports.RowCache = RowCache;
    var ViewItem = (function () {
        function ViewItem(context, model) {
            var _this = this;
            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.model.isExpanded()));
            }
            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();
                    this.unbindDragStart = null;
                }
                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.context.renderer.renderElement(this.context.tree, this.model.getElement(), this.templateId, this.row.templateData);
            }
        };
        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;
            }
            if (this.unbindDragStart) {
                this.unbindDragStart.dispose();
                this.unbindDragStart = null;
            }
            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;
            this.model = null;
        };
        return ViewItem;
    }());
    exports.ViewItem = ViewItem;
    var RootViewItem = (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 = (function (_super) {
        __extends(TreeView, _super);
        function TreeView(context, container) {
            var _this = _super.call(this) || this;
            _this.lastClickTimeStamp = 0;
            _this.isRefreshing = false;
            _this.refreshingPreviousChildrenIds = {};
            _this._onDOMFocus = new event_1.Emitter();
            _this._onDOMBlur = new event_1.Emitter();
            TreeView.counter++;
            _this.instance = TreeView.counter;
            _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)
            };
            _this.modelListeners = [];
            _this.viewListeners = [];
            _this.dragAndDropListeners = [];
            _this.model = null;
            _this.items = {};
            _this.domNode = document.createElement('div');
            _this.domNode.className = "monaco-tree no-focused-item monaco-tree-instance-" + _this.instance;
            _this.domNode.tabIndex = 0;
            _this.styleElement = DOM.createStyleSheet(_this.domNode);
            // 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: scrollable_1.ScrollbarVisibility.Hidden,
                vertical: (typeof context.options.verticalScrollMode !== 'undefined' ? context.options.verticalScrollMode : scrollable_1.ScrollbarVisibility.Auto),
                useShadows: context.options.useShadows
            });
            _this.scrollableElement.onScroll(function (e) {
                _this.render(e.scrollTop, e.height);
                _this.emit('scroll', e); // TODO@Joao: is anyone interested in this event?
            });
            if (Browser.isIE) {
                _this.wrapper.style.msTouchAction = 'none';
                _this.wrapper.style.msContentZooming = 'none';
            }
            else {
                _this.wrapperGesture = new Touch.Gesture(_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);
            focusTracker.addFocusListener(function () { return _this.onFocus(); });
            focusTracker.addBlurListener(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, 'click', function (e) { return _this.onClick(e); }));
            _this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, 'auxclick', function (e) { return _this.onClick(e); })); // >= Chrome 56
            _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.onHiddenScrollTop = 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
        });
        Object.defineProperty(TreeView.prototype, "onDOMBlur", {
            get: function () { return this._onDOMBlur.event; },
            enumerable: true,
            configurable: true
        });
        TreeView.prototype.applyStyles = function (styles) {
            var content = [];
            if (styles.listFocusBackground) {
                content.push(".monaco-tree.monaco-tree-instance-" + this.instance + ".focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) { background-color: " + styles.listFocusBackground + "; }");
            }
            if (styles.listFocusForeground) {
                content.push(".monaco-tree.monaco-tree-instance-" + this.instance + ".focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) { color: " + styles.listFocusForeground + "; }");
            }
            if (styles.listActiveSelectionBackground) {
                content.push(".monaco-tree.monaco-tree-instance-" + this.instance + ".focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { background-color: " + styles.listActiveSelectionBackground + "; }");
            }
            if (styles.listActiveSelectionForeground) {
                content.push(".monaco-tree.monaco-tree-instance-" + this.instance + ".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.monaco-tree-instance-" + this.instance + ".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.monaco-tree-instance-" + this.instance + ".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.monaco-tree-instance-" + this.instance + " .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { background-color: " + styles.listInactiveSelectionBackground + "; }");
            }
            if (styles.listInactiveSelectionForeground) {
                content.push(".monaco-tree.monaco-tree-instance-" + this.instance + " .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { color: " + styles.listInactiveSelectionForeground + "; }");
            }
            if (styles.listHoverBackground) {
                content.push(".monaco-tree.monaco-tree-instance-" + this.instance + " .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) { background-color: " + styles.listHoverBackground + "; }");
            }
            if (styles.listHoverForeground) {
                content.push(".monaco-tree.monaco-tree-instance-" + this.instance + " .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.monaco-tree-instance-" + this.instance + " .monaco-tree-wrapper.drop-target,\n\t\t\t\t.monaco-tree.monaco-tree-instance-" + this.instance + " .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.monaco-tree-instance-" + this.instance + " .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.monaco-tree-instance-" + this.instance + ".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.monaco-tree-instance-" + this.instance + ".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.monaco-tree-instance-" + this.instance + " .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.monaco-tree-instance-" + this.instance + " .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.monaco-tree-instance-" + this.instance + " .monaco-tree-wrapper.drop-target,\n\t\t\t\t.monaco-tree.monaco-tree-instance-" + this.instance + " .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");
            }
            this.styleElement.innerHTML = content.join('\n');
        };
        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.onVisible = function () {
            this.scrollTop = this.onHiddenScrollTop;
            this.onHiddenScrollTop = null;
            this.setupMSGesture();
        };
        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.onHidden = function () {
            this.onHiddenScrollTop = this.scrollTop;
        };
        TreeView.prototype.isTreeVisible = function () {
            return this.onHiddenScrollTop === null;
        };
        TreeView.prototype.layout = function (height) {
            if (!this.isTreeVisible()) {
                return;
            }
            this.viewHeight = height || DOM.getContentHeight(this.wrapper); // render
        };
        TreeView.prototype.render = function (scrollTop, viewHeight) {
            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';
            }
            this.lastRenderTop = renderTop;
            this.lastRenderHeight = renderBottom - renderTop;
        };
        TreeView.prototype.setModel = function (newModel) {
            var _this = this;
            this.releaseModel();
            this.model = newModel;
            this.modelListeners.push(this.model.addBulkListener(function (e) { return _this.onModelEvents(e); }));
        };
        TreeView.prototype.onModelEvents = function (events) {
            var elementsToRefresh = [];
            for (var i = 0, len = events.length; i < len; i++) {
                var event = events[i];
                var data = event.data;
                switch (event.type) {
                    case 'refreshing':
                        this.onRefreshing();
                        break;
                    case 'refreshed':
                        this.onRefreshed();
                        break;
                    case 'clearingInput':
                        this.onClearingInput(data);
                        break;
                    case 'setInput':
                        this.onSetInput(data);
                        break;
                    case 'item:childrenRefreshing':
                        this.onItemChildrenRefreshing(data);
                        break;
                    case 'item:childrenRefreshed':
                        this.onItemChildrenRefreshed(data);
                        break;
                    case 'item:refresh':
                        elementsToRefresh.push(data.item);
                        break;
                    case 'item:expanding':
                        this.onItemExpanding(data);
                        break;
                    case 'item:expanded':
                        this.onItemExpanded(data);
                        break;
                    case 'item:collapsing':
                        this.onItemCollapsing(data);
                        break;
                    case 'item:reveal':
                        this.onItemReveal(data);
                        break;
                    case 'item:addTrait':
                        this.onItemAddTrait(data);
                        break;
                    case 'item:removeTrait':
                        this.onItemRemoveTrait(data);
                        break;
                    case 'focus':
                        this.onModelFocusChange();
                        break;
                }
            }
            if (elementsToRefresh.length > 0) {
                this.onItemsRefresh(elementsToRefresh);
            }
        };
        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;
        };
        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 scrollState = this.scrollableElement.getScrollState();
                return scrollState.height;
            },
            set: function (viewHeight) {
                this.scrollableElement.updateState({
                    height: viewHeight,
                    scrollHeight: this.getTotalHeight()
                });
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TreeView.prototype, "scrollTop", {
            get: function () {
                var scrollState = this.scrollableElement.getScrollState();
                return scrollState.scrollTop;
            },
            set: function (scrollTop) {
                this.scrollableElement.updateState({
                    scrollTop: scrollTop,
                    scrollHeight: this.getTotalHeight()
                });
            },
            enumerable: true,
            configurable: true
        });
        TreeView.prototype.getScrollPosition = function () {
            var height = this.getTotalHeight() - this.viewHeight;
            return height <= 0 ? 0 : this.scrollTop / height;
        };
        TreeView.prototype.setScrollPosition = function (pos) {
            var height = this.getTotalHeight() - this.viewHeight;
            this.scrollTop = height * pos;
        };
        // 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);
            this.emit('viewItem:create', { item: this.inputItem.model });
        };
        TreeView.prototype.onItemChildrenRefreshing = function (e) {
            var item = e.item;
            var viewItem = this.items[item.id];
            if (viewItem) {
                viewItem.loadingTimer = setTimeout(function () {
                    viewItem.loadingTimer = 0;
                    viewItem.loading = true;
                }, TreeView.LOADING_DECORATION_DELAY);
            }
            if (!e.isNested) {
                var childrenIds = [];
                var navigator = item.getNavigator();
                var childItem;
                while (childItem = navigator.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 = this.refreshingPreviousChildrenIds[item.id];
                var afterModelItems = [];
                var navigator = item.getNavigator();
                var childItem;
                while (childItem = navigator.next()) {
                    afterModelItems.push(childItem);
                }
                var skipDiff = Math.abs(previousChildrenIds.length - afterModelItems.length) > 1000;
                var diff = void 0;
                var doToInsertItemsAlreadyExist = void 0;
                if (!skipDiff) {
                    var lcs = new Diff.LcsDiff({
                        getLength: function () { return previousChildrenIds.length; },
                        getElementHash: function (i) { return previousChildrenIds[i]; }
                    }, {
                        getLength: function () { return afterModelItems.length; },
                        getElementHash: function (i) { return afterModelItems[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[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, len = diff.length; i < len; i++) {
                        var diffChange = diff[i];
                        if (diffChange.originalLength > 0) {
                            this.onRemoveItems(new iterator_1.ArrayIterator(previousChildrenIds, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength));
                        }
                        if (diffChange.modifiedLength > 0) {
                            var beforeItem = afterModelItems[diffChange.modifiedStart - 1] || item;
                            beforeItem = beforeItem.getDepth() > 0 ? beforeItem : null;
                            this.onInsertItems(new iterator_1.ArrayIterator(afterModelItems, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength), beforeItem ? beforeItem.id : null);
                        }
                    }
                }
                else if (skipDiff || diff.length) {
                    this.onRemoveItems(new iterator_1.ArrayIterator(previousChildrenIds));
                    this.onInsertItems(new iterator_1.ArrayIterator(afterModelItems), item.getDepth() > 0 ? item.id : null);
                }
                if (skipDiff || diff.length) {
                    this.onRowsChanged();
                }
            }
        };
        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);
                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.getRelativeTop = function (item) {
            if (item && item.isVisible()) {
                var viewItem = this.items[item.id];
                if (viewItem) {
                    return (viewItem.top - this.scrollTop) / (this.viewHeight - viewItem.height);
                }
            }
            return -1;
        };
        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();
            this.emit('viewItem:dispose', { item: this.inputItem.model });
            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.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();
                if (!element) {
                    return;
                }
                var id = this.context.dataSource.getId(this.context.tree, element);
                var viewItem = this.items[id];
                var 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 (this.didJustPressContextMenuKey) {
                event.preventDefault();
                event.stopPropagation();
            }
            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)
            }
            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('URL', 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);
            TreeView.currentExternalDragAndDropData = 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 === undefined) {
                        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;
            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 = [];
                    if (this.currentDropPromise) {
                        this.currentDropPromise.cancel();
                        this.currentDropPromise = null;
                    }
                }
                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 (TreeView.currentExternalDragAndDropData) {
                    this.currentDragAndDropData = TreeView.currentExternalDragAndDropData;
                }
                else {
                    if (!event.dataTransfer.types) {
                        return false;
                    }
                    this.currentDragAndDropData = new dnd.DesktopDragAndDropData();
                }
            }
            this.currentDragAndDropData.update(event);
            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 !== _.DragOverBubble.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 === _.DragOverEffect.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 = [];
                    if (this.currentDropPromise) {
                        this.currentDropPromise.cancel();
                        this.currentDropPromise = null;
                    }
                }
                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 === _.DragOverBubble.BUBBLE_DOWN) {
                        var nav = item.getNavigator();
                        var child;
                        while (child = nav.next()) {
                            viewItem = this.items[child.id];
                            if (viewItem) {
                                viewItem.dropTarget = true;
                                this.currentDropTargets.push(viewItem);
                            }
                        }
                    }
                    if (reaction.autoExpand) {
                        this.currentDropPromise = WinJS.TPromise.timeout(500)
                            .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 = new Mouse.DragMouseEvent(e);
                event.preventDefault();
                this.currentDragAndDropData.update(event);
                this.context.dnd.drop(this.context.tree, this.currentDragAndDropData, this.currentDropElement, event);
                this.onDragEnd(e);
            }
            this.cancelDragAndDropScrollInterval();
        };
        TreeView.prototype.onDragEnd = function (e) {
            if (this.currentDropTarget) {
                this.currentDropTargets.forEach(function (i) { return i.dropTarget = false; });
                this.currentDropTargets = [];
            }
            if (this.currentDropPromise) {
                this.currentDropPromise.cancel();
                this.currentDropPromise = null;
            }
            this.cancelDragAndDropScrollInterval();
            this.currentDragAndDropData = null;
            TreeView.currentExternalDragAndDropData = null;
            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;
            do {
                if (element[TreeView.BINDING]) {
                    candidate = element[TreeView.BINDING];
                }
                if (element === this.wrapper || element === this.domNode) {
                    return candidate;
                }
                if (element === document.body) {
                    return null;
                }
            } while (element = element.parentElement);
            return undefined;
        };
        // Cleanup
        TreeView.prototype.releaseModel = function () {
            if (this.model) {
                this.modelListeners = Lifecycle.dispose(this.modelListeners);
                this.model = null;
            }
        };
        TreeView.prototype.dispose = function () {
            // TODO@joao: improve
            this.scrollableElement.dispose();
            this.releaseModel();
            this.modelListeners = null;
            this.viewListeners = Lifecycle.dispose(this.viewListeners);
            this._onDOMFocus.dispose();
            this._onDOMBlur.dispose();
            if (this.domNode.parentNode) {
                this.domNode.parentNode.removeChild(this.domNode);
            }
            this.domNode = null;
            if (this.wrapperGesture) {
                this.wrapperGesture.dispose();
                this.wrapperGesture = null;
            }
            if (this.context.cache) {
                this.context.cache.dispose();
                this.context.cache = null;
            }
            _super.prototype.dispose.call(this);
        };
        TreeView.BINDING = 'monaco-tree-row';
        TreeView.LOADING_DECORATION_DELAY = 800;
        TreeView.counter = 0;
        TreeView.currentExternalDragAndDropData = null;
        return TreeView;
    }(treeViewModel_1.HeightMap));
    exports.TreeView = TreeView;
});

define(__m[249/*vs/css!vs/base/browser/ui/selectBox/selectBox*/], __M([5/*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[259/*vs/base/browser/ui/selectBox/selectBox*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,11/*vs/base/common/event*/,41/*vs/base/browser/ui/widget*/,4/*vs/base/browser/dom*/,33/*vs/base/common/arrays*/,32/*vs/base/common/color*/,26/*vs/base/common/objects*/,249/*vs/css!vs/base/browser/ui/selectBox/selectBox*/]), function (require, exports, lifecycle_1, event_1, widget_1, dom, arrays, color_1, objects_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.defaultStyles = {
        selectBackground: color_1.Color.fromHex('#3C3C3C'),
        selectForeground: color_1.Color.fromHex('#F0F0F0'),
        selectBorder: color_1.Color.fromHex('#3C3C3C')
    };
    var SelectBox = (function (_super) {
        __extends(SelectBox, _super);
        function SelectBox(options, selected, styles) {
            if (styles === void 0) { styles = objects_1.clone(exports.defaultStyles); }
            var _this = _super.call(this) || this;
            _this.selectElement = document.createElement('select');
            _this.selectElement.className = 'select-box';
            _this.setOptions(options, selected);
            _this.toDispose = [];
            _this._onDidSelect = new event_1.Emitter();
            _this.selectBackground = styles.selectBackground;
            _this.selectForeground = styles.selectForeground;
            _this.selectBorder = styles.selectBorder;
            _this.toDispose.push(dom.addStandardDisposableListener(_this.selectElement, 'change', function (e) {
                _this.selectElement.title = e.target.value;
                _this._onDidSelect.fire({
                    index: e.target.selectedIndex,
                    selected: e.target.value
                });
            }));
            _this.toDispose.push(dom.addStandardDisposableListener(_this.selectElement, 'keydown', function (e) {
                if (e.equals(10 /* Space */) || e.equals(3 /* Enter */)) {
                    // Space is used to expand select box, do not propagate it (prevent action bar action run)
                    e.stopPropagation();
                }
            }));
            return _this;
        }
        Object.defineProperty(SelectBox.prototype, "onDidSelect", {
            get: function () {
                return this._onDidSelect.event;
            },
            enumerable: true,
            configurable: true
        });
        SelectBox.prototype.setOptions = function (options, selected, disabled) {
            var _this = this;
            if (!this.options || !arrays.equals(this.options, options)) {
                this.options = options;
                this.selectElement.options.length = 0;
                var i_1 = 0;
                this.options.forEach(function (option) {
                    _this.selectElement.add(_this.createOption(option, disabled === i_1++));
                });
            }
            this.select(selected);
        };
        SelectBox.prototype.select = function (index) {
            if (index >= 0 && index < this.options.length) {
                this.selected = index;
            }
            else if (this.selected < 0) {
                this.selected = 0;
            }
            this.selectElement.selectedIndex = this.selected;
            this.selectElement.title = this.options[this.selected];
        };
        SelectBox.prototype.focus = function () {
            if (this.selectElement) {
                this.selectElement.focus();
            }
        };
        SelectBox.prototype.blur = function () {
            if (this.selectElement) {
                this.selectElement.blur();
            }
        };
        SelectBox.prototype.render = function (container) {
            this.container = container;
            dom.addClass(container, 'select-container');
            container.appendChild(this.selectElement);
            this.setOptions(this.options, this.selected);
            this.applyStyles();
        };
        SelectBox.prototype.style = function (styles) {
            this.selectBackground = styles.selectBackground;
            this.selectForeground = styles.selectForeground;
            this.selectBorder = styles.selectBorder;
            this.applyStyles();
        };
        SelectBox.prototype.applyStyles = function () {
            if (this.selectElement) {
                var background = this.selectBackground ? this.selectBackground.toString() : null;
                var foreground = this.selectForeground ? this.selectForeground.toString() : null;
                var border = this.selectBorder ? this.selectBorder.toString() : null;
                this.selectElement.style.backgroundColor = background;
                this.selectElement.style.color = foreground;
                this.selectElement.style.borderColor = border;
            }
        };
        SelectBox.prototype.createOption = function (value, disabled) {
            var option = document.createElement('option');
            option.value = value;
            option.text = value;
            option.disabled = disabled;
            return option;
        };
        SelectBox.prototype.dispose = function () {
            this.toDispose = lifecycle_1.dispose(this.toDispose);
            _super.prototype.dispose.call(this);
        };
        return SelectBox;
    }(widget_1.Widget));
    exports.SelectBox = SelectBox;
});

define(__m[260/*vs/css!vs/base/parts/quickopen/browser/quickopen*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[261/*vs/css!vs/base/parts/tree/browser/tree*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[270/*vs/css!vs/editor/browser/controller/textAreaHandler*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[274/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[277/*vs/css!vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[278/*vs/css!vs/editor/browser/viewParts/decorations/decorations*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[279/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[280/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[283/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[286/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[288/*vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[291/*vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[294/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[296/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[299/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[300/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[306/*vs/css!vs/editor/browser/viewParts/selections/selections*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[307/*vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[308/*vs/css!vs/editor/browser/widget/media/diffEditor*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[309/*vs/css!vs/editor/browser/widget/media/diffReview*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[310/*vs/css!vs/editor/browser/widget/media/editor*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[312/*vs/css!vs/editor/browser/widget/media/tokens*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[313/*vs/css!vs/editor/contrib/bracketMatching/browser/bracketMatching*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[314/*vs/css!vs/editor/contrib/clipboard/browser/clipboard*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[315/*vs/css!vs/editor/contrib/codelens/browser/codelensWidget*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[316/*vs/css!vs/editor/contrib/colorPicker/browser/colorPicker*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[325/*vs/css!vs/editor/contrib/dnd/browser/dnd*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[327/*vs/css!vs/editor/contrib/find/browser/findWidget*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[328/*vs/css!vs/editor/contrib/folding/browser/folding*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[171/*vs/css!vs/editor/contrib/goToDeclaration/browser/goToDeclarationMouse*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[335/*vs/css!vs/editor/contrib/goToDeclaration/browser/messageController*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[366/*vs/css!vs/editor/contrib/gotoError/browser/gotoError*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[388/*vs/css!vs/editor/contrib/hover/browser/hover*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[389/*vs/css!vs/editor/contrib/links/browser/links*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[390/*vs/css!vs/editor/contrib/parameterHints/browser/parameterHints*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[391/*vs/css!vs/editor/contrib/quickFix/browser/lightBulbWidget*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[392/*vs/css!vs/editor/contrib/referenceSearch/browser/referencesWidget*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[393/*vs/css!vs/editor/contrib/rename/browser/renameInputField*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[394/*vs/css!vs/editor/contrib/snippet/browser/snippetSession*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[395/*vs/css!vs/editor/contrib/suggest/browser/media/suggest*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[396/*vs/css!vs/editor/contrib/zoneWidget/browser/peekViewWidget*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[399/*vs/css!vs/editor/contrib/zoneWidget/browser/zoneWidget*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[400/*vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[402/*vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[403/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[404/*vs/css!vs/editor/standalone/browser/quickOpen/gotoLine*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[405/*vs/css!vs/editor/standalone/browser/quickOpen/quickOutline*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[408/*vs/css!vs/editor/standalone/browser/standalone-tokens*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[409/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/], __M([5/*vs/css!vs/editor/editor.main*/]), {});
define(__m[410/*vs/editor/browser/config/charWidthReader*/], __M([1/*require*/,0/*exports*/]), 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 CharWidthRequestType;
    (function (CharWidthRequestType) {
        CharWidthRequestType[CharWidthRequestType["Regular"] = 0] = "Regular";
        CharWidthRequestType[CharWidthRequestType["Italic"] = 1] = "Italic";
        CharWidthRequestType[CharWidthRequestType["Bold"] = 2] = "Bold";
    })(CharWidthRequestType = exports.CharWidthRequestType || (exports.CharWidthRequestType = {}));
    var CharWidthRequest = (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 = (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.fontFamily;
            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.fontFamily;
            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.fontFamily;
            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 = '&nbsp;';
                // 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;
});











define(__m[412/*vs/editor/browser/config/elementSizeObserver*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ElementSizeObserver = (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;
});

define(__m[25/*vs/editor/browser/editorBrowser*/], __M([1/*require*/,0/*exports*/]), 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 });
    /**
     * 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 = {}));
});











define(__m[114/*vs/editor/browser/editorDom*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,47/*vs/base/browser/mouseEvent*/,4/*vs/base/browser/dom*/,83/*vs/base/browser/globalMouseMoveMonitor*/]), function (require, exports, lifecycle_1, mouseEvent_1, dom, globalMouseMoveMonitor_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * Coordinates relative to the whole document (e.g. mouse event's pageX and pageY)
     */
    var PageCoordinates = (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 = (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 = (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 = (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 = (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 = (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 <<capture>> 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;
});

define(__m[112/*vs/editor/browser/view/viewLayer*/], __M([1/*require*/,0/*exports*/,27/*vs/base/browser/fastDomNode*/]), function (require, exports, fastDomNode_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var RenderedLinesCollection = (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: ' + 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 = (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 = (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.join('');
            }
            else {
                lastChild.insertAdjacentHTML('afterend', newLinesHTML.join(''));
            }
            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.join('');
            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 hadNewLine = false;
            var wasNew = [];
            var newLinesHTML = [];
            var hadInvalidLine = false;
            var wasInvalid = [];
            var invalidLinesHTML = [];
            for (var i = 0, len = ctx.linesLength; i < len; i++) {
                var line = ctx.lines[i];
                var lineNumber = i + ctx.rendLineNumberStart;
                wasNew[i] = false;
                wasInvalid[i] = false;
                var renderResult = line.renderLine(lineNumber, deltaTop[i], this.viewportData);
                if (renderResult !== null) {
                    // Line needs rendering
                    var lineDomNode = line.getDomNode();
                    if (!lineDomNode) {
                        // Line is new
                        newLinesHTML.push(renderResult);
                        wasNew[i] = true;
                        hadNewLine = true;
                    }
                    else {
                        // Line is invalid
                        invalidLinesHTML.push(renderResult);
                        wasInvalid[i] = true;
                        hadInvalidLine = true;
                    }
                }
            }
            if (hadNewLine) {
                this._finishRenderingNewLines(ctx, domNodeIsEmpty, newLinesHTML, wasNew);
            }
            if (hadInvalidLine) {
                this._finishRenderingInvalidLines(ctx, invalidLinesHTML, wasInvalid);
            }
        };
        return ViewLayerRenderer;
    }());
});

define(__m[135/*vs/editor/common/config/editorZoom*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/event*/]), function (require, exports, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorZoom = new (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(-9, zoomLevel), 9);
            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[54/*vs/editor/common/controller/cursorEvents*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * 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 = {}));
});

define(__m[131/*vs/editor/common/core/editorState*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/]), function (require, exports, strings) {
    /*---------------------------------------------------------------------------------------------
     *  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 CodeEditorStateFlag;
    (function (CodeEditorStateFlag) {
        CodeEditorStateFlag[CodeEditorStateFlag["Value"] = 1] = "Value";
        CodeEditorStateFlag[CodeEditorStateFlag["Selection"] = 2] = "Selection";
        CodeEditorStateFlag[CodeEditorStateFlag["Position"] = 4] = "Position";
        CodeEditorStateFlag[CodeEditorStateFlag["Scroll"] = 8] = "Scroll";
    })(CodeEditorStateFlag = exports.CodeEditorStateFlag || (exports.CodeEditorStateFlag = {}));
    var EditorState = (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;
});

define(__m[12/*vs/editor/common/core/position*/], __M([1/*require*/,0/*exports*/]), 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 });
    /**
     * A position in the editor.
     */
    var Position = (function () {
        function Position(lineNumber, column) {
            this.lineNumber = lineNumber;
            this.column = column;
        }
        /**
         * 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[2/*vs/editor/common/core/range*/], __M([1/*require*/,0/*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 = (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, startColumn, endLineNumber, 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, resultStartColumn = a.startColumn, resultEndLineNumber = a.endLineNumber, resultEndColumn = a.endColumn, otherStartLineNumber = b.startLineNumber, otherStartColumn = b.startColumn, otherEndLineNumber = b.endLineNumber, 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);
        };
        /**
         * Clone this range.
         */
        Range.prototype.cloneRange = function () {
            return new Range(this.startLineNumber, this.startColumn, this.endLineNumber, this.endColumn);
        };
        /**
         * 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);
        };
        /**
         * Create a `Range` from an `IRange`.
         */
        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;
        };
        /**
         * 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) {
            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;
        };
        /**
         * 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;
});











define(__m[164/*vs/editor/browser/widget/diffNavigator*/], __M([1/*require*/,0/*exports*/,72/*vs/base/common/assert*/,38/*vs/base/common/eventEmitter*/,26/*vs/base/common/objects*/,2/*vs/editor/common/core/range*/,3/*vs/base/common/lifecycle*/]), function (require, exports, assert, eventEmitter_1, objects, range_1, lifecycle_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var defaultOptions = {
        followsCaret: true,
        ignoreCharChanges: true,
        alwaysRevealFirst: true
    };
    /**
     * Create a new diff navigator for the provided diff editor.
     */
    var DiffNavigator = (function (_super) {
        __extends(DiffNavigator, _super);
        function DiffNavigator(editor, options) {
            if (options === void 0) { options = {}; }
            var _this = _super.call(this, [
                DiffNavigator.Events.UPDATED
            ]) || this;
            _this.editor = editor;
            _this.options = objects.mixin(options, defaultOptions, false);
            _this.disposed = false;
            _this.toUnbind = [];
            _this.nextIdx = -1;
            _this.ranges = [];
            _this.ignoreSelectionChange = false;
            _this.revealFirst = _this.options.alwaysRevealFirst;
            // hook up to diff editor for diff, disposal, and caret move
            _this.toUnbind.push(_this.editor.onDidDispose(function () { return _this.dispose(); }));
            _this.toUnbind.push(_this.editor.onDidUpdateDiff(function () { return _this.onDiffUpdated(); }));
            if (_this.options.followsCaret) {
                _this.toUnbind.push(_this.editor.getModifiedEditor().onDidChangeCursorPosition(function (e) {
                    if (_this.ignoreSelectionChange) {
                        return;
                    }
                    _this.nextIdx = -1;
                }));
            }
            if (_this.options.alwaysRevealFirst) {
                _this.toUnbind.push(_this.editor.getModifiedEditor().onDidChangeModel(function (e) {
                    _this.revealFirst = true;
                }));
            }
            // init things
            _this.init();
            return _this;
        }
        DiffNavigator.prototype.init = function () {
            var changes = this.editor.getLineChanges();
            if (!changes) {
                return;
            }
        };
        DiffNavigator.prototype.onDiffUpdated = function () {
            this.init();
            this.compute(this.editor.getLineChanges());
            if (this.revealFirst) {
                // Only reveal first on first non-null changes
                if (this.editor.getLineChanges() !== null) {
                    this.revealFirst = false;
                    this.nextIdx = -1;
                    this.next();
                }
            }
        };
        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.emit(DiffNavigator.Events.UPDATED, {});
        };
        DiffNavigator.prototype.initIdx = function (fwd) {
            var found = false;
            var position = this.editor.getPosition();
            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) {
            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);
            }
            finally {
                this.ignoreSelectionChange = false;
            }
        };
        DiffNavigator.prototype.canNavigate = function () {
            return this.ranges && this.ranges.length > 0;
        };
        DiffNavigator.prototype.next = function () {
            this.move(true);
        };
        DiffNavigator.prototype.previous = function () {
            this.move(false);
        };
        DiffNavigator.prototype.dispose = function () {
            this.toUnbind = lifecycle_1.dispose(this.toUnbind);
            this.ranges = null;
            this.disposed = true;
            _super.prototype.dispose.call(this);
        };
        DiffNavigator.Events = {
            UPDATED: 'navigation.updated'
        };
        return DiffNavigator;
    }(eventEmitter_1.EventEmitter));
    exports.DiffNavigator = DiffNavigator;
});

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

define(__m[435/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,59/*vs/editor/common/core/editOperation*/,2/*vs/editor/common/core/range*/]), function (require, exports, strings, editOperation_1, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var TrimTrailingWhitespaceCommand = (function () {
        function TrimTrailingWhitespaceCommand(selection) {
            this.selection = selection;
        }
        TrimTrailingWhitespaceCommand.prototype.getEditOperations = function (model, builder) {
            var ops = trimTrailingWhitespace(model, []);
            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;
});











define(__m[22/*vs/editor/common/core/selection*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/,12/*vs/editor/common/core/position*/]), function (require, exports, range_1, position_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * 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 = {}));
    /**
     * A selection in the editor.
     * The selection is a range that has an orientation.
     */
    var Selection = (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 SelectionDirection.LTR;
            }
            return SelectionDirection.RTL;
        };
        /**
         * Create a new selection with a different `positionLineNumber` and `positionColumn`.
         */
        Selection.prototype.setEndPosition = function (endLineNumber, endColumn) {
            if (this.getDirection() === SelectionDirection.LTR) {
                return new Selection(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
            }
            return new Selection(endLineNumber, endColumn, this.startLineNumber, this.startColumn);
        };
        /**
         * Get the position at `positionLineNumber` and `positionColumn`.
         */
        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() === SelectionDirection.LTR) {
                return new Selection(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
            }
            return new Selection(this.endLineNumber, this.endColumn, startLineNumber, startColumn);
        };
        // ----
        /**
         * Create a `Selection` from one or two positions
         */
        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 === SelectionDirection.LTR) {
                return new Selection(startLineNumber, startColumn, endLineNumber, endColumn);
            }
            return new Selection(endLineNumber, endColumn, startLineNumber, startColumn);
        };
        return Selection;
    }(range_1.Range));
    exports.Selection = Selection;
});

define(__m[73/*vs/editor/common/commands/replaceCommand*/], __M([1/*require*/,0/*exports*/,22/*vs/editor/common/core/selection*/]), function (require, exports, selection_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ReplaceCommand = (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 = (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 = (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 = (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;
});

define(__m[441/*vs/editor/common/commands/surroundSelectionCommand*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var SurroundSelectionCommand = (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;
});

define(__m[97/*vs/editor/common/core/token*/], __M([1/*require*/,0/*exports*/]), 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 Token = (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 = (function () {
        function TokenizationResult(tokens, endState) {
            this.tokens = tokens;
            this.endState = endState;
        }
        return TokenizationResult;
    }());
    exports.TokenizationResult = TokenizationResult;
    var TokenizationResult2 = (function () {
        function TokenizationResult2(tokens, endState) {
            this.tokens = tokens;
            this.endState = endState;
        }
        return TokenizationResult2;
    }());
    exports.TokenizationResult2 = TokenizationResult2;
});

define(__m[96/*vs/editor/common/core/uint*/], __M([1/*require*/,0/*exports*/]), 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 Uint8Matrix = (function () {
        function Uint8Matrix(rows, cols, defaultValue) {
            var data = new Uint8Array(rows * cols);
            for (var i = 0, len = rows * cols; i < len; i++) {
                data[i] = defaultValue;
            }
            this._data = data;
            this._rows = rows;
            this._cols = cols;
        }
        Uint8Matrix.prototype.get = function (row, col) {
            return this._data[row * this._cols + col];
        };
        Uint8Matrix.prototype.set = function (row, col, value) {
            this._data[row * this._cols + col] = value;
        };
        return Uint8Matrix;
    }());
    exports.Uint8Matrix = Uint8Matrix;
    var Constants;
    (function (Constants) {
        /**
         * MAX SMI (SMall Integer) as defined in v8.
         * one bit is lost for boxing/unboxing flag.
         * one bit is lost for sign flag.
         * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values
         */
        Constants[Constants["MAX_SAFE_SMALL_INTEGER"] = 1073741824] = "MAX_SAFE_SMALL_INTEGER";
        /**
         * MIN SMI (SMall Integer) as defined in v8.
         * one bit is lost for boxing/unboxing flag.
         * one bit is lost for sign flag.
         * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values
         */
        Constants[Constants["MIN_SAFE_SMALL_INTEGER"] = -1073741824] = "MIN_SAFE_SMALL_INTEGER";
        /**
         * Max unsigned integer that fits on 8 bits.
         */
        Constants[Constants["MAX_UINT_8"] = 255] = "MAX_UINT_8";
        /**
         * Max unsigned integer that fits on 16 bits.
         */
        Constants[Constants["MAX_UINT_16"] = 65535] = "MAX_UINT_16";
        /**
         * Max unsigned integer that fits on 32 bits.
         */
        Constants[Constants["MAX_UINT_32"] = 4294967295] = "MAX_UINT_32";
    })(Constants = exports.Constants || (exports.Constants = {}));
    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;
});

define(__m[89/*vs/editor/common/core/characterClassifier*/], __M([1/*require*/,0/*exports*/,96/*vs/editor/common/core/uint*/]), function (require, exports, uint_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * A fast character classifier that uses a compact array for ASCII values.
     */
    var CharacterClassifier = (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 Boolean;
    (function (Boolean) {
        Boolean[Boolean["False"] = 0] = "False";
        Boolean[Boolean["True"] = 1] = "True";
    })(Boolean || (Boolean = {}));
    var CharacterSet = (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;
});











define(__m[94/*vs/editor/common/controller/wordCharacterClassifier*/], __M([1/*require*/,0/*exports*/,89/*vs/editor/common/core/characterClassifier*/]), function (require, exports, characterClassifier_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var WordCharacterClass;
    (function (WordCharacterClass) {
        WordCharacterClass[WordCharacterClass["Regular"] = 0] = "Regular";
        WordCharacterClass[WordCharacterClass["Whitespace"] = 1] = "Whitespace";
        WordCharacterClass[WordCharacterClass["WordSeparator"] = 2] = "WordSeparator";
    })(WordCharacterClass = exports.WordCharacterClass || (exports.WordCharacterClass = {}));
    var WordCharacterClassifier = (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); });
});











define(__m[457/*vs/editor/common/diff/diffComputer*/], __M([1/*require*/,0/*exports*/,139/*vs/base/common/diff/diff*/,9/*vs/base/common/strings*/]), function (require, exports, diff_1, strings) {
    /*---------------------------------------------------------------------------------------------
     *  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 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 MarkerSequence = (function () {
        function MarkerSequence(buffer, startMarkers, endMarkers) {
            this.buffer = buffer;
            this.startMarkers = startMarkers;
            this.endMarkers = endMarkers;
        }
        MarkerSequence.prototype.equals = function (other) {
            if (!(other instanceof MarkerSequence)) {
                return false;
            }
            var otherMarkerSequence = other;
            if (this.getLength() !== otherMarkerSequence.getLength()) {
                return false;
            }
            for (var i = 0, len = this.getLength(); i < len; i++) {
                var myElement = this.getElementHash(i);
                var otherElement = otherMarkerSequence.getElementHash(i);
                if (myElement !== otherElement) {
                    return false;
                }
            }
            return true;
        };
        MarkerSequence.prototype.getLength = function () {
            return this.startMarkers.length;
        };
        MarkerSequence.prototype.getElementHash = function (i) {
            return this.buffer.substring(this.startMarkers[i].offset, this.endMarkers[i].offset);
        };
        MarkerSequence.prototype.getStartLineNumber = function (i) {
            if (i === this.startMarkers.length) {
                // This is the special case where a change happened after the last marker
                return this.startMarkers[i - 1].lineNumber + 1;
            }
            return this.startMarkers[i].lineNumber;
        };
        MarkerSequence.prototype.getStartColumn = function (i) {
            return this.startMarkers[i].column;
        };
        MarkerSequence.prototype.getEndLineNumber = function (i) {
            return this.endMarkers[i].lineNumber;
        };
        MarkerSequence.prototype.getEndColumn = function (i) {
            return this.endMarkers[i].column;
        };
        return MarkerSequence;
    }());
    var LineMarkerSequence = (function (_super) {
        __extends(LineMarkerSequence, _super);
        function LineMarkerSequence(lines) {
            var _this = this;
            var buffer = '';
            var startMarkers = [];
            var endMarkers = [];
            for (var pos = 0, i = 0, length_1 = lines.length; i < length_1; i++) {
                buffer += lines[i];
                var startColumn = LineMarkerSequence._getFirstNonBlankColumn(lines[i], 1);
                var endColumn = LineMarkerSequence._getLastNonBlankColumn(lines[i], 1);
                startMarkers.push({
                    offset: pos + startColumn - 1,
                    lineNumber: i + 1,
                    column: startColumn
                });
                endMarkers.push({
                    offset: pos + endColumn - 1,
                    lineNumber: i + 1,
                    column: endColumn
                });
                pos += lines[i].length;
            }
            _this = _super.call(this, buffer, startMarkers, endMarkers) || this;
            return _this;
        }
        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 (startIndex, endIndex) {
            var startMarkers = [];
            var endMarkers = [];
            for (var index = startIndex; index <= endIndex; index++) {
                var startMarker = this.startMarkers[index];
                var endMarker = this.endMarkers[index];
                for (var i = startMarker.offset; i < endMarker.offset; i++) {
                    startMarkers.push({
                        offset: i,
                        lineNumber: startMarker.lineNumber,
                        column: startMarker.column + (i - startMarker.offset)
                    });
                    endMarkers.push({
                        offset: i + 1,
                        lineNumber: startMarker.lineNumber,
                        column: startMarker.column + (i - startMarker.offset) + 1
                    });
                }
            }
            return new MarkerSequence(this.buffer, startMarkers, endMarkers);
        };
        return LineMarkerSequence;
    }(MarkerSequence));
    var CharChange = (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 = (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 (diffChange, originalLineSequence, modifiedLineSequence, continueProcessingPredicate, shouldPostProcessCharChanges) {
            var originalStartLineNumber;
            var originalEndLineNumber;
            var modifiedStartLineNumber;
            var modifiedEndLineNumber;
            var charChanges;
            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 (diffChange.originalLength !== 0 && diffChange.modifiedLength !== 0 && continueProcessingPredicate()) {
                var originalCharSequence = originalLineSequence.getCharSequence(diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1);
                var modifiedCharSequence = modifiedLineSequence.getCharSequence(diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1);
                var rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueProcessingPredicate, false);
                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 = (function () {
        function DiffComputer(originalLines, modifiedLines, opts) {
            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);
            if (opts.shouldConsiderTrimWhitespaceInEmptyCase && this.shouldIgnoreTrimWhitespace && this.original.equals(this.modified)) {
                // Diff would be empty with `shouldIgnoreTrimWhitespace`
                this.shouldIgnoreTrimWhitespace = false;
            }
        }
        DiffComputer.prototype.computeDiff = function () {
            if (this.original.getLength() === 1 && this.original.getElementHash(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.getElementHash(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(rawChanges[i], this.original, this.modified, this._continueProcessingPredicate.bind(this), 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(nextChange, this.original, this.modified, this._continueProcessingPredicate.bind(this), 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;
            }
            result.push(new LineChange(originalLineNumber, originalLineNumber, modifiedLineNumber, modifiedLineNumber, [
                new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn)
            ]));
        };
        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;
                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;
});

define(__m[149/*vs/editor/common/editorAction*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/]), function (require, exports, winjs_base_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var InternalEditorAction = (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 winjs_base_1.TPromise.as(void 0);
            }
            var r = this._run();
            return r ? r : winjs_base_1.TPromise.as(void 0);
        };
        return InternalEditorAction;
    }());
    exports.InternalEditorAction = InternalEditorAction;
});

define(__m[20/*vs/editor/common/editorCommon*/], __M([1/*require*/,0/*exports*/]), 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 });
    /**
     * 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 = {}));
    var TextModelResolvedOptions = (function () {
        /**
         * @internal
         */
        function TextModelResolvedOptions(src) {
            this.tabSize = 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.insertSpaces === other.insertSpaces
                && this.defaultEOL === other.defaultEOL
                && this.trimAutoWhitespace === other.trimAutoWhitespace);
        };
        /**
         * @internal
         */
        TextModelResolvedOptions.prototype.createChangeEvent = function (newOpts) {
            return {
                tabSize: this.tabSize !== newOpts.tabSize,
                insertSpaces: this.insertSpaces !== newOpts.insertSpaces,
                trimAutoWhitespace: this.trimAutoWhitespace !== newOpts.trimAutoWhitespace,
            };
        };
        return TextModelResolvedOptions;
    }());
    exports.TextModelResolvedOptions = TextModelResolvedOptions;
    var FindMatch = (function () {
        /**
         * @internal
         */
        function FindMatch(range, matches) {
            this.range = range;
            this.matches = matches;
        }
        return FindMatch;
    }());
    exports.FindMatch = FindMatch;
    /**
     * 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 = {}));
    /**
     * @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'
    };
    /**
     *@internal
     */
    function isCommonCodeEditor(thing) {
        if (thing && typeof thing.getEditorType === 'function') {
            return thing.getEditorType() === exports.EditorType.ICodeEditor;
        }
        else {
            return false;
        }
    }
    exports.isCommonCodeEditor = isCommonCodeEditor;
    /**
     *@internal
     */
    function isCommonDiffEditor(thing) {
        if (thing && typeof thing.getEditorType === 'function') {
            return thing.getEditorType() === exports.EditorType.IDiffEditor;
        }
        else {
            return false;
        }
    }
    exports.isCommonDiffEditor = isCommonDiffEditor;
    /**
     * 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',
    };
});

define(__m[151/*vs/editor/browser/controller/textAreaState*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,9/*vs/base/common/strings*/]), function (require, exports, range_1, editorCommon_1, strings) {
    /*---------------------------------------------------------------------------------------------
     *  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 TextAreaState = (function () {
        function TextAreaState(value, selectionStart, selectionEnd) {
            this.value = value;
            this.selectionStart = selectionStart;
            this.selectionEnd = selectionEnd;
        }
        TextAreaState.prototype.equals = function (other) {
            if (other instanceof TextAreaState) {
                return (this.value === other.value
                    && this.selectionStart === other.selectionStart
                    && this.selectionEnd === other.selectionEnd);
            }
            return false;
        };
        TextAreaState.prototype.toString = function () {
            return '[ <' + this.value + '>, selectionStart: ' + this.selectionStart + ', selectionEnd: ' + this.selectionEnd + ']';
        };
        TextAreaState.prototype.readFromTextArea = function (textArea) {
            return new TextAreaState(textArea.getValue(), textArea.getSelectionStart(), textArea.getSelectionEnd());
        };
        TextAreaState.prototype.collapseSelection = function () {
            return new TextAreaState(this.value, this.value.length, this.value.length);
        };
        TextAreaState.prototype.writeToTextArea = function (reason, textArea, select) {
            // console.log(Date.now() + ': applyToTextArea ' + reason + ': ' + this.toString());
            textArea.setValue(reason, this.value);
            if (select) {
                textArea.setSelectionRange(reason, this.selectionStart, this.selectionEnd);
            }
        };
        TextAreaState.selectedText = function (text) {
            return new TextAreaState(text, 0, text.length);
        };
        TextAreaState.deduceInput = function (previousState, currentState, couldBeEmojiInput) {
            if (!previousState) {
                // This is the EMPTY state
                return {
                    text: '',
                    replaceCharCnt: 0
                };
            }
            // console.log('------------------------deduceInput');
            // console.log('PREVIOUS STATE: ' + previousState.toString());
            // console.log('CURRENT STATE: ' + currentState.toString());
            var previousValue = previousState.value;
            var previousSelectionStart = previousState.selectionStart;
            var previousSelectionEnd = previousState.selectionEnd;
            var currentValue = currentState.value;
            var currentSelectionStart = currentState.selectionStart;
            var currentSelectionEnd = currentState.selectionEnd;
            // Strip the previous suffix from the value (without interfering with the current selection)
            var previousSuffix = previousValue.substring(previousSelectionEnd);
            var currentSuffix = currentValue.substring(currentSelectionEnd);
            var suffixLength = strings.commonSuffixLength(previousSuffix, currentSuffix);
            currentValue = currentValue.substring(0, currentValue.length - suffixLength);
            previousValue = previousValue.substring(0, previousValue.length - suffixLength);
            var previousPrefix = previousValue.substring(0, previousSelectionStart);
            var currentPrefix = currentValue.substring(0, currentSelectionStart);
            var prefixLength = strings.commonPrefixLength(previousPrefix, currentPrefix);
            currentValue = currentValue.substring(prefixLength);
            previousValue = previousValue.substring(prefixLength);
            currentSelectionStart -= prefixLength;
            previousSelectionStart -= prefixLength;
            currentSelectionEnd -= prefixLength;
            previousSelectionEnd -= prefixLength;
            // console.log('AFTER DIFFING PREVIOUS STATE: <' + previousValue + '>, selectionStart: ' + previousSelectionStart + ', selectionEnd: ' + previousSelectionEnd);
            // console.log('AFTER DIFFING CURRENT STATE: <' + currentValue + '>, selectionStart: ' + currentSelectionStart + ', selectionEnd: ' + currentSelectionEnd);
            if (couldBeEmojiInput && currentSelectionStart === currentSelectionEnd && previousValue.length > 0) {
                // on OSX, emojis from the emoji picker are inserted at random locations
                // the only hints we can use is that the selection is immediately after the inserted emoji
                // and that none of the old text has been deleted
                var potentialEmojiInput = null;
                if (currentSelectionStart === currentValue.length) {
                    // emoji potentially inserted "somewhere" after the previous selection => it should appear at the end of `currentValue`
                    if (strings.startsWith(currentValue, previousValue)) {
                        // only if all of the old text is accounted for
                        potentialEmojiInput = currentValue.substring(previousValue.length);
                    }
                }
                else {
                    // emoji potentially inserted "somewhere" before the previous selection => it should appear at the start of `currentValue`
                    if (strings.endsWith(currentValue, previousValue)) {
                        // only if all of the old text is accounted for
                        potentialEmojiInput = currentValue.substring(0, currentValue.length - previousValue.length);
                    }
                }
                if (potentialEmojiInput !== null && potentialEmojiInput.length > 0) {
                    // now we check that this is indeed an emoji
                    // emojis can grow quite long, so a length check is of no help
                    // e.g. 1F3F4 E0067 E0062 E0065 E006E E0067 E007F  ; fully-qualified     # 🏴󠁧󠁢󠁥󠁮󠁧󠁿 England
                    // Oftentimes, emojis use Variation Selector-16 (U+FE0F), so that is a good hint
                    // http://emojipedia.org/variation-selector-16/
                    // > An invisible codepoint which specifies that the preceding character
                    // > should be displayed with emoji presentation. Only required if the
                    // > preceding character defaults to text presentation.
                    if (/\uFE0F/.test(potentialEmojiInput) || strings.containsEmoji(potentialEmojiInput)) {
                        return {
                            text: potentialEmojiInput,
                            replaceCharCnt: 0
                        };
                    }
                }
            }
            if (currentSelectionStart === currentSelectionEnd) {
                // composition accept case (noticed in FF + Japanese)
                // [blahblah] => blahblah|
                if (previousValue === currentValue
                    && previousSelectionStart === 0
                    && previousSelectionEnd === previousValue.length
                    && currentSelectionStart === currentValue.length
                    && currentValue.indexOf('\n') === -1) {
                    if (strings.containsFullWidthCharacter(currentValue)) {
                        return {
                            text: '',
                            replaceCharCnt: 0
                        };
                    }
                }
                // no current selection
                var replacePreviousCharacters_1 = (previousPrefix.length - prefixLength);
                // console.log('REMOVE PREVIOUS: ' + (previousPrefix.length - prefixLength) + ' chars');
                return {
                    text: currentValue,
                    replaceCharCnt: replacePreviousCharacters_1
                };
            }
            // there is a current selection => composition case
            var replacePreviousCharacters = previousSelectionEnd - previousSelectionStart;
            return {
                text: currentValue,
                replaceCharCnt: replacePreviousCharacters
            };
        };
        TextAreaState.EMPTY = new TextAreaState('', 0, 0);
        return TextAreaState;
    }());
    exports.TextAreaState = TextAreaState;
    var PagedScreenReaderStrategy = (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) {
            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, editorCommon_1.EndOfLinePreference.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, editorCommon_1.EndOfLinePreference.LF);
            var text = null;
            if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) {
                // take full selection
                text = model.getValueInRange(selection, editorCommon_1.EndOfLinePreference.LF);
            }
            else {
                var selectionRange1 = selectionStartPageRange.intersectRanges(selection);
                var selectionRange2 = selectionEndPageRange.intersectRanges(selection);
                text = (model.getValueInRange(selectionRange1, editorCommon_1.EndOfLinePreference.LF)
                    + String.fromCharCode(8230)
                    + model.getValueInRange(selectionRange2, editorCommon_1.EndOfLinePreference.LF));
            }
            // Chromium handles very poorly text even of a few thousand chars
            // Cut text to avoid stalling the entire UI
            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);
        };
        PagedScreenReaderStrategy._LINES_PER_PAGE = 10;
        return PagedScreenReaderStrategy;
    }());
    exports.PagedScreenReaderStrategy = PagedScreenReaderStrategy;
});











define(__m[154/*vs/editor/browser/controller/textAreaInput*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/async*/,9/*vs/base/common/strings*/,11/*vs/base/common/event*/,3/*vs/base/common/lifecycle*/,151/*vs/editor/browser/controller/textAreaState*/,28/*vs/base/browser/browser*/,15/*vs/base/common/platform*/,4/*vs/base/browser/dom*/]), function (require, exports, async_1, strings, event_1, lifecycle_1, textAreaState_1, browser, platform, dom) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CopyOptions = {
        forceCopyWithSyntaxHighlighting: false
    };
    var ReadFromTextArea;
    (function (ReadFromTextArea) {
        ReadFromTextArea[ReadFromTextArea["Type"] = 0] = "Type";
        ReadFromTextArea[ReadFromTextArea["Paste"] = 1] = "Paste";
    })(ReadFromTextArea || (ReadFromTextArea = {}));
    /**
     * 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 = (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._host = host;
            _this._textArea = _this._register(new TextAreaWrapper(textArea));
            _this._asyncTriggerCut = _this._register(new async_1.RunOnceScheduler(function () { return _this._onCut.fire(); }, 0));
            _this._textAreaState = textAreaState_1.TextAreaState.EMPTY;
            _this.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.equals(109 /* KEY_IN_COMPOSITION */)) {
                    // Stop propagation for keyDown events if the IME is processing key input
                    e.stopPropagation();
                }
                if (e.equals(9 /* Escape */)) {
                    // Prevent default always for `Esc`, otherwise it will generate a keypress
                    // See https://msdn.microsoft.com/en-us/library/ie/ms536939(v=vs.85).aspx
                    e.preventDefault();
                }
                _this._onKeyDown.fire(e);
            }));
            _this._register(dom.addStandardDisposableListener(textArea.domNode, 'keyup', function (e) {
                _this._onKeyUp.fire(e);
            }));
            _this._register(dom.addDisposableListener(textArea.domNode, 'compositionstart', function (e) {
                if (_this._isDoingComposition) {
                    return;
                }
                _this._isDoingComposition = true;
                // In IE we cannot set .value when handling 'compositionstart' because the entire composition will get canceled.
                if (!browser.isEdgeOrIE) {
                    _this._setAndWriteTextAreaState('compositionstart', textAreaState_1.TextAreaState.EMPTY);
                }
                _this._onCompositionStart.fire();
            }));
            /**
             * Deduce the typed input from a text area's value and the last observed state.
             */
            var deduceInputFromTextAreaValue = function (couldBeEmojiInput) {
                var oldState = _this._textAreaState;
                var newState = _this._textAreaState.readFromTextArea(_this._textArea);
                return [newState, textAreaState_1.TextAreaState.deduceInput(oldState, newState, couldBeEmojiInput)];
            };
            /**
             * Deduce the composition input from a string.
             */
            var deduceComposition = function (text) {
                var oldState = _this._textAreaState;
                var newState = textAreaState_1.TextAreaState.selectedText(text);
                var typeInput = {
                    text: newState.value,
                    replaceCharCnt: oldState.selectionEnd - oldState.selectionStart
                };
                return [newState, typeInput];
            };
            _this._register(dom.addDisposableListener(textArea.domNode, 'compositionupdate', function (e) {
                if (browser.isChromev56) {
                    // See https://github.com/Microsoft/monaco-editor/issues/320
                    // where compositionupdate .data is broken in Chrome v55 and v56
                    // See https://bugs.chromium.org/p/chromium/issues/detail?id=677050#c9
                    // The textArea doesn't get the composition update yet, the value of textarea is still obsolete
                    // so we can't correct e at this moment.
                    return;
                }
                if (browser.isEdgeOrIE && e.locale === 'ja') {
                    // 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.
                    var _a = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ false), newState_1 = _a[0], typeInput_1 = _a[1];
                    _this._textAreaState = newState_1;
                    _this._onType.fire(typeInput_1);
                    _this._onCompositionUpdate.fire(e);
                    return;
                }
                var _b = deduceComposition(e.data), newState = _b[0], typeInput = _b[1];
                _this._textAreaState = newState;
                _this._onType.fire(typeInput);
                _this._onCompositionUpdate.fire(e);
            }));
            _this._register(dom.addDisposableListener(textArea.domNode, 'compositionend', function (e) {
                if (browser.isEdgeOrIE && e.locale === 'ja') {
                    // https://github.com/Microsoft/monaco-editor/issues/339
                    var _a = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ false), newState = _a[0], typeInput = _a[1];
                    _this._textAreaState = newState;
                    _this._onType.fire(typeInput);
                }
                else {
                    var _b = deduceComposition(e.data), newState = _b[0], typeInput = _b[1];
                    _this._textAreaState = newState;
                    _this._onType.fire(typeInput);
                }
                // Due to isEdgeOrIE (where the textarea was not cleared initially) and isChrome (the textarea is not updated correctly when composition ends)
                // we cannot assume the text at the end consists only of the composited text
                if (browser.isEdgeOrIE || browser.isChrome) {
                    _this._textAreaState = _this._textAreaState.readFromTextArea(_this._textArea);
                }
                if (!_this._isDoingComposition) {
                    return;
                }
                _this._isDoingComposition = false;
                _this._onCompositionEnd.fire();
            }));
            _this._register(dom.addDisposableListener(textArea.domNode, 'input', function () {
                if (_this._isDoingComposition) {
                    // See https://github.com/Microsoft/monaco-editor/issues/320
                    if (browser.isChromev56) {
                        var _a = deduceComposition(_this._textArea.getValue()), newState_2 = _a[0], typeInput_2 = _a[1];
                        _this._textAreaState = newState_2;
                        _this._onType.fire(typeInput_2);
                        var e = {
                            data: typeInput_2.text
                        };
                        _this._onCompositionUpdate.fire(e);
                    }
                    return;
                }
                var _b = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ platform.isMacintosh), newState = _b[0], typeInput = _b[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;
                // console.log('==> DEDUCED INPUT: ' + JSON.stringify(typeInput));
                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._ensureClipboardGetsEditorSelection(e);
                _this._asyncTriggerCut.schedule();
            }));
            _this._register(dom.addDisposableListener(textArea.domNode, 'copy', function (e) {
                _this._ensureClipboardGetsEditorSelection(e);
            }));
            _this._register(dom.addDisposableListener(textArea.domNode, 'paste', function (e) {
                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 () { return _this._setHasFocus(true); }));
            _this._register(dom.addDisposableListener(textArea.domNode, 'blur', function () { return _this._setHasFocus(false); }));
            return _this;
        }
        TextAreaInput.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
        };
        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._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.isEdgeOrIE && (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 = (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 = (function (_super) {
        __extends(TextAreaWrapper, _super);
        function TextAreaWrapper(_textArea) {
            var _this = _super.call(this) || this;
            _this._actual = _textArea;
            return _this;
        }
        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);
            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
                return;
            }
            // console.log('reason: ' + reason + ', setSelectionRange: ' + selectionStart + ' -> ' + selectionEnd);
            if (currentIsFocused) {
                // No need to focus, only need to change the selection range
                textArea.setSelectionRange(selectionStart, selectionEnd);
                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);
                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));
});

define(__m[475/*vs/editor/common/model/editStack*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/]), function (require, exports, errors_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var EditStack = (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.pushEditOperation = function (beforeCursorState, editOperations, cursorStateComputer) {
            // No support for parallel universes :(
            this.future = [];
            if (!this.currentOpenStackElement) {
                this.currentOpenStackElement = {
                    beforeVersionId: this.model.getAlternativeVersionId(),
                    beforeCursorState: beforeCursorState,
                    editOperations: [],
                    afterCursorState: null,
                    afterVersionId: -1
                };
            }
            var inverseEditOperation = {
                operations: this.model.applyEdits(editOperations)
            };
            this.currentOpenStackElement.editOperations.push(inverseEditOperation);
            try {
                this.currentOpenStackElement.afterCursorState = cursorStateComputer ? cursorStateComputer(inverseEditOperation.operations) : null;
            }
            catch (e) {
                errors_1.onUnexpectedError(e);
                this.currentOpenStackElement.afterCursorState = null;
            }
            this.currentOpenStackElement.afterVersionId = this.model.getVersionId();
            return this.currentOpenStackElement.afterCursorState;
        };
        EditStack.prototype.undo = function () {
            this.pushStackElement();
            if (this.past.length > 0) {
                var pastStackElement = this.past.pop();
                try {
                    // Apply all operations in reverse order
                    for (var i = pastStackElement.editOperations.length - 1; i >= 0; i--) {
                        pastStackElement.editOperations[i] = {
                            operations: this.model.applyEdits(pastStackElement.editOperations[i].operations)
                        };
                    }
                }
                catch (e) {
                    this.clear();
                    return null;
                }
                this.future.push(pastStackElement);
                return {
                    selections: pastStackElement.beforeCursorState,
                    recordedVersionId: pastStackElement.beforeVersionId
                };
            }
            return null;
        };
        EditStack.prototype.redo = function () {
            if (this.future.length > 0) {
                if (this.currentOpenStackElement) {
                    throw new Error('How is this possible?');
                }
                var futureStackElement = this.future.pop();
                try {
                    // Apply all operations
                    for (var i = 0; i < futureStackElement.editOperations.length; i++) {
                        futureStackElement.editOperations[i] = {
                            operations: this.model.applyEdits(futureStackElement.editOperations[i].operations)
                        };
                    }
                }
                catch (e) {
                    this.clear();
                    return null;
                }
                this.past.push(futureStackElement);
                return {
                    selections: futureStackElement.afterCursorState,
                    recordedVersionId: futureStackElement.afterVersionId
                };
            }
            return null;
        };
        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[481/*vs/editor/common/model/indentRanges*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var IndentRange = (function () {
        function IndentRange(startLineNumber, endLineNumber, indent) {
            this.startLineNumber = startLineNumber;
            this.endLineNumber = endLineNumber;
            this.indent = indent;
        }
        IndentRange.deepCloneArr = function (indentRanges) {
            var result = [];
            for (var i = 0, len = indentRanges.length; i < len; i++) {
                var r = indentRanges[i];
                result[i] = new IndentRange(r.startLineNumber, r.endLineNumber, r.indent);
            }
            return result;
        };
        return IndentRange;
    }());
    exports.IndentRange = IndentRange;
    function computeRanges(model, minimumRangeSize) {
        if (minimumRangeSize === void 0) { minimumRangeSize = 1; }
        var result = [];
        var previousRegions = [];
        previousRegions.push({ indent: -1, line: model.getLineCount() + 1 }); // sentinel, to make sure there's at least one entry
        for (var line = model.getLineCount(); line > 0; line--) {
            var indent = model.getIndentLevel(line);
            if (indent === -1) {
                continue; // only whitespace
            }
            var previous = previousRegions[previousRegions.length - 1];
            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 >= minimumRangeSize) {
                    result.push(new IndentRange(line, endLineNumber, indent));
                }
            }
            if (previous.indent === indent) {
                previous.line = line;
            }
            else {
                // new region with a bigger indent
                previousRegions.push({ indent: indent, line: line });
            }
        }
        return result.reverse();
    }
    exports.computeRanges = computeRanges;
});

define(__m[482/*vs/editor/common/model/indentationGuesser*/], __M([1/*require*/,0/*exports*/]), 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 });
    /**
     * Compute the diff in spaces between two line's indentation.
     */
    function spacesDiff(a, aLength, b, bLength) {
        // 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 0;
        }
        if (bSpacesCnt > 0 && bTabsCount > 0) {
            return 0;
        }
        var tabsDiff = Math.abs(aTabsCount - bTabsCount);
        var spacesDiff = Math.abs(aSpacesCnt - bSpacesCnt);
        if (tabsDiff === 0) {
            return spacesDiff;
        }
        if (spacesDiff % tabsDiff === 0) {
            return spacesDiff / tabsDiff;
        }
        return 0;
    }
    function guessIndentation(lines, defaultTabSize, defaultInsertSpaces) {
        // Look at most at the first 10k lines
        var linesLen = Math.min(lines.length, 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]; // limit guesses for `tabSize` to 2, 4, 6 or 8.
        var MAX_ALLOWED_TAB_SIZE_GUESS = 8; // max(2,4,6,8) = 8
        var spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0]; // `tabSize` scores
        for (var i = 0; i < linesLen; i++) {
            var currentLineText = lines[i];
            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 = currentLineText.length; j < lenJ; j++) {
                var charCode = currentLineText.charCodeAt(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++;
            }
            var currentSpacesDiff = spacesDiff(previousLineText, previousLineIndentation, currentLineText, currentLineIndentation);
            if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) {
                spacesDiffCount[currentSpacesDiff]++;
            }
            previousLineText = currentLineText;
            previousLineIndentation = currentLineIndentation;
        }
        // Take into account the last line as well
        var deltaSpacesCount = spacesDiff(previousLineText, previousLineIndentation, '', 0);
        if (deltaSpacesCount <= MAX_ALLOWED_TAB_SIZE_GUESS) {
            spacesDiffCount[deltaSpacesCount]++;
        }
        var insertSpaces = defaultInsertSpaces;
        if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) {
            insertSpaces = (linesIndentedWithTabsCount < linesIndentedWithSpacesCount);
        }
        var tabSize = defaultTabSize;
        var tabSizeScore = (insertSpaces ? 0 : 0.1 * linesLen);
        // console.log("score threshold: " + tabSizeScore);
        ALLOWED_TAB_SIZE_GUESSES.forEach(function (possibleTabSize) {
            var possibleTabSizeScore = spacesDiffCount[possibleTabSize];
            if (possibleTabSizeScore > tabSizeScore) {
                tabSizeScore = possibleTabSizeScore;
                tabSize = possibleTabSize;
            }
        });
        // 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[55/*vs/editor/common/model/textModelEvents*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * @internal
     */
    exports.TextModelEventType = {
        ModelDispose: 'modelDispose',
        ModelTokensChanged: 'modelTokensChanged',
        ModelLanguageChanged: 'modelLanguageChanged',
        ModelOptionsChanged: 'modelOptionsChanged',
        ModelContentChanged: 'contentChanged',
        ModelRawContentChanged2: 'rawContentChanged2',
        ModelDecorationsChanged: 'decorationsChanged',
    };
    /**
     * @internal
     */
    var RawContentChangedType;
    (function (RawContentChangedType) {
        RawContentChangedType[RawContentChangedType["Flush"] = 1] = "Flush";
        RawContentChangedType[RawContentChangedType["LineChanged"] = 2] = "LineChanged";
        RawContentChangedType[RawContentChangedType["LinesDeleted"] = 3] = "LinesDeleted";
        RawContentChangedType[RawContentChangedType["LinesInserted"] = 4] = "LinesInserted";
        RawContentChangedType[RawContentChangedType["EOLChanged"] = 5] = "EOLChanged";
    })(RawContentChangedType = exports.RawContentChangedType || (exports.RawContentChangedType = {}));
    /**
     * An event describing that a model has been reset to a new value.
     * @internal
     */
    var ModelRawFlush = (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 = (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 = (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 = (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 = (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 = (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;
        };
        return ModelRawContentChangedEvent;
    }());
    exports.ModelRawContentChangedEvent = ModelRawContentChangedEvent;
});

define(__m[158/*vs/editor/common/model/textModelSearch*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,94/*vs/editor/common/controller/wordCharacterClassifier*/]), function (require, exports, strings, position_1, range_1, editorCommon_1, wordCharacterClassifier_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var LIMIT_FIND_COUNT = 999;
    var SearchParams = (function () {
        function SearchParams(searchString, isRegex, matchCase, wordSeparators) {
            this.searchString = searchString;
            this.isRegex = isRegex;
            this.matchCase = matchCase;
            this.wordSeparators = wordSeparators;
        }
        SearchParams._isMultilineRegexSource = function (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 */) {
                        return true;
                    }
                }
            }
            return false;
        };
        SearchParams.prototype.parseSearchRequest = function () {
            if (this.searchString === '') {
                return null;
            }
            // Try to create a RegExp out of the params
            var multiline;
            if (this.isRegex) {
                multiline = SearchParams._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;
    var SearchData = (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 editorCommon_1.FindMatch(range, null);
        }
        var matches = [];
        for (var i = 0, len = rawMatches.length; i < len; i++) {
            matches[i] = rawMatches[i];
        }
        return new editorCommon_1.FindMatch(range, matches);
    }
    var TextModelSearch = (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, matchIndex, match0) {
            var startOffset;
            if (model.getEOL() === '\r\n') {
                var lineFeedCountBeforeMatch = 0;
                for (var i = 0; i < matchIndex; i++) {
                    var chCode = text.charCodeAt(i);
                    if (chCode === 10 /* LineFeed */) {
                        lineFeedCountBeforeMatch++;
                    }
                }
                startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch /* add as many \r as there were \n */;
            }
            else {
                startOffset = deltaOffset + matchIndex;
            }
            var endOffset;
            if (model.getEOL() === '\r\n') {
                var lineFeedCountInMatch = 0;
                for (var i = 0, len = match0.length; i < len; i++) {
                    var chCode = text.charCodeAt(i + matchIndex);
                    if (chCode === 10 /* LineFeed */) {
                        lineFeedCountInMatch++;
                    }
                }
                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, editorCommon_1.EndOfLinePreference.LF);
            var result = [];
            var counter = 0;
            var m;
            searcher.reset(0);
            while ((m = searcher.next(text))) {
                result[counter++] = createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, 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 editorCommon_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)), editorCommon_1.EndOfLinePreference.LF);
            searcher.reset(searchStart.column - 1);
            var m = searcher.next(text);
            if (m) {
                return createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, 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 (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 (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));
    }
    var Searcher = (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;
    }());
});

define(__m[101/*vs/editor/common/model/textSource*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,20/*vs/editor/common/editorCommon*/]), function (require, exports, strings, editorCommon_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var RawTextSource = (function () {
        function RawTextSource() {
        }
        RawTextSource.fromString = function (rawText) {
            // Count the number of lines that end with \r\n
            var carriageReturnCnt = 0;
            var lastCarriageReturnIndex = -1;
            while ((lastCarriageReturnIndex = rawText.indexOf('\r', lastCarriageReturnIndex + 1)) !== -1) {
                carriageReturnCnt++;
            }
            var containsRTL = strings.containsRTL(rawText);
            var isBasicASCII = (containsRTL ? false : strings.isBasicASCII(rawText));
            // Split the text into lines
            var lines = rawText.split(/\r\n|\r|\n/);
            // Remove the BOM (if present)
            var BOM = '';
            if (strings.startsWithUTF8BOM(lines[0])) {
                BOM = strings.UTF8_BOM_CHARACTER;
                lines[0] = lines[0].substr(1);
            }
            return {
                BOM: BOM,
                lines: lines,
                length: rawText.length,
                containsRTL: containsRTL,
                isBasicASCII: isBasicASCII,
                totalCRCount: carriageReturnCnt
            };
        };
        return RawTextSource;
    }());
    exports.RawTextSource = RawTextSource;
    var TextSource = (function () {
        function TextSource() {
        }
        /**
         * if text source is empty or with precisely one line, returns null. No end of line is detected.
         * if text source contains more lines ending with '\r\n', returns '\r\n'.
         * Otherwise returns '\n'. More lines end with '\n'.
         */
        TextSource._getEOL = function (rawTextSource, defaultEOL) {
            var lineFeedCnt = rawTextSource.lines.length - 1;
            if (lineFeedCnt === 0) {
                // This is an empty file or a file with precisely one line
                return (defaultEOL === editorCommon_1.DefaultEndOfLine.LF ? '\n' : '\r\n');
            }
            if (rawTextSource.totalCRCount > lineFeedCnt / 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';
        };
        TextSource.fromRawTextSource = function (rawTextSource, defaultEOL) {
            return {
                length: rawTextSource.length,
                lines: rawTextSource.lines,
                BOM: rawTextSource.BOM,
                EOL: this._getEOL(rawTextSource, defaultEOL),
                containsRTL: rawTextSource.containsRTL,
                isBasicASCII: rawTextSource.isBasicASCII,
            };
        };
        TextSource.fromString = function (text, defaultEOL) {
            return this.fromRawTextSource(RawTextSource.fromString(text), defaultEOL);
        };
        TextSource.create = function (source, defaultEOL) {
            if (typeof source === 'string') {
                return this.fromString(source, defaultEOL);
            }
            return this.fromRawTextSource(source, defaultEOL);
        };
        return TextSource;
    }());
    exports.TextSource = TextSource;
});

define(__m[116/*vs/editor/common/model/tokensBinaryEncoding*/], __M([1/*require*/,0/*exports*/]), 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 TokenMetadata = (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;
});

define(__m[90/*vs/editor/common/core/viewLineToken*/], __M([1/*require*/,0/*exports*/,116/*vs/editor/common/model/tokensBinaryEncoding*/]), function (require, exports, tokensBinaryEncoding_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * A token on a line.
     */
    var ViewLineToken = (function () {
        function ViewLineToken(endIndex, metadata) {
            this.endIndex = endIndex;
            this._metadata = metadata;
        }
        ViewLineToken.prototype.getForeground = function () {
            return tokensBinaryEncoding_1.TokenMetadata.getForeground(this._metadata);
        };
        ViewLineToken.prototype.getType = function () {
            return tokensBinaryEncoding_1.TokenMetadata.getClassNameFromMetadata(this._metadata);
        };
        ViewLineToken.prototype.getInlineStyle = function (colorMap) {
            return tokensBinaryEncoding_1.TokenMetadata.getInlineStyleFromMetadata(this._metadata, colorMap);
        };
        ViewLineToken._equals = function (a, b) {
            return (a.endIndex === b.endIndex
                && a._metadata === b._metadata);
        };
        ViewLineToken.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 (!this._equals(a[i], b[i])) {
                    return false;
                }
            }
            return true;
        };
        return ViewLineToken;
    }());
    exports.ViewLineToken = ViewLineToken;
    var ViewLineTokenFactory = (function () {
        function ViewLineTokenFactory() {
        }
        ViewLineTokenFactory.inflateArr = function (tokens, lineLength) {
            var result = [];
            for (var i = 0, len = (tokens.length >>> 1); i < len; i++) {
                var endOffset = (i + 1 < len ? tokens[((i + 1) << 1)] : lineLength);
                var metadata = tokens[(i << 1) + 1];
                result[i] = new ViewLineToken(endOffset, metadata);
            }
            return result;
        };
        ViewLineTokenFactory.sliceAndInflate = function (tokens, startOffset, endOffset, deltaOffset, lineLength) {
            var tokenIndex = this.findIndexInSegmentsArray(tokens, startOffset);
            var maxEndOffset = (endOffset - startOffset + deltaOffset);
            var result = [], resultLen = 0;
            for (var i = tokenIndex, len = (tokens.length >>> 1); i < len; i++) {
                var tokenStartOffset = tokens[(i << 1)];
                if (tokenStartOffset >= endOffset) {
                    break;
                }
                var tokenEndOffset = (i + 1 < len ? tokens[((i + 1) << 1)] : lineLength);
                var newEndOffset = Math.min(maxEndOffset, tokenEndOffset - startOffset + deltaOffset);
                var metadata = tokens[(i << 1) + 1];
                result[resultLen++] = new ViewLineToken(newEndOffset, metadata);
            }
            return result;
        };
        ViewLineTokenFactory.findIndexInSegmentsArray = function (tokens, desiredIndex) {
            var low = 0;
            var high = (tokens.length >>> 1) - 1;
            while (low < high) {
                var mid = low + Math.ceil((high - low) / 2);
                var value = tokens[(mid << 1)];
                if (value > desiredIndex) {
                    high = mid - 1;
                }
                else {
                    low = mid;
                }
            }
            return low;
        };
        return ViewLineTokenFactory;
    }());
    exports.ViewLineTokenFactory = ViewLineTokenFactory;
});

define(__m[130/*vs/editor/common/core/lineTokens*/], __M([1/*require*/,0/*exports*/,116/*vs/editor/common/model/tokensBinaryEncoding*/,90/*vs/editor/common/core/viewLineToken*/]), function (require, exports, tokensBinaryEncoding_1, viewLineToken_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var LineToken = (function () {
        function LineToken(source, tokenIndex, tokenCount, startOffset, endOffset, metadata) {
            this._source = source;
            this._tokenIndex = tokenIndex;
            this._metadata = metadata;
            this.startOffset = startOffset;
            this.endOffset = endOffset;
            this.hasPrev = (this._tokenIndex > 0);
            this.hasNext = (this._tokenIndex + 1 < tokenCount);
        }
        Object.defineProperty(LineToken.prototype, "languageId", {
            get: function () {
                return tokensBinaryEncoding_1.TokenMetadata.getLanguageId(this._metadata);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(LineToken.prototype, "tokenType", {
            get: function () {
                return tokensBinaryEncoding_1.TokenMetadata.getTokenType(this._metadata);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(LineToken.prototype, "fontStyle", {
            get: function () {
                return tokensBinaryEncoding_1.TokenMetadata.getFontStyle(this._metadata);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(LineToken.prototype, "foregroundId", {
            get: function () {
                return tokensBinaryEncoding_1.TokenMetadata.getForeground(this._metadata);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(LineToken.prototype, "backgroundId", {
            get: function () {
                return tokensBinaryEncoding_1.TokenMetadata.getBackground(this._metadata);
            },
            enumerable: true,
            configurable: true
        });
        LineToken.prototype.prev = function () {
            if (!this.hasPrev) {
                return null;
            }
            return this._source.tokenAt(this._tokenIndex - 1);
        };
        LineToken.prototype.next = function () {
            if (!this.hasNext) {
                return null;
            }
            return this._source.tokenAt(this._tokenIndex + 1);
        };
        return LineToken;
    }());
    exports.LineToken = LineToken;
    var LineTokens = (function () {
        function LineTokens(tokens, text) {
            this._tokens = tokens;
            this._tokensCount = (this._tokens.length >>> 1);
            this._text = text;
            this._textLength = this._text.length;
        }
        LineTokens.prototype.getTokenCount = function () {
            return this._tokensCount;
        };
        LineTokens.prototype.getLineContent = function () {
            return this._text;
        };
        LineTokens.prototype.getLineLength = function () {
            return this._textLength;
        };
        LineTokens.prototype.getTokenStartOffset = function (tokenIndex) {
            return this._tokens[(tokenIndex << 1)];
        };
        LineTokens.prototype.getLanguageId = function (tokenIndex) {
            var metadata = this._tokens[(tokenIndex << 1) + 1];
            return tokensBinaryEncoding_1.TokenMetadata.getLanguageId(metadata);
        };
        LineTokens.prototype.getStandardTokenType = function (tokenIndex) {
            var metadata = this._tokens[(tokenIndex << 1) + 1];
            return tokensBinaryEncoding_1.TokenMetadata.getTokenType(metadata);
        };
        LineTokens.prototype.getTokenEndOffset = function (tokenIndex) {
            if (tokenIndex + 1 < this._tokensCount) {
                return this._tokens[(tokenIndex + 1) << 1];
            }
            return this._textLength;
        };
        /**
         * Find the token containing offset `offset`.
         * ```
         *   For example, with the following tokens [0, 5), [5, 9), [9, infinity)
         *   Searching for 0, 1, 2, 3 or 4 will return 0.
         *   Searching for 5, 6, 7 or 8 will return 1.
         *   Searching for 9, 10, 11, ... will return 2.
         * ```
         * @param offset The search offset
         * @return The index of the token containing the offset.
         */
        LineTokens.prototype.findTokenIndexAtOffset = function (offset) {
            return viewLineToken_1.ViewLineTokenFactory.findIndexInSegmentsArray(this._tokens, offset);
        };
        LineTokens.prototype.findTokenAtOffset = function (offset) {
            var tokenIndex = this.findTokenIndexAtOffset(offset);
            return this.tokenAt(tokenIndex);
        };
        LineTokens.prototype.tokenAt = function (tokenIndex) {
            var startOffset = this._tokens[(tokenIndex << 1)];
            var endOffset;
            if (tokenIndex + 1 < this._tokensCount) {
                endOffset = this._tokens[(tokenIndex + 1) << 1];
            }
            else {
                endOffset = this._textLength;
            }
            var metadata = this._tokens[(tokenIndex << 1) + 1];
            return new LineToken(this, tokenIndex, this._tokensCount, startOffset, endOffset, metadata);
        };
        LineTokens.prototype.firstToken = function () {
            if (this._textLength === 0) {
                return null;
            }
            return this.tokenAt(0);
        };
        LineTokens.prototype.lastToken = function () {
            if (this._textLength === 0) {
                return null;
            }
            return this.tokenAt(this._tokensCount - 1);
        };
        LineTokens.prototype.inflate = function () {
            return viewLineToken_1.ViewLineTokenFactory.inflateArr(this._tokens, this._textLength);
        };
        LineTokens.prototype.sliceAndInflate = function (startOffset, endOffset, deltaOffset) {
            return viewLineToken_1.ViewLineTokenFactory.sliceAndInflate(this._tokens, startOffset, endOffset, deltaOffset, this._textLength);
        };
        return LineTokens;
    }());
    exports.LineTokens = LineTokens;
});











define(__m[118/*vs/editor/common/model/modelLine*/], __M([1/*require*/,0/*exports*/,130/*vs/editor/common/core/lineTokens*/,12/*vs/editor/common/core/position*/]), function (require, exports, lineTokens_1, position_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var LineMarker = (function () {
        function LineMarker(id, internalDecorationId, position, stickToPreviousCharacter) {
            this.id = id;
            this.internalDecorationId = internalDecorationId;
            this.position = position;
            this.stickToPreviousCharacter = stickToPreviousCharacter;
        }
        LineMarker.prototype.toString = function () {
            return '{\'' + this.id + '\';' + this.position.toString() + ',' + this.stickToPreviousCharacter + '}';
        };
        LineMarker.prototype.updateLineNumber = function (markersTracker, lineNumber) {
            if (this.position.lineNumber === lineNumber) {
                return;
            }
            markersTracker.addChangedMarker(this);
            this.position = new position_1.Position(lineNumber, this.position.column);
        };
        LineMarker.prototype.updateColumn = function (markersTracker, column) {
            if (this.position.column === column) {
                return;
            }
            markersTracker.addChangedMarker(this);
            this.position = new position_1.Position(this.position.lineNumber, column);
        };
        LineMarker.prototype.updatePosition = function (markersTracker, position) {
            if (this.position.lineNumber === position.lineNumber && this.position.column === position.column) {
                return;
            }
            markersTracker.addChangedMarker(this);
            this.position = position;
        };
        LineMarker.prototype.setPosition = function (position) {
            this.position = position;
        };
        LineMarker.compareMarkers = function (a, b) {
            if (a.position.column === b.position.column) {
                return (a.stickToPreviousCharacter ? 0 : 1) - (b.stickToPreviousCharacter ? 0 : 1);
            }
            return a.position.column - b.position.column;
        };
        return LineMarker;
    }());
    exports.LineMarker = LineMarker;
    var MarkersTracker = (function () {
        function MarkersTracker() {
            this._changedDecorations = [];
            this._changedDecorationsLen = 0;
        }
        MarkersTracker.prototype.addChangedMarker = function (marker) {
            var internalDecorationId = marker.internalDecorationId;
            if (internalDecorationId !== 0) {
                this._changedDecorations[this._changedDecorationsLen++] = internalDecorationId;
            }
        };
        MarkersTracker.prototype.getDecorationIds = function () {
            return this._changedDecorations;
        };
        return MarkersTracker;
    }());
    exports.MarkersTracker = MarkersTracker;
    var NO_OP_TOKENS_ADJUSTER = {
        adjust: function () { },
        finish: function () { }
    };
    var NO_OP_MARKERS_ADJUSTER = {
        adjustDelta: function () { },
        adjustSet: function () { },
        finish: function () { }
    };
    var MarkerMoveSemantics;
    (function (MarkerMoveSemantics) {
        MarkerMoveSemantics[MarkerMoveSemantics["MarkerDefined"] = 0] = "MarkerDefined";
        MarkerMoveSemantics[MarkerMoveSemantics["ForceMove"] = 1] = "ForceMove";
        MarkerMoveSemantics[MarkerMoveSemantics["ForceStay"] = 2] = "ForceStay";
    })(MarkerMoveSemantics || (MarkerMoveSemantics = {}));
    /**
     * Returns:
     *  - 0 => the line consists of whitespace
     *  - otherwise => the indent level is returned value - 1
     */
    function computePlusOneIndentLevel(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 0; // line only consists of whitespace
        }
        return indent + 1;
    }
    var AbstractModelLine = (function () {
        function AbstractModelLine(initializeMarkers) {
            if (initializeMarkers) {
                this._markers = null;
            }
        }
        ///
        // private _printMarkers(): string {
        // 	if (!this._markers) {
        // 		return '[]';
        // 	}
        // 	if (this._markers.length === 0) {
        // 		return '[]';
        // 	}
        // 	var markers = this._markers;
        // 	var printMarker = (m:LineMarker) => {
        // 		if (m.stickToPreviousCharacter) {
        // 			return '|' + m.position.column;
        // 		}
        // 		return m.position.column + '|';
        // 	};
        // 	return '[' + markers.map(printMarker).join(', ') + ']';
        // }
        AbstractModelLine.prototype._createMarkersAdjuster = function (markersTracker) {
            if (!this._markers) {
                return NO_OP_MARKERS_ADJUSTER;
            }
            if (this._markers.length === 0) {
                return NO_OP_MARKERS_ADJUSTER;
            }
            this._markers.sort(LineMarker.compareMarkers);
            var markers = this._markers;
            var markersLength = markers.length;
            var markersIndex = 0;
            var marker = markers[markersIndex];
            // console.log('------------- INITIAL MARKERS: ' + this._printMarkers());
            var adjustMarkerBeforeColumn = function (toColumn, moveSemantics) {
                if (marker.position.column < toColumn) {
                    return true;
                }
                if (marker.position.column > toColumn) {
                    return false;
                }
                if (moveSemantics === 1 /* ForceMove */) {
                    return false;
                }
                if (moveSemantics === 2 /* ForceStay */) {
                    return true;
                }
                return marker.stickToPreviousCharacter;
            };
            var adjustDelta = function (toColumn, delta, minimumAllowedColumn, moveSemantics) {
                // console.log('------------------------------');
                // console.log('adjustDelta called: toColumn: ' + toColumn + ', delta: ' + delta + ', minimumAllowedColumn: ' + minimumAllowedColumn + ', moveSemantics: ' + MarkerMoveSemantics[moveSemantics]);
                // console.log('BEFORE::: markersIndex: ' + markersIndex + ' : ' + this._printMarkers());
                while (markersIndex < markersLength && adjustMarkerBeforeColumn(toColumn, moveSemantics)) {
                    if (delta !== 0) {
                        var newColumn = Math.max(minimumAllowedColumn, marker.position.column + delta);
                        marker.updateColumn(markersTracker, newColumn);
                    }
                    markersIndex++;
                    if (markersIndex < markersLength) {
                        marker = markers[markersIndex];
                    }
                }
                // console.log('AFTER::: markersIndex: ' + markersIndex + ' : ' + this._printMarkers());
            };
            var adjustSet = function (toColumn, newColumn, moveSemantics) {
                // console.log('------------------------------');
                // console.log('adjustSet called: toColumn: ' + toColumn + ', newColumn: ' + newColumn + ', moveSemantics: ' + MarkerMoveSemantics[moveSemantics]);
                // console.log('BEFORE::: markersIndex: ' + markersIndex + ' : ' + this._printMarkers());
                while (markersIndex < markersLength && adjustMarkerBeforeColumn(toColumn, moveSemantics)) {
                    marker.updateColumn(markersTracker, newColumn);
                    markersIndex++;
                    if (markersIndex < markersLength) {
                        marker = markers[markersIndex];
                    }
                }
                // console.log('AFTER::: markersIndex: ' + markersIndex + ' : ' + this._printMarkers());
            };
            var finish = function (delta, lineTextLength) {
                adjustDelta(1073741824 /* MAX_SAFE_SMALL_INTEGER */, delta, 1, 0 /* MarkerDefined */);
                // console.log('------------- FINAL MARKERS: ' + this._printMarkers());
            };
            return {
                adjustDelta: adjustDelta,
                adjustSet: adjustSet,
                finish: finish
            };
        };
        AbstractModelLine.prototype.applyEdits = function (markersTracker, edits, tabSize) {
            var deltaColumn = 0;
            var resultText = this.text;
            var tokensAdjuster = this._createTokensAdjuster();
            var markersAdjuster = this._createMarkersAdjuster(markersTracker);
            for (var i = 0, len = edits.length; i < len; i++) {
                var edit = edits[i];
                // console.log();
                // console.log('=============================');
                // console.log('EDIT #' + i + ' [ ' + edit.startColumn + ' -> ' + edit.endColumn + ' ] : <<<' + edit.text + '>>>, forceMoveMarkers: ' + edit.forceMoveMarkers);
                // console.log('deltaColumn: ' + deltaColumn);
                var startColumn = deltaColumn + edit.startColumn;
                var endColumn = deltaColumn + edit.endColumn;
                var deletingCnt = endColumn - startColumn;
                var insertingCnt = edit.text.length;
                // Adjust tokens & markers before this edit
                // console.log('Adjust tokens & markers before this edit');
                tokensAdjuster.adjust(edit.startColumn - 1, deltaColumn, 1);
                markersAdjuster.adjustDelta(edit.startColumn, deltaColumn, 1, edit.forceMoveMarkers ? 1 /* ForceMove */ : (deletingCnt > 0 ? 2 /* ForceStay */ : 0 /* MarkerDefined */));
                // Adjust tokens & markers for the common part of this edit
                var commonLength = Math.min(deletingCnt, insertingCnt);
                if (commonLength > 0) {
                    // console.log('Adjust tokens & markers for the common part of this edit');
                    tokensAdjuster.adjust(edit.startColumn - 1 + commonLength, deltaColumn, startColumn);
                    if (!edit.forceMoveMarkers) {
                        markersAdjuster.adjustDelta(edit.startColumn + commonLength, deltaColumn, startColumn, edit.forceMoveMarkers ? 1 /* ForceMove */ : (deletingCnt > insertingCnt ? 2 /* ForceStay */ : 0 /* MarkerDefined */));
                    }
                }
                // Perform the edit & update `deltaColumn`
                resultText = resultText.substring(0, startColumn - 1) + edit.text + resultText.substring(endColumn - 1);
                deltaColumn += insertingCnt - deletingCnt;
                // Adjust tokens & markers inside this edit
                // console.log('Adjust tokens & markers inside this edit');
                tokensAdjuster.adjust(edit.endColumn, deltaColumn, startColumn);
                markersAdjuster.adjustSet(edit.endColumn, startColumn + insertingCnt, edit.forceMoveMarkers ? 1 /* ForceMove */ : 0 /* MarkerDefined */);
            }
            // Wrap up tokens & markers; adjust remaining if needed
            tokensAdjuster.finish(deltaColumn, resultText.length);
            markersAdjuster.finish(deltaColumn, resultText.length);
            // Save the resulting text
            this._setText(resultText, tabSize);
            return deltaColumn;
        };
        AbstractModelLine.prototype.split = function (markersTracker, splitColumn, forceMoveMarkers, tabSize) {
            // console.log('--> split @ ' + splitColumn + '::: ' + this._printMarkers());
            var myText = this.text.substring(0, splitColumn - 1);
            var otherText = this.text.substring(splitColumn - 1);
            var otherMarkers = null;
            if (this._markers) {
                this._markers.sort(LineMarker.compareMarkers);
                for (var i = 0, len = this._markers.length; i < len; i++) {
                    var marker = this._markers[i];
                    if (marker.position.column > splitColumn
                        || (marker.position.column === splitColumn
                            && (forceMoveMarkers
                                || !marker.stickToPreviousCharacter))) {
                        var myMarkers = this._markers.slice(0, i);
                        otherMarkers = this._markers.slice(i);
                        this._markers = myMarkers;
                        break;
                    }
                }
                if (otherMarkers) {
                    for (var i = 0, len = otherMarkers.length; i < len; i++) {
                        var marker = otherMarkers[i];
                        marker.updateColumn(markersTracker, marker.position.column - (splitColumn - 1));
                    }
                }
            }
            this._setText(myText, tabSize);
            var otherLine = this._createModelLine(otherText, tabSize);
            if (otherMarkers) {
                otherLine.addMarkers(otherMarkers);
            }
            return otherLine;
        };
        AbstractModelLine.prototype.append = function (markersTracker, myLineNumber, other, tabSize) {
            // console.log('--> append: THIS :: ' + this._printMarkers());
            // console.log('--> append: OTHER :: ' + this._printMarkers());
            var thisTextLength = this.text.length;
            this._setText(this.text + other.text, tabSize);
            if (other instanceof AbstractModelLine) {
                if (other._markers) {
                    // Other has markers
                    var otherMarkers = other._markers;
                    // Adjust other markers
                    for (var i = 0, len = otherMarkers.length; i < len; i++) {
                        var marker = otherMarkers[i];
                        marker.updatePosition(markersTracker, new position_1.Position(myLineNumber, marker.position.column + thisTextLength));
                    }
                    this.addMarkers(otherMarkers);
                }
            }
        };
        AbstractModelLine.prototype.addMarker = function (marker) {
            if (!this._markers) {
                this._markers = [marker];
            }
            else {
                this._markers.push(marker);
            }
        };
        AbstractModelLine.prototype.addMarkers = function (markers) {
            if (markers.length === 0) {
                return;
            }
            if (!this._markers) {
                this._markers = markers.slice(0);
            }
            else {
                this._markers = this._markers.concat(markers);
            }
        };
        AbstractModelLine.prototype.removeMarker = function (marker) {
            if (!this._markers) {
                return;
            }
            var index = this._indexOfMarkerId(marker.id);
            if (index < 0) {
                return;
            }
            if (this._markers.length === 1) {
                // was last marker on line
                this._markers = null;
            }
            else {
                this._markers.splice(index, 1);
            }
        };
        AbstractModelLine.prototype.removeMarkers = function (deleteMarkers) {
            if (!this._markers) {
                return;
            }
            for (var i = 0, len = this._markers.length; i < len; i++) {
                var marker = this._markers[i];
                if (deleteMarkers[marker.id]) {
                    this._markers.splice(i, 1);
                    len--;
                    i--;
                }
            }
            if (this._markers.length === 0) {
                this._markers = null;
            }
        };
        AbstractModelLine.prototype.getMarkers = function () {
            if (!this._markers) {
                return null;
            }
            return this._markers;
        };
        AbstractModelLine.prototype.updateLineNumber = function (markersTracker, newLineNumber) {
            if (this._markers) {
                var markers = this._markers;
                for (var i = 0, len = markers.length; i < len; i++) {
                    var marker = markers[i];
                    marker.updateLineNumber(markersTracker, newLineNumber);
                }
            }
        };
        AbstractModelLine.prototype._indexOfMarkerId = function (markerId) {
            var markers = this._markers;
            for (var i = 0, len = markers.length; i < len; i++) {
                if (markers[i].id === markerId) {
                    return i;
                }
            }
            return undefined;
        };
        return AbstractModelLine;
    }());
    exports.AbstractModelLine = AbstractModelLine;
    var ModelLine = (function (_super) {
        __extends(ModelLine, _super);
        function ModelLine(text, tabSize) {
            var _this = _super.call(this, true) || this;
            _this._metadata = 0;
            _this._setText(text, tabSize);
            _this._state = null;
            _this._lineTokens = null;
            return _this;
        }
        Object.defineProperty(ModelLine.prototype, "text", {
            get: function () { return this._text; },
            enumerable: true,
            configurable: true
        });
        ModelLine.prototype.isInvalid = function () {
            return (this._metadata & 0x00000001) ? true : false;
        };
        ModelLine.prototype.setIsInvalid = function (isInvalid) {
            this._metadata = (this._metadata & 0xfffffffe) | (isInvalid ? 1 : 0);
        };
        /**
         * Returns:
         *  - -1 => the line consists of whitespace
         *  - otherwise => the indent level is returned value
         */
        ModelLine.prototype.getIndentLevel = function () {
            return ((this._metadata & 0xfffffffe) >> 1) - 1;
        };
        ModelLine.prototype._setPlusOneIndentLevel = function (value) {
            this._metadata = (this._metadata & 0x00000001) | ((value & 0xefffffff) << 1);
        };
        ModelLine.prototype.updateTabSize = function (tabSize) {
            if (tabSize === 0) {
                // don't care mark
                this._metadata = this._metadata & 0x00000001;
            }
            else {
                this._setPlusOneIndentLevel(computePlusOneIndentLevel(this._text, tabSize));
            }
        };
        ModelLine.prototype._createModelLine = function (text, tabSize) {
            return new ModelLine(text, tabSize);
        };
        ModelLine.prototype.split = function (markersTracker, splitColumn, forceMoveMarkers, tabSize) {
            var result = _super.prototype.split.call(this, markersTracker, splitColumn, forceMoveMarkers, tabSize);
            // Mark overflowing tokens for deletion & delete marked tokens
            this._deleteMarkedTokens(this._markOverflowingTokensForDeletion(0, this.text.length));
            return result;
        };
        ModelLine.prototype.append = function (markersTracker, myLineNumber, other, tabSize) {
            var thisTextLength = this.text.length;
            _super.prototype.append.call(this, markersTracker, myLineNumber, other, tabSize);
            if (other instanceof ModelLine) {
                var otherRawTokens = other._lineTokens;
                if (otherRawTokens) {
                    // Other has real tokens
                    var otherTokens = new Uint32Array(otherRawTokens);
                    // Adjust other tokens
                    if (thisTextLength > 0) {
                        for (var i = 0, len = (otherTokens.length >>> 1); i < len; i++) {
                            otherTokens[(i << 1)] = otherTokens[(i << 1)] + thisTextLength;
                        }
                    }
                    // Append other tokens
                    var myRawTokens = this._lineTokens;
                    if (myRawTokens) {
                        // I have real tokens
                        var myTokens = new Uint32Array(myRawTokens);
                        var result = new Uint32Array(myTokens.length + otherTokens.length);
                        result.set(myTokens, 0);
                        result.set(otherTokens, myTokens.length);
                        this._lineTokens = result.buffer;
                    }
                    else {
                        // I don't have real tokens
                        this._lineTokens = otherTokens.buffer;
                    }
                }
            }
        };
        // --- BEGIN STATE
        ModelLine.prototype.resetTokenizationState = function () {
            this._state = null;
            this._lineTokens = null;
        };
        ModelLine.prototype.setState = function (state) {
            this._state = state;
        };
        ModelLine.prototype.getState = function () {
            return this._state || null;
        };
        // --- END STATE
        // --- BEGIN TOKENS
        ModelLine.prototype.setTokens = function (topLevelLanguageId, tokens) {
            if (!tokens || tokens.length === 0) {
                this._lineTokens = null;
                return;
            }
            if (tokens.length === 2) {
                // there is one token
                if (tokens[0] === 0 && tokens[1] === getDefaultMetadata(topLevelLanguageId)) {
                    this._lineTokens = null;
                    return;
                }
            }
            this._lineTokens = tokens.buffer;
        };
        ModelLine.prototype.getTokens = function (topLevelLanguageId) {
            var rawLineTokens = this._lineTokens;
            if (rawLineTokens) {
                return new lineTokens_1.LineTokens(new Uint32Array(rawLineTokens), this._text);
            }
            var lineTokens = new Uint32Array(2);
            lineTokens[0] = 0;
            lineTokens[1] = getDefaultMetadata(topLevelLanguageId);
            return new lineTokens_1.LineTokens(lineTokens, this._text);
        };
        // --- END TOKENS
        ModelLine.prototype._createTokensAdjuster = function () {
            var _this = this;
            if (!this._lineTokens) {
                // This line does not have real tokens, so there is nothing to adjust
                return NO_OP_TOKENS_ADJUSTER;
            }
            var lineTokens = new Uint32Array(this._lineTokens);
            var tokensLength = (lineTokens.length >>> 1);
            var tokenIndex = 0;
            var tokenStartOffset = 0;
            var removeTokensCount = 0;
            var adjust = function (toColumn, delta, minimumAllowedColumn) {
                // console.log(`------------------------------------------------------------------`);
                // console.log(`before call: tokenIndex: ${tokenIndex}: ${lineTokens}`);
                // console.log(`adjustTokens: ${toColumn} with delta: ${delta} and [${minimumAllowedColumn}]`);
                // console.log(`tokenStartOffset: ${tokenStartOffset}`);
                var minimumAllowedIndex = minimumAllowedColumn - 1;
                while (tokenStartOffset < toColumn && tokenIndex < tokensLength) {
                    if (tokenStartOffset > 0 && delta !== 0) {
                        // adjust token's `startIndex` by `delta`
                        var newTokenStartOffset = Math.max(minimumAllowedIndex, tokenStartOffset + delta);
                        lineTokens[(tokenIndex << 1)] = newTokenStartOffset;
                        // console.log(` * adjusted token start offset for token at ${tokenIndex}: ${newTokenStartOffset}`);
                        if (delta < 0) {
                            var tmpTokenIndex = tokenIndex;
                            while (tmpTokenIndex > 0) {
                                var prevTokenStartOffset = lineTokens[((tmpTokenIndex - 1) << 1)];
                                if (prevTokenStartOffset >= newTokenStartOffset) {
                                    if (prevTokenStartOffset !== 4294967295 /* MAX_UINT_32 */) {
                                        // console.log(` * marking for deletion token at ${tmpTokenIndex - 1}`);
                                        lineTokens[((tmpTokenIndex - 1) << 1)] = 4294967295 /* MAX_UINT_32 */;
                                        removeTokensCount++;
                                    }
                                    tmpTokenIndex--;
                                }
                                else {
                                    break;
                                }
                            }
                        }
                    }
                    tokenIndex++;
                    if (tokenIndex < tokensLength) {
                        tokenStartOffset = lineTokens[(tokenIndex << 1)];
                    }
                }
                // console.log(`after call: tokenIndex: ${tokenIndex}: ${lineTokens}`);
            };
            var finish = function (delta, lineTextLength) {
                adjust(1073741824 /* MAX_SAFE_SMALL_INTEGER */, delta, 1);
                // Mark overflowing tokens for deletion & delete marked tokens
                _this._deleteMarkedTokens(_this._markOverflowingTokensForDeletion(removeTokensCount, lineTextLength));
            };
            return {
                adjust: adjust,
                finish: finish
            };
        };
        ModelLine.prototype._markOverflowingTokensForDeletion = function (removeTokensCount, lineTextLength) {
            if (!this._lineTokens) {
                return removeTokensCount;
            }
            var lineTokens = new Uint32Array(this._lineTokens);
            var tokensLength = (lineTokens.length >>> 1);
            if (removeTokensCount + 1 === tokensLength) {
                // no more removing, cannot end up without any tokens for mode transition reasons
                return removeTokensCount;
            }
            for (var tokenIndex = tokensLength - 1; tokenIndex > 0; tokenIndex--) {
                var tokenStartOffset = lineTokens[(tokenIndex << 1)];
                if (tokenStartOffset < lineTextLength) {
                    // valid token => stop iterating
                    return removeTokensCount;
                }
                // this token now overflows the text => mark it for removal
                if (tokenStartOffset !== 4294967295 /* MAX_UINT_32 */) {
                    // console.log(` * marking for deletion token at ${tokenIndex}`);
                    lineTokens[(tokenIndex << 1)] = 4294967295 /* MAX_UINT_32 */;
                    removeTokensCount++;
                    if (removeTokensCount + 1 === tokensLength) {
                        // no more removing, cannot end up without any tokens for mode transition reasons
                        return removeTokensCount;
                    }
                }
            }
            return removeTokensCount;
        };
        ModelLine.prototype._deleteMarkedTokens = function (removeTokensCount) {
            if (removeTokensCount === 0) {
                return;
            }
            var lineTokens = new Uint32Array(this._lineTokens);
            var tokensLength = (lineTokens.length >>> 1);
            var newTokens = new Uint32Array(((tokensLength - removeTokensCount) << 1)), newTokenIdx = 0;
            for (var i = 0; i < tokensLength; i++) {
                var startOffset = lineTokens[(i << 1)];
                if (startOffset === 4294967295 /* MAX_UINT_32 */) {
                    // marked for deletion
                    continue;
                }
                var metadata = lineTokens[(i << 1) + 1];
                newTokens[newTokenIdx++] = startOffset;
                newTokens[newTokenIdx++] = metadata;
            }
            this._lineTokens = newTokens.buffer;
        };
        ModelLine.prototype._setText = function (text, tabSize) {
            this._text = text;
            if (tabSize === 0) {
                // don't care mark
                this._metadata = this._metadata & 0x00000001;
            }
            else {
                this._setPlusOneIndentLevel(computePlusOneIndentLevel(text, tabSize));
            }
        };
        return ModelLine;
    }(AbstractModelLine));
    exports.ModelLine = ModelLine;
    /**
     * A model line that cannot store any tokenization state, nor does it compute indentation levels.
     * It has no fields except the text.
     */
    var MinimalModelLine = (function (_super) {
        __extends(MinimalModelLine, _super);
        function MinimalModelLine(text, tabSize) {
            var _this = _super.call(this, false) || this;
            _this._setText(text, tabSize);
            return _this;
        }
        Object.defineProperty(MinimalModelLine.prototype, "text", {
            get: function () { return this._text; },
            enumerable: true,
            configurable: true
        });
        MinimalModelLine.prototype.isInvalid = function () {
            return false;
        };
        MinimalModelLine.prototype.setIsInvalid = function (isInvalid) {
        };
        /**
         * Returns:
         *  - -1 => the line consists of whitespace
         *  - otherwise => the indent level is returned value
         */
        MinimalModelLine.prototype.getIndentLevel = function () {
            return 0;
        };
        MinimalModelLine.prototype.updateTabSize = function (tabSize) {
        };
        MinimalModelLine.prototype._createModelLine = function (text, tabSize) {
            return new MinimalModelLine(text, tabSize);
        };
        MinimalModelLine.prototype.split = function (markersTracker, splitColumn, forceMoveMarkers, tabSize) {
            return _super.prototype.split.call(this, markersTracker, splitColumn, forceMoveMarkers, tabSize);
        };
        MinimalModelLine.prototype.append = function (markersTracker, myLineNumber, other, tabSize) {
            _super.prototype.append.call(this, markersTracker, myLineNumber, other, tabSize);
        };
        // --- BEGIN STATE
        MinimalModelLine.prototype.resetTokenizationState = function () {
        };
        MinimalModelLine.prototype.setState = function (state) {
        };
        MinimalModelLine.prototype.getState = function () {
            return null;
        };
        // --- END STATE
        // --- BEGIN TOKENS
        MinimalModelLine.prototype.setTokens = function (topLevelLanguageId, tokens) {
        };
        MinimalModelLine.prototype.getTokens = function (topLevelLanguageId) {
            var lineTokens = new Uint32Array(2);
            lineTokens[0] = 0;
            lineTokens[1] = getDefaultMetadata(topLevelLanguageId);
            return new lineTokens_1.LineTokens(lineTokens, this._text);
        };
        // --- END TOKENS
        MinimalModelLine.prototype._createTokensAdjuster = function () {
            // This line does not have real tokens, so there is nothing to adjust
            return NO_OP_TOKENS_ADJUSTER;
        };
        MinimalModelLine.prototype._setText = function (text, tabSize) {
            this._text = text;
        };
        return MinimalModelLine;
    }(AbstractModelLine));
    exports.MinimalModelLine = MinimalModelLine;
    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;
    }
});

define(__m[95/*vs/editor/common/model/wordHelper*/], __M([1/*require*/,0/*exports*/]), 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 });
    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 usualSeparators = exports.USUAL_WORD_SEPARATORS;
        var source = '(-?\\d*\\.\\d\\w*)|([^';
        for (var i = 0; i < usualSeparators.length; i++) {
            if (allowInWords.indexOf(usualSeparators[i]) >= 0) {
                continue;
            }
            source += '\\' + usualSeparators[i];
        }
        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';
                }
                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;
        var end = text.indexOf(' ', pos);
        if (end === -1) {
            end = text.length;
        }
        wordDefinition.lastIndex = start;
        var match;
        while (match = wordDefinition.exec(text)) {
            if (match.index <= pos && wordDefinition.lastIndex >= pos) {
                return {
                    word: match[0],
                    startColumn: textOffset + 1 + match.index,
                    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)) {
            if (match.index > 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 + match.index,
                    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
            ? getWordAtPosSlow(column, wordDefinition, text, textOffset)
            : 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;
});

define(__m[511/*vs/editor/common/modes/abstractMode*/], __M([1/*require*/,0/*exports*/]), 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 FrankensteinMode = (function () {
        function FrankensteinMode(languageIdentifier) {
            this._languageIdentifier = languageIdentifier;
        }
        FrankensteinMode.prototype.getId = function () {
            return this._languageIdentifier.language;
        };
        FrankensteinMode.prototype.getLanguageIdentifier = function () {
            return this._languageIdentifier;
        };
        return FrankensteinMode;
    }());
    exports.FrankensteinMode = FrankensteinMode;
});

define(__m[60/*vs/editor/common/modes/languageConfiguration*/], __M([1/*require*/,0/*exports*/]), 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 });
    /**
     * 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 = (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[513/*vs/editor/common/modes/languageSelector*/], __M([1/*require*/,0/*exports*/,165/*vs/base/common/glob*/]), function (require, exports, glob_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function matches(selection, uri, language) {
        return score(selection, uri, language) > 0;
    }
    exports.default = matches;
    function score(selector, candidateUri, candidateLanguage) {
        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);
                if (value === 10) {
                    return value; // already at the highest
                }
                if (value > ret) {
                    ret = value;
                }
            }
            return ret;
        }
        else if (typeof selector === 'string') {
            // short-hand notion, desugars to
            // 'fooLang' -> [{ language: 'fooLang', scheme: 'file' }, { language: 'fooLang', scheme: 'untitled' }]
            // '*' -> { language: '*', scheme: '*' }
            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;
            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[533/*vs/editor/common/modes/languageFeatureRegistry*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/event*/,513/*vs/editor/common/modes/languageSelector*/]), function (require, exports, event_1, languageSelector_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var LanguageFeatureRegistry = (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 {
                dispose: 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 || model.isTooLargeForHavingARichMode()) {
                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 || model.isTooLargeForHavingARichMode()) {
                return;
            }
            this._updateScores(model);
            for (var from = 0; from < this._entries.length; from++) {
                var entry = this._entries[from];
                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);
            }
            // 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.default = LanguageFeatureRegistry;
});

define(__m[536/*vs/editor/common/modes/linkComputer*/], __M([1/*require*/,0/*exports*/,89/*vs/editor/common/core/characterClassifier*/,96/*vs/editor/common/core/uint*/]), function (require, exports, characterClassifier_1, uint_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var State;
    (function (State) {
        State[State["Invalid"] = 0] = "Invalid";
        State[State["Start"] = 1] = "Start";
        State[State["H"] = 2] = "H";
        State[State["HT"] = 3] = "HT";
        State[State["HTT"] = 4] = "HTT";
        State[State["HTTP"] = 5] = "HTTP";
        State[State["F"] = 6] = "F";
        State[State["FI"] = 7] = "FI";
        State[State["FIL"] = 8] = "FIL";
        State[State["BeforeColon"] = 9] = "BeforeColon";
        State[State["AfterColon"] = 10] = "AfterColon";
        State[State["AlmostThere"] = 11] = "AlmostThere";
        State[State["End"] = 12] = "End";
        State[State["Accept"] = 13] = "Accept";
    })(State || (State = {}));
    var StateMachine = (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;
    }());
    // 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 CharacterClass;
    (function (CharacterClass) {
        CharacterClass[CharacterClass["None"] = 0] = "None";
        CharacterClass[CharacterClass["ForceTermination"] = 1] = "ForceTermination";
        CharacterClass[CharacterClass["CannotEndIn"] = 2] = "CannotEndIn";
    })(CharacterClass || (CharacterClass = {}));
    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 = (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);
            return {
                range: {
                    startLineNumber: lineNumber,
                    startColumn: linkBeginIndex + 1,
                    endLineNumber: lineNumber,
                    endColumn: lastIncludedCharIndex + 2
                },
                url: line.substring(linkBeginIndex, lastIncludedCharIndex + 1)
            };
        };
        LinkComputer.computeLinks = function (model) {
            var 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 = 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;
    }());
    /**
     * 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;
});

define(__m[543/*vs/editor/common/modes/supports/characterPair*/], __M([1/*require*/,0/*exports*/,60/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, languageConfiguration_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CharacterPairSupport = (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._surroundingPairs = config.surroundingPairs || this._autoClosingPairs;
        }
        CharacterPairSupport.prototype.getAutoClosingPairs = function () {
            return this._autoClosingPairs;
        };
        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; i < this._autoClosingPairs.length; ++i) {
                var autoClosingPair = this._autoClosingPairs[i];
                if (autoClosingPair.open === character) {
                    return autoClosingPair.isOK(standardTokenType);
                }
            }
            return true;
        };
        CharacterPairSupport.prototype.getSurroundingPairs = function () {
            return this._surroundingPairs;
        };
        return CharacterPairSupport;
    }());
    exports.CharacterPairSupport = CharacterPairSupport;
});

define(__m[545/*vs/editor/common/modes/supports/indentRules*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,60/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, strings, languageConfiguration_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var IndentConsts;
    (function (IndentConsts) {
        IndentConsts[IndentConsts["INCREASE_MASK"] = 1] = "INCREASE_MASK";
        IndentConsts[IndentConsts["DECREASE_MASK"] = 2] = "DECREASE_MASK";
        IndentConsts[IndentConsts["INDENT_NEXTLINE_MASK"] = 4] = "INDENT_NEXTLINE_MASK";
        IndentConsts[IndentConsts["UNINDENT_MASK"] = 8] = "UNINDENT_MASK";
    })(IndentConsts = exports.IndentConsts || (exports.IndentConsts = {}));
    ;
    var IndentRulesSupport = (function () {
        function IndentRulesSupport(indentationRules) {
            this._indentationRules = indentationRules;
        }
        IndentRulesSupport.prototype.onType = function (text) {
            if (this._indentationRules) {
                if (this._indentationRules.unIndentedLinePattern && this._indentationRules.unIndentedLinePattern.test(text)) {
                    return null;
                }
                if (this._indentationRules.decreaseIndentPattern && this._indentationRules.decreaseIndentPattern.test(text)) {
                    return languageConfiguration_1.IndentAction.Outdent;
                }
            }
            return null;
        };
        IndentRulesSupport.prototype.containNonWhitespace = function (text) {
            // the text doesn't contain any non-whitespace character.
            var nonWhitespaceIdx = strings.lastNonWhitespaceIndex(text);
            if (nonWhitespaceIdx >= 0) {
                return true;
            }
            return false;
        };
        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;
});

define(__m[546/*vs/editor/common/modes/supports/inplaceReplaceSupport*/], __M([1/*require*/,0/*exports*/]), 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 BasicInplaceReplace = (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)), n1 = Number(value), 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;
});

define(__m[550/*vs/editor/common/modes/supports/onEnter*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,9/*vs/base/common/strings*/,60/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, errors_1, strings, languageConfiguration_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var OnEnterSupport = (function () {
        function OnEnterSupport(opts) {
            opts = opts || {};
            opts.brackets = opts.brackets || [
                ['(', ')'],
                ['{', '}'],
                ['[', ']']
            ];
            this._brackets = opts.brackets.map(function (bracket) {
                return {
                    open: bracket[0],
                    openRegExp: OnEnterSupport._createOpenBracketRegExp(bracket[0]),
                    close: bracket[1],
                    closeRegExp: OnEnterSupport._createCloseBracketRegExp(bracket[1]),
                };
            });
            this._regExpRules = opts.regExpRules || [];
            this._indentationRules = opts.indentationRules;
        }
        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];
                if (rule.beforeText.test(beforeEnterText)) {
                    if (rule.afterText) {
                        if (rule.afterText.test(afterEnterText)) {
                            return rule.action;
                        }
                    }
                    else {
                        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;
});

define(__m[98/*vs/editor/common/modes/supports/richEditBrackets*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,2/*vs/editor/common/core/range*/]), function (require, exports, strings, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var RichEditBracket = (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 = (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 createOrRegex([input.open, input.close]);
    });
    var getReversedRegexForBracketPair = once(function (input) { return input.open + ";" + input.close; }, function (input) {
        return createOrRegex([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 createOrRegex(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 createOrRegex(pieces);
    });
    function createOrRegex(pieces) {
        var regexStr = "(" + pieces.map(strings.escapeRegExpCharacters).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 = (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;
            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;
            var matchLength = m[0].length;
            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;
});

define(__m[202/*vs/editor/common/modes/supports/tokenization*/], __M([1/*require*/,0/*exports*/,32/*vs/base/common/color*/]), function (require, exports, color_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ParsedTokenThemeRule = (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) {
        // 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();
        // ensure default foreground gets id 1 and default background gets id 2
        var defaults = new ThemeTrieElementRule(defaultFontStyle, colorMap.getId(defaultForeground), colorMap.getId(defaultBackground));
        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 ColorMap = (function () {
        function ColorMap() {
            this._lastColorId = 0;
            this._id2color = [];
            this._color2id = new Map();
        }
        ColorMap.prototype.getId = function (color) {
            if (color === null) {
                return 0;
            }
            color = color.toUpperCase();
            if (!/^[0-9A-F]{6}$/.test(color)) {
                throw new Error('Illegal color name: ' + color);
            }
            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 = (function () {
        function TokenTheme(colorMap, root) {
            this._colorMap = colorMap;
            this._root = root;
            this._cache = new Map();
        }
        TokenTheme.createFromRawTokenTheme = function (source) {
            return this.createFromParsedTokenTheme(parseTokenTheme(source));
        };
        TokenTheme.createFromParsedTokenTheme = function (source) {
            return resolveParsedTokenThemeRules(source);
        };
        TokenTheme.prototype.getColorMap = function () {
            return this._colorMap.getColorMap();
        };
        /**
         * used for testing purposes
         */
        TokenTheme.prototype.getThemeTrieElement = function () {
            return this._root.toExternalThemeTrieElement();
        };
        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)\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 */;
        }
        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 = (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.cloneArr = function (arr) {
            var r = [];
            for (var i = 0, len = arr.length; i < len; i++) {
                r[i] = arr[i].clone();
            }
            return r;
        };
        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 ExternalThemeTrieElement = (function () {
        function ExternalThemeTrieElement(mainRule, children) {
            this.mainRule = mainRule;
            this.children = children || Object.create(null);
        }
        return ExternalThemeTrieElement;
    }());
    exports.ExternalThemeTrieElement = ExternalThemeTrieElement;
    var ThemeTrieElement = (function () {
        function ThemeTrieElement(mainRule) {
            this._mainRule = mainRule;
            this._children = new Map();
        }
        /**
         * used for testing purposes
         */
        ThemeTrieElement.prototype.toExternalThemeTrieElement = function () {
            var children = Object.create(null);
            this._children.forEach(function (element, index) {
                children[index] = element.toExternalThemeTrieElement();
            });
            return new ExternalThemeTrieElement(this._mainRule, children);
        };
        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.toString() + "; }";
        }
        rules.push('.mtki { font-style: italic; }');
        rules.push('.mtkb { font-weight: bold; }');
        rules.push('.mtku { text-decoration: underline; }');
        return rules.join('\n');
    }
    exports.generateTokensCSSForColorMap = generateTokensCSSForColorMap;
});

define(__m[203/*vs/editor/common/modes/tokenizationRegistry*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/event*/,26/*vs/base/common/objects*/]), function (require, exports, event_1, objects) {
    /*---------------------------------------------------------------------------------------------
     *  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 TokenizationRegistryImpl = (function () {
        function TokenizationRegistryImpl() {
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
            this._map = Object.create(null);
            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[language] = support;
            this.fire([language]);
            return {
                dispose: function () {
                    if (_this._map[language] !== support) {
                        return;
                    }
                    delete _this._map[language];
                    _this.fire([language]);
                }
            };
        };
        TokenizationRegistryImpl.prototype.get = function (language) {
            return (this._map[language] || null);
        };
        TokenizationRegistryImpl.prototype.setColorMap = function (colorMap) {
            if (!objects.equals(colorMap, this._colorMap)) {
                this._colorMap = colorMap;
                this._onDidChange.fire({
                    changedLanguages: Object.keys(this._map),
                    changedColorMap: true
                });
            }
        };
        TokenizationRegistryImpl.prototype.getColorMap = function () {
            return this._colorMap;
        };
        TokenizationRegistryImpl.prototype.getDefaultForeground = function () {
            return this._colorMap[1 /* DefaultForeground */];
        };
        TokenizationRegistryImpl.prototype.getDefaultBackground = function () {
            return this._colorMap[2 /* DefaultBackground */];
        };
        return TokenizationRegistryImpl;
    }());
    exports.TokenizationRegistryImpl = TokenizationRegistryImpl;
});

define(__m[17/*vs/editor/common/modes*/], __M([1/*require*/,0/*exports*/,533/*vs/editor/common/modes/languageFeatureRegistry*/,203/*vs/editor/common/modes/tokenizationRegistry*/]), function (require, exports, languageFeatureRegistry_1, tokenizationRegistry_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * Open ended enum at runtime
     * @internal
     */
    var LanguageId;
    (function (LanguageId) {
        LanguageId[LanguageId["Null"] = 0] = "Null";
        LanguageId[LanguageId["PlainText"] = 1] = "PlainText";
    })(LanguageId = exports.LanguageId || (exports.LanguageId = {}));
    /**
     * @internal
     */
    var LanguageIdentifier = (function () {
        function LanguageIdentifier(language, id) {
            this.language = language;
            this.id = id;
        }
        return LanguageIdentifier;
    }());
    exports.LanguageIdentifier = LanguageIdentifier;
    /**
     * A font style. Values are 2^x such that a bit mask can be used.
     * @internal
     */
    var FontStyle;
    (function (FontStyle) {
        FontStyle[FontStyle["NotSet"] = -1] = "NotSet";
        FontStyle[FontStyle["None"] = 0] = "None";
        FontStyle[FontStyle["Italic"] = 1] = "Italic";
        FontStyle[FontStyle["Bold"] = 2] = "Bold";
        FontStyle[FontStyle["Underline"] = 4] = "Underline";
    })(FontStyle = exports.FontStyle || (exports.FontStyle = {}));
    /**
     * Open ended enum at runtime
     * @internal
     */
    var ColorId;
    (function (ColorId) {
        ColorId[ColorId["None"] = 0] = "None";
        ColorId[ColorId["DefaultForeground"] = 1] = "DefaultForeground";
        ColorId[ColorId["DefaultBackground"] = 2] = "DefaultBackground";
    })(ColorId = exports.ColorId || (exports.ColorId = {}));
    /**
     * A standard token type. Values are 2^x such that a bit mask can be used.
     * @internal
     */
    var StandardTokenType;
    (function (StandardTokenType) {
        StandardTokenType[StandardTokenType["Other"] = 0] = "Other";
        StandardTokenType[StandardTokenType["Comment"] = 1] = "Comment";
        StandardTokenType[StandardTokenType["String"] = 2] = "String";
        StandardTokenType[StandardTokenType["RegEx"] = 4] = "RegEx";
    })(StandardTokenType = exports.StandardTokenType || (exports.StandardTokenType = {}));
    /**
     * Helpers to manage the "collapsed" metadata of an entire StackElement stack.
     * The following assumptions have been made:
     *  - languageId < 256 => needs 8 bits
     *  - unique color count < 512 => needs 9 bits
     *
     * The binary format is:
     * - -------------------------------------------
     *     3322 2222 2222 1111 1111 1100 0000 0000
     *     1098 7654 3210 9876 5432 1098 7654 3210
     * - -------------------------------------------
     *     xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
     *     bbbb bbbb bfff ffff ffFF FTTT LLLL LLLL
     * - -------------------------------------------
     *  - L = LanguageId (8 bits)
     *  - T = StandardTokenType (3 bits)
     *  - F = FontStyle (3 bits)
     *  - f = foreground color (9 bits)
     *  - b = background color (9 bits)
     *
     * @internal
     */
    var MetadataConsts;
    (function (MetadataConsts) {
        MetadataConsts[MetadataConsts["LANGUAGEID_MASK"] = 255] = "LANGUAGEID_MASK";
        MetadataConsts[MetadataConsts["TOKEN_TYPE_MASK"] = 1792] = "TOKEN_TYPE_MASK";
        MetadataConsts[MetadataConsts["FONT_STYLE_MASK"] = 14336] = "FONT_STYLE_MASK";
        MetadataConsts[MetadataConsts["FOREGROUND_MASK"] = 8372224] = "FOREGROUND_MASK";
        MetadataConsts[MetadataConsts["BACKGROUND_MASK"] = 4286578688] = "BACKGROUND_MASK";
        MetadataConsts[MetadataConsts["LANGUAGEID_OFFSET"] = 0] = "LANGUAGEID_OFFSET";
        MetadataConsts[MetadataConsts["TOKEN_TYPE_OFFSET"] = 8] = "TOKEN_TYPE_OFFSET";
        MetadataConsts[MetadataConsts["FONT_STYLE_OFFSET"] = 11] = "FONT_STYLE_OFFSET";
        MetadataConsts[MetadataConsts["FOREGROUND_OFFSET"] = 14] = "FOREGROUND_OFFSET";
        MetadataConsts[MetadataConsts["BACKGROUND_OFFSET"] = 23] = "BACKGROUND_OFFSET";
    })(MetadataConsts = exports.MetadataConsts || (exports.MetadataConsts = {}));
    /**
     * 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 = {}));
    /**
     * @internal
     */
    exports.symbolKindToCssClass = (function () {
        var _fromMapping = Object.create(null);
        _fromMapping[SymbolKind.File] = 'file';
        _fromMapping[SymbolKind.Module] = 'module';
        _fromMapping[SymbolKind.Namespace] = 'namespace';
        _fromMapping[SymbolKind.Package] = 'package';
        _fromMapping[SymbolKind.Class] = 'class';
        _fromMapping[SymbolKind.Method] = 'method';
        _fromMapping[SymbolKind.Property] = 'property';
        _fromMapping[SymbolKind.Field] = 'field';
        _fromMapping[SymbolKind.Constructor] = 'constructor';
        _fromMapping[SymbolKind.Enum] = 'enum';
        _fromMapping[SymbolKind.Interface] = 'interface';
        _fromMapping[SymbolKind.Function] = 'function';
        _fromMapping[SymbolKind.Variable] = 'variable';
        _fromMapping[SymbolKind.Constant] = 'constant';
        _fromMapping[SymbolKind.String] = 'string';
        _fromMapping[SymbolKind.Number] = 'number';
        _fromMapping[SymbolKind.Boolean] = 'boolean';
        _fromMapping[SymbolKind.Array] = 'array';
        _fromMapping[SymbolKind.Object] = 'object';
        _fromMapping[SymbolKind.Key] = 'key';
        _fromMapping[SymbolKind.Null] = 'null';
        _fromMapping[SymbolKind.EnumMember] = 'enum-member';
        _fromMapping[SymbolKind.Struct] = 'struct';
        _fromMapping[SymbolKind.Event] = 'event';
        _fromMapping[SymbolKind.Operator] = 'operator';
        _fromMapping[SymbolKind.TypeParameter] = 'type-parameter';
        return function toCssClassName(kind) {
            return _fromMapping[kind] || 'property';
        };
    })();
    // --- feature registries ------
    /**
     * @internal
     */
    exports.ReferenceProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.RenameProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.SuggestRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.SignatureHelpProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.HoverProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.DocumentSymbolProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.DocumentHighlightProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.DefinitionProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.ImplementationProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.TypeDefinitionProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.CodeLensProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.CodeActionProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.DocumentFormattingEditProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.DocumentRangeFormattingEditProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.OnTypeFormattingEditProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.LinkProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.ColorProviderRegistry = new languageFeatureRegistry_1.default();
    /**
     * @internal
     */
    exports.TokenizationRegistry = new tokenizationRegistry_1.TokenizationRegistryImpl();
});

define(__m[68/*vs/editor/common/modes/nullMode*/], __M([1/*require*/,0/*exports*/,17/*vs/editor/common/modes*/,97/*vs/editor/common/core/token*/]), function (require, exports, modes_1, token_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var NullStateImpl = (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);
    }
    exports.nullTokenize2 = nullTokenize2;
});

define(__m[91/*vs/editor/common/modes/supports*/], __M([1/*require*/,0/*exports*/,17/*vs/editor/common/modes*/]), function (require, exports, modes) {
    /*---------------------------------------------------------------------------------------------
     *  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 });
    function createScopedLineTokens(context, offset) {
        var tokenCount = context.getTokenCount();
        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.getTokenStartOffset(firstTokenIndex), context.getTokenEndOffset(lastTokenIndex));
    }
    exports.createScopedLineTokens = createScopedLineTokens;
    var ScopedLineTokens = (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.getTokenStartOffset = function (tokenIndex) {
            return this._actual.getTokenStartOffset(tokenIndex + this._firstTokenIndex) - this.firstCharOffset;
        };
        ScopedLineTokens.prototype.getStandardTokenType = function (tokenIndex) {
            return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex);
        };
        return ScopedLineTokens;
    }());
    exports.ScopedLineTokens = ScopedLineTokens;
    var IgnoreBracketsInTokens;
    (function (IgnoreBracketsInTokens) {
        IgnoreBracketsInTokens[IgnoreBracketsInTokens["value"] = 7] = "value";
    })(IgnoreBracketsInTokens || (IgnoreBracketsInTokens = {}));
    function ignoreBracketsInToken(standardTokenType) {
        return (standardTokenType & 7 /* value */) !== 0;
    }
    exports.ignoreBracketsInToken = ignoreBracketsInToken;
});

define(__m[207/*vs/editor/common/modes/supports/electricCharacter*/], __M([1/*require*/,0/*exports*/,91/*vs/editor/common/modes/supports*/,98/*vs/editor/common/modes/supports/richEditBrackets*/,60/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, supports_1, richEditBrackets_1, languageConfiguration_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var BracketElectricCharacterSupport = (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 actual = line.substring(line.length - pair.open.length + 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;
});

define(__m[43/*vs/editor/common/modes/languageConfigurationRegistry*/], __M([1/*require*/,0/*exports*/,543/*vs/editor/common/modes/supports/characterPair*/,207/*vs/editor/common/modes/supports/electricCharacter*/,550/*vs/editor/common/modes/supports/onEnter*/,545/*vs/editor/common/modes/supports/indentRules*/,98/*vs/editor/common/modes/supports/richEditBrackets*/,11/*vs/base/common/event*/,10/*vs/base/common/errors*/,9/*vs/base/common/strings*/,95/*vs/editor/common/model/wordHelper*/,91/*vs/editor/common/modes/supports*/,2/*vs/editor/common/core/range*/,60/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, characterPair_1, electricCharacter_1, onEnter_1, indentRules_1, richEditBrackets_1, event_1, errors_1, strings, wordHelper_1, supports_1, range_1, languageConfiguration_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var RichEditSupport = (function () {
        function RichEditSupport(languageIdentifier, previous, rawConf) {
            var prev = null;
            if (previous) {
                prev = previous._conf;
            }
            this._conf = RichEditSupport._mergeConf(prev, rawConf);
            if (this._conf.brackets) {
                this.brackets = new richEditBrackets_1.RichEditBrackets(languageIdentifier, this._conf.brackets);
            }
            this.onEnter = RichEditSupport._handleOnEnter(this._conf);
            this.comments = RichEditSupport._handleComments(this._conf);
            this.characterPair = new characterPair_1.CharacterPairSupport(this._conf);
            this.electricCharacter = new electricCharacter_1.BracketElectricCharacterSupport(this.brackets, this.characterPair.getAutoClosingPairs(), this._conf.__electricCharacterSupport);
            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);
            }
        }
        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),
                __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;
                onEnter.indentationRules = conf.indentationRules;
            }
            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 LanguageConfigurationRegistryImpl = (function () {
        function LanguageConfigurationRegistryImpl() {
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
            this._entries = [];
        }
        LanguageConfigurationRegistryImpl.prototype.register = function (languageIdentifier, configuration) {
            var _this = this;
            var previous = this._getRichEditSupport(languageIdentifier.id);
            var current = new RichEditSupport(languageIdentifier, previous, configuration);
            this._entries[languageIdentifier.id] = current;
            this._onDidChange.fire(void 0);
            return {
                dispose: function () {
                    if (_this._entries[languageIdentifier.id] === current) {
                        _this._entries[languageIdentifier.id] = previous;
                        _this._onDidChange.fire(void 0);
                    }
                }
            };
        };
        LanguageConfigurationRegistryImpl.prototype._getRichEditSupport = function (languageId) {
            return this._entries[languageId] || null;
        };
        LanguageConfigurationRegistryImpl.prototype.getIndentationRules = function (languageId) {
            var value = this._entries[languageId];
            if (!value) {
                return null;
            }
            return value.indentationRules || null;
        };
        // 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.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);
        };
        // beigin 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 = lineNumber - 1;
                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 {
                        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 = isNaN(columnNumber) ? 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();
});

define(__m[122/*vs/editor/common/modes/textToHtmlTokenizer*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,17/*vs/editor/common/modes*/,68/*vs/editor/common/modes/nullMode*/,130/*vs/editor/common/core/lineTokens*/]), function (require, exports, strings, modes_1, nullMode_1, lineTokens_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function tokenizeToString(text, languageId) {
        return _tokenizeToString(text, _getSafeTokenizationSupport(languageId));
    }
    exports.tokenizeToString = tokenizeToString;
    function tokenizeLineToHTML(text, viewLineTokens, colorMap, startOffset, endOffset, tabSize) {
        var result = "<div>";
        var charIndex = startOffset;
        var tabsCharDelta = 0;
        for (var tokenIndex = 0, lenJ = viewLineTokens.length; tokenIndex < lenJ; tokenIndex++) {
            var token = viewLineTokens[tokenIndex];
            var tokenEndIndex = token.endIndex;
            if (token.endIndex <= 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 += '&nbsp;';
                            insertSpacesCount--;
                        }
                        break;
                    case 60 /* LessThan */:
                        partContent += '&lt;';
                        break;
                    case 62 /* GreaterThan */:
                        partContent += '&gt;';
                        break;
                    case 38 /* Ampersand */:
                        partContent += '&amp;';
                        break;
                    case 0 /* Null */:
                        partContent += '&#00;';
                        break;
                    case 65279 /* UTF8_BOM */:
                    case 8232 /* LINE_SEPARATOR_2028 */:
                        partContent += '\ufffd';
                        break;
                    case 13 /* CarriageReturn */:
                        // zero width space, because carriage return would introduce a line break
                        partContent += '&#8203';
                        break;
                    default:
                        partContent += String.fromCharCode(charCode);
                }
            }
            result += "<span style=\"" + token.getInlineStyle(colorMap) + "\">" + partContent + "</span>";
            if (token.endIndex > endOffset || charIndex >= endOffset) {
                break;
            }
        }
        result += "</div>";
        return result;
    }
    exports.tokenizeLineToHTML = tokenizeLineToHTML;
    function _getSafeTokenizationSupport(languageId) {
        var tokenizationSupport = modes_1.TokenizationRegistry.get(languageId);
        if (tokenizationSupport) {
            return tokenizationSupport;
        }
        return {
            getInitialState: function () { return nullMode_1.NULL_STATE; },
            tokenize: undefined,
            tokenize2: function (buffer, state, deltaOffset) { return nullMode_1.nullTokenize2(0 /* Null */, buffer, state, deltaOffset); }
        };
    }
    function _tokenizeToString(text, tokenizationSupport) {
        var result = "<div class=\"monaco-tokenized-source\">";
        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 += "<br/>";
            }
            var tokenizationResult = tokenizationSupport.tokenize2(line, currentState, 0);
            var lineTokens = new lineTokens_1.LineTokens(tokenizationResult.tokens, line);
            var viewLineTokens = lineTokens.inflate();
            var startOffset = 0;
            for (var j = 0, lenJ = viewLineTokens.length; j < lenJ; j++) {
                var viewLineToken = viewLineTokens[j];
                result += "<span class=\"" + viewLineToken.getType() + "\">" + strings.escape(line.substring(startOffset, viewLineToken.endIndex)) + "</span>";
                startOffset = viewLineToken.endIndex;
            }
            currentState = tokenizationResult.endState;
        }
        result += "</div>";
        return result;
    }
});

define(__m[210/*vs/editor/common/services/abstractCodeEditorService*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/event*/]), function (require, exports, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var AbstractCodeEditorService = (function () {
        function AbstractCodeEditorService() {
            this._transientWatchers = {};
            this._codeEditors = Object.create(null);
            this._diffEditors = Object.create(null);
            this._onCodeEditorAdd = new event_1.Emitter();
            this._onCodeEditorRemove = new event_1.Emitter();
            this._onDiffEditorAdd = new event_1.Emitter();
            this._onDiffEditorRemove = new event_1.Emitter();
        }
        AbstractCodeEditorService.prototype.addCodeEditor = function (editor) {
            this._codeEditors[editor.getId()] = editor;
            this._onCodeEditorAdd.fire(editor);
        };
        Object.defineProperty(AbstractCodeEditorService.prototype, "onCodeEditorAdd", {
            get: function () {
                return this._onCodeEditorAdd.event;
            },
            enumerable: true,
            configurable: true
        });
        AbstractCodeEditorService.prototype.removeCodeEditor = function (editor) {
            if (delete this._codeEditors[editor.getId()]) {
                this._onCodeEditorRemove.fire(editor);
            }
        };
        Object.defineProperty(AbstractCodeEditorService.prototype, "onCodeEditorRemove", {
            get: function () {
                return this._onCodeEditorRemove.event;
            },
            enumerable: true,
            configurable: true
        });
        AbstractCodeEditorService.prototype.getCodeEditor = function (editorId) {
            return this._codeEditors[editorId] || null;
        };
        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);
        };
        Object.defineProperty(AbstractCodeEditorService.prototype, "onDiffEditorAdd", {
            get: function () {
                return this._onDiffEditorAdd.event;
            },
            enumerable: true,
            configurable: true
        });
        AbstractCodeEditorService.prototype.removeDiffEditor = function (editor) {
            if (delete this._diffEditors[editor.getId()]) {
                this._onDiffEditorRemove.fire(editor);
            }
        };
        Object.defineProperty(AbstractCodeEditorService.prototype, "onDiffEditorRemove", {
            get: function () {
                return this._onDiffEditorRemove.event;
            },
            enumerable: true,
            configurable: true
        });
        AbstractCodeEditorService.prototype.getDiffEditor = function (editorId) {
            return this._diffEditors[editorId] || null;
        };
        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; i < editors.length; i++) {
                var editor = editors[i];
                if (editor.isFocused()) {
                    // bingo!
                    return editor;
                }
                if (editor.hasWidgetFocus()) {
                    editorWithWidgetFocus = editor;
                }
            }
            return editorWithWidgetFocus;
        };
        AbstractCodeEditorService.prototype.setTransientModelProperty = function (model, key, value) {
            var uri = model.uri.toString();
            var w;
            if (this._transientWatchers.hasOwnProperty(uri)) {
                w = this._transientWatchers[uri];
            }
            else {
                w = new ModelTransientSettingWatcher(uri, model, this);
                this._transientWatchers[uri] = w;
            }
            w.set(key, value);
        };
        AbstractCodeEditorService.prototype.getTransientModelProperty = function (model, key) {
            var uri = model.uri.toString();
            if (!this._transientWatchers.hasOwnProperty(uri)) {
                return undefined;
            }
            return this._transientWatchers[uri].get(key);
        };
        AbstractCodeEditorService.prototype._removeWatcher = function (w) {
            delete this._transientWatchers[w.uri];
        };
        return AbstractCodeEditorService;
    }());
    exports.AbstractCodeEditorService = AbstractCodeEditorService;
    var ModelTransientSettingWatcher = (function () {
        function ModelTransientSettingWatcher(uri, model, owner) {
            var _this = this;
            this.uri = uri;
            this._values = {};
            model.onWillDispose(function () { return owner._removeWatcher(_this); });
        }
        ModelTransientSettingWatcher.prototype.set = function (key, value) {
            this._values[key] = value;
        };
        ModelTransientSettingWatcher.prototype.get = function (key) {
            return this._values[key];
        };
        return ModelTransientSettingWatcher;
    }());
    exports.ModelTransientSettingWatcher = ModelTransientSettingWatcher;
});

define(__m[152/*vs/editor/common/standalone/standaloneBase*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/event*/,40/*vs/base/common/keyCodes*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,7/*vs/base/common/winjs.base*/,123/*vs/base/common/cancellation*/,97/*vs/editor/common/core/token*/,24/*vs/base/common/uri*/]), function (require, exports, event_1, keyCodes_1, position_1, range_1, selection_1, winjs_base_1, cancellation_1, token_1, uri_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    // --------------------------------------------
    // This is repeated here so it can be exported
    // because TS inlines const enums
    // --------------------------------------------
    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 = exports.Severity || (exports.Severity = {}));
    // --------------------------------------------
    // This is repeated here so it can be exported
    // because TS inlines const enums
    // --------------------------------------------
    var KeyMod = (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;
    // --------------------------------------------
    // This is repeated here so it can be exported
    // because TS inlines const enums
    // --------------------------------------------
    /**
     * 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 = {}));
    function createMonacoBaseAPI() {
        return {
            editor: undefined,
            languages: undefined,
            CancellationTokenSource: cancellation_1.CancellationTokenSource,
            Emitter: event_1.Emitter,
            KeyCode: KeyCode,
            KeyMod: KeyMod,
            Position: position_1.Position,
            Range: range_1.Range,
            Selection: selection_1.Selection,
            SelectionDirection: selection_1.SelectionDirection,
            Severity: Severity,
            Promise: winjs_base_1.TPromise,
            Uri: uri_1.default,
            Token: token_1.Token
        };
    }
    exports.createMonacoBaseAPI = createMonacoBaseAPI;
});

define(__m[111/*vs/editor/common/view/minimapCharRenderer*/], __M([1/*require*/,0/*exports*/,17/*vs/editor/common/modes*/,11/*vs/base/common/event*/]), function (require, exports, modes_1, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MinimapTokensColorTracker = (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 = [null];
                this._backgroundIsLight = true;
                return;
            }
            this._colors = [null];
            for (var colorId = 1; colorId < colorMap.length; colorId++) {
                this._colors[colorId] = colorMap[colorId].toRGBA();
            }
            var backgroundLuminosity = colorMap[2 /* DefaultBackground */].getLuminosity();
            this._backgroundIsLight = (backgroundLuminosity >= 0.5);
            this._onDidChange.fire(void 0);
        };
        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 Constants;
    (function (Constants) {
        Constants[Constants["START_CH_CODE"] = 32] = "START_CH_CODE";
        Constants[Constants["END_CH_CODE"] = 126] = "END_CH_CODE";
        Constants[Constants["CHAR_COUNT"] = 95] = "CHAR_COUNT";
        Constants[Constants["SAMPLED_CHAR_HEIGHT"] = 16] = "SAMPLED_CHAR_HEIGHT";
        Constants[Constants["SAMPLED_CHAR_WIDTH"] = 10] = "SAMPLED_CHAR_WIDTH";
        Constants[Constants["SAMPLED_HALF_CHAR_WIDTH"] = 5] = "SAMPLED_HALF_CHAR_WIDTH";
        Constants[Constants["x2_CHAR_HEIGHT"] = 4] = "x2_CHAR_HEIGHT";
        Constants[Constants["x2_CHAR_WIDTH"] = 2] = "x2_CHAR_WIDTH";
        Constants[Constants["x1_CHAR_HEIGHT"] = 2] = "x1_CHAR_HEIGHT";
        Constants[Constants["x1_CHAR_WIDTH"] = 1] = "x1_CHAR_WIDTH";
        Constants[Constants["RGBA_CHANNELS_CNT"] = 4] = "RGBA_CHANNELS_CNT";
    })(Constants = exports.Constants || (exports.Constants = {}));
    var MinimapCharRenderer = (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;
});











define(__m[78/*vs/editor/common/view/renderingContext*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/]), function (require, exports, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var RestrictedRenderingContext = (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.lineIsVisible = function (lineNumber) {
            return (this.visibleRange.startLineNumber <= lineNumber
                && lineNumber <= this.visibleRange.endLineNumber);
        };
        RestrictedRenderingContext.prototype.getDecorationsInViewport = function () {
            return this.viewportData.getDecorationsInViewport();
        };
        return RestrictedRenderingContext;
    }());
    exports.RestrictedRenderingContext = RestrictedRenderingContext;
    var RenderingContext = (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) {
            var visibleRanges = this._viewLines.visibleRangesForRange2(new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column));
            if (!visibleRanges) {
                return null;
            }
            return visibleRanges[0];
        };
        return RenderingContext;
    }(RestrictedRenderingContext));
    exports.RenderingContext = RenderingContext;
    var LineVisibleRanges = (function () {
        function LineVisibleRanges(lineNumber, ranges) {
            this.lineNumber = lineNumber;
            this.ranges = ranges;
        }
        return LineVisibleRanges;
    }());
    exports.LineVisibleRanges = LineVisibleRanges;
    var HorizontalRange = (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;
});

define(__m[214/*vs/editor/browser/viewParts/lines/rangeUtil*/], __M([1/*require*/,0/*exports*/,78/*vs/editor/common/view/renderingContext*/]), function (require, exports, renderingContext_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var FloatHorizontalRange = (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 = (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) {
                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;
});

define(__m[215/*vs/editor/common/view/runtimeMinimapCharRenderer*/], __M([1/*require*/,0/*exports*/,111/*vs/editor/common/view/minimapCharRenderer*/]), function (require, exports, minimapCharRenderer_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    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,
    ];
});

define(__m[216/*vs/editor/common/view/viewContext*/], __M([1/*require*/,0/*exports*/]), 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 ViewContext = (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;
});

define(__m[217/*vs/editor/common/view/viewEventDispatcher*/], __M([1/*require*/,0/*exports*/]), 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 ViewEventDispatcher = (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;
});











define(__m[57/*vs/editor/common/view/viewEvents*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,3/*vs/base/common/lifecycle*/]), function (require, exports, errors, lifecycle_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ViewEventType;
    (function (ViewEventType) {
        ViewEventType[ViewEventType["ViewConfigurationChanged"] = 1] = "ViewConfigurationChanged";
        ViewEventType[ViewEventType["ViewCursorStateChanged"] = 2] = "ViewCursorStateChanged";
        ViewEventType[ViewEventType["ViewDecorationsChanged"] = 3] = "ViewDecorationsChanged";
        ViewEventType[ViewEventType["ViewFlushed"] = 4] = "ViewFlushed";
        ViewEventType[ViewEventType["ViewFocusChanged"] = 5] = "ViewFocusChanged";
        ViewEventType[ViewEventType["ViewLineMappingChanged"] = 6] = "ViewLineMappingChanged";
        ViewEventType[ViewEventType["ViewLinesChanged"] = 7] = "ViewLinesChanged";
        ViewEventType[ViewEventType["ViewLinesDeleted"] = 8] = "ViewLinesDeleted";
        ViewEventType[ViewEventType["ViewLinesInserted"] = 9] = "ViewLinesInserted";
        ViewEventType[ViewEventType["ViewRevealRangeRequest"] = 10] = "ViewRevealRangeRequest";
        ViewEventType[ViewEventType["ViewScrollChanged"] = 11] = "ViewScrollChanged";
        ViewEventType[ViewEventType["ViewTokensChanged"] = 12] = "ViewTokensChanged";
        ViewEventType[ViewEventType["ViewTokensColorsChanged"] = 13] = "ViewTokensColorsChanged";
        ViewEventType[ViewEventType["ViewZonesChanged"] = 14] = "ViewZonesChanged";
        ViewEventType[ViewEventType["ViewThemeChanged"] = 15] = "ViewThemeChanged";
    })(ViewEventType = exports.ViewEventType || (exports.ViewEventType = {}));
    var ViewConfigurationChangedEvent = (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.layoutInfo = source.layoutInfo;
            this.fontInfo = source.fontInfo;
            this.viewInfo = source.viewInfo;
            this.wrappingInfo = source.wrappingInfo;
        }
        return ViewConfigurationChangedEvent;
    }());
    exports.ViewConfigurationChangedEvent = ViewConfigurationChangedEvent;
    var ViewCursorStateChangedEvent = (function () {
        function ViewCursorStateChangedEvent(selections, isInEditableRange, screenReaderMessage) {
            this.type = 2 /* ViewCursorStateChanged */;
            this.selections = selections;
            this.isInEditableRange = isInEditableRange;
            this.screenReaderMessage = screenReaderMessage;
        }
        return ViewCursorStateChangedEvent;
    }());
    exports.ViewCursorStateChangedEvent = ViewCursorStateChangedEvent;
    var ViewDecorationsChangedEvent = (function () {
        function ViewDecorationsChangedEvent() {
            this.type = 3 /* ViewDecorationsChanged */;
            // Nothing to do
        }
        return ViewDecorationsChangedEvent;
    }());
    exports.ViewDecorationsChangedEvent = ViewDecorationsChangedEvent;
    var ViewFlushedEvent = (function () {
        function ViewFlushedEvent() {
            this.type = 4 /* ViewFlushed */;
            // Nothing to do
        }
        return ViewFlushedEvent;
    }());
    exports.ViewFlushedEvent = ViewFlushedEvent;
    var ViewFocusChangedEvent = (function () {
        function ViewFocusChangedEvent(isFocused) {
            this.type = 5 /* ViewFocusChanged */;
            this.isFocused = isFocused;
        }
        return ViewFocusChangedEvent;
    }());
    exports.ViewFocusChangedEvent = ViewFocusChangedEvent;
    var ViewLineMappingChangedEvent = (function () {
        function ViewLineMappingChangedEvent() {
            this.type = 6 /* ViewLineMappingChanged */;
            // Nothing to do
        }
        return ViewLineMappingChangedEvent;
    }());
    exports.ViewLineMappingChangedEvent = ViewLineMappingChangedEvent;
    var ViewLinesChangedEvent = (function () {
        function ViewLinesChangedEvent(fromLineNumber, toLineNumber) {
            this.type = 7 /* ViewLinesChanged */;
            this.fromLineNumber = fromLineNumber;
            this.toLineNumber = toLineNumber;
        }
        return ViewLinesChangedEvent;
    }());
    exports.ViewLinesChangedEvent = ViewLinesChangedEvent;
    var ViewLinesDeletedEvent = (function () {
        function ViewLinesDeletedEvent(fromLineNumber, toLineNumber) {
            this.type = 8 /* ViewLinesDeleted */;
            this.fromLineNumber = fromLineNumber;
            this.toLineNumber = toLineNumber;
        }
        return ViewLinesDeletedEvent;
    }());
    exports.ViewLinesDeletedEvent = ViewLinesDeletedEvent;
    var ViewLinesInsertedEvent = (function () {
        function ViewLinesInsertedEvent(fromLineNumber, toLineNumber) {
            this.type = 9 /* ViewLinesInserted */;
            this.fromLineNumber = fromLineNumber;
            this.toLineNumber = toLineNumber;
        }
        return ViewLinesInsertedEvent;
    }());
    exports.ViewLinesInsertedEvent = ViewLinesInsertedEvent;
    var VerticalRevealType;
    (function (VerticalRevealType) {
        VerticalRevealType[VerticalRevealType["Simple"] = 0] = "Simple";
        VerticalRevealType[VerticalRevealType["Center"] = 1] = "Center";
        VerticalRevealType[VerticalRevealType["CenterIfOutsideViewport"] = 2] = "CenterIfOutsideViewport";
        VerticalRevealType[VerticalRevealType["Top"] = 3] = "Top";
        VerticalRevealType[VerticalRevealType["Bottom"] = 4] = "Bottom";
    })(VerticalRevealType = exports.VerticalRevealType || (exports.VerticalRevealType = {}));
    var ViewRevealRangeRequestEvent = (function () {
        function ViewRevealRangeRequestEvent(range, verticalType, revealHorizontal) {
            this.type = 10 /* ViewRevealRangeRequest */;
            this.range = range;
            this.verticalType = verticalType;
            this.revealHorizontal = revealHorizontal;
        }
        return ViewRevealRangeRequestEvent;
    }());
    exports.ViewRevealRangeRequestEvent = ViewRevealRangeRequestEvent;
    var ViewScrollChangedEvent = (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 = (function () {
        function ViewTokensChangedEvent(ranges) {
            this.type = 12 /* ViewTokensChanged */;
            this.ranges = ranges;
        }
        return ViewTokensChangedEvent;
    }());
    exports.ViewTokensChangedEvent = ViewTokensChangedEvent;
    var ViewThemeChangedEvent = (function () {
        function ViewThemeChangedEvent() {
            this.type = 15 /* ViewThemeChanged */;
        }
        return ViewThemeChangedEvent;
    }());
    exports.ViewThemeChangedEvent = ViewThemeChangedEvent;
    var ViewTokensColorsChangedEvent = (function () {
        function ViewTokensColorsChangedEvent() {
            this.type = 13 /* ViewTokensColorsChanged */;
            // Nothing to do
        }
        return ViewTokensColorsChangedEvent;
    }());
    exports.ViewTokensColorsChangedEvent = ViewTokensColorsChangedEvent;
    var ViewZonesChangedEvent = (function () {
        function ViewZonesChangedEvent() {
            this.type = 14 /* ViewZonesChanged */;
            // Nothing to do
        }
        return ViewZonesChangedEvent;
    }());
    exports.ViewZonesChangedEvent = ViewZonesChangedEvent;
    var ViewEventEmitter = (function (_super) {
        __extends(ViewEventEmitter, _super);
        function ViewEventEmitter() {
            var _this = _super.call(this) || this;
            _this._listeners = [];
            return _this;
        }
        ViewEventEmitter.prototype.dispose = function () {
            this._listeners = [];
            _super.prototype.dispose.call(this);
        };
        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 {
                dispose: 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;
    function safeInvokeListener(listener, events) {
        try {
            listener(events);
        }
        catch (e) {
            errors.onUnexpectedError(e);
        }
    }
});

define(__m[138/*vs/editor/common/viewLayout/lineDecorations*/], __M([1/*require*/,0/*exports*/]), 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 LineDecoration = (function () {
        function LineDecoration(startColumn, endColumn, className, insertsBeforeOrAfter) {
            this.startColumn = startColumn;
            this.endColumn = endColumn;
            this.className = className;
            this.insertsBeforeOrAfter = insertsBeforeOrAfter;
        }
        LineDecoration._equals = function (a, b) {
            return (a.startColumn === b.startColumn
                && a.endColumn === b.endColumn
                && a.className === b.className
                && a.insertsBeforeOrAfter === b.insertsBeforeOrAfter);
        };
        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()) {
                    // Ignore empty range decorations
                    continue;
                }
                var startColumn = (range.startLineNumber === lineNumber ? range.startColumn : minLineColumn);
                var endColumn = (range.endLineNumber === lineNumber ? range.endColumn : maxLineColumn);
                if (endColumn <= 1) {
                    // An empty decoration (endColumn === 1)
                    continue;
                }
                result[resultLen++] = new LineDecoration(startColumn, endColumn, d.inlineClassName, d.insertsBeforeOrAfter);
            }
            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 = (function () {
        function DecorationSegment(startOffset, endOffset, className) {
            this.startOffset = startOffset;
            this.endOffset = endOffset;
            this.className = className;
        }
        return DecorationSegment;
    }());
    exports.DecorationSegment = DecorationSegment;
    var Stack = (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 = (function () {
        function LineDecorationsNormalizer() {
        }
        /**
         * Normalize line decorations. Overlapping decorations will generate multiple segments
         */
        LineDecorationsNormalizer.normalize = function (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 currentStartOffset = d.startColumn - 1;
                var currentEndOffset = d.endColumn - 2;
                nextStartOffset = stack.consumeLowerThan(currentStartOffset, nextStartOffset, result);
                if (stack.count === 0) {
                    nextStartOffset = currentStartOffset;
                }
                stack.insert(currentEndOffset, d.className);
            }
            stack.consumeLowerThan(1073741824 /* MAX_SAFE_SMALL_INTEGER */, nextStartOffset, result);
            return result;
        };
        return LineDecorationsNormalizer;
    }());
    exports.LineDecorationsNormalizer = LineDecorationsNormalizer;
});

define(__m[106/*vs/editor/common/viewLayout/viewLineRenderer*/], __M([1/*require*/,0/*exports*/,90/*vs/editor/common/core/viewLineToken*/,138/*vs/editor/common/viewLayout/lineDecorations*/,9/*vs/base/common/strings*/]), function (require, exports, viewLineToken_1, lineDecorations_1, strings) {
    /*---------------------------------------------------------------------------------------------
     *  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 RenderWhitespace;
    (function (RenderWhitespace) {
        RenderWhitespace[RenderWhitespace["None"] = 0] = "None";
        RenderWhitespace[RenderWhitespace["Boundary"] = 1] = "Boundary";
        RenderWhitespace[RenderWhitespace["All"] = 2] = "All";
    })(RenderWhitespace = exports.RenderWhitespace || (exports.RenderWhitespace = {}));
    var LinePart = (function () {
        function LinePart(endIndex, type) {
            this.endIndex = endIndex;
            this.type = type;
        }
        return LinePart;
    }());
    var RenderLineInput = (function () {
        function RenderLineInput(useMonospaceOptimizations, lineContent, mightContainRTL, fauxIndentLength, lineTokens, lineDecorations, tabSize, spaceWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures) {
            this.useMonospaceOptimizations = useMonospaceOptimizations;
            this.lineContent = lineContent;
            this.mightContainRTL = mightContainRTL;
            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.lineContent === other.lineContent
                && this.mightContainRTL === other.mightContainRTL
                && 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)
                && viewLineToken_1.ViewLineToken.equalsArr(this.lineTokens, other.lineTokens));
        };
        return RenderLineInput;
    }());
    exports.RenderLineInput = RenderLineInput;
    var CharacterMappingConstants;
    (function (CharacterMappingConstants) {
        CharacterMappingConstants[CharacterMappingConstants["PART_INDEX_MASK"] = 4294901760] = "PART_INDEX_MASK";
        CharacterMappingConstants[CharacterMappingConstants["CHAR_INDEX_MASK"] = 65535] = "CHAR_INDEX_MASK";
        CharacterMappingConstants[CharacterMappingConstants["CHAR_INDEX_OFFSET"] = 0] = "CHAR_INDEX_OFFSET";
        CharacterMappingConstants[CharacterMappingConstants["PART_INDEX_OFFSET"] = 16] = "PART_INDEX_OFFSET";
    })(CharacterMappingConstants = exports.CharacterMappingConstants || (exports.CharacterMappingConstants = {}));
    /**
     * Provides a both direction mapping between a line's character and its rendered position.
     */
    var CharacterMapping = (function () {
        function CharacterMapping(length, partCount) {
            this.length = length;
            this._data = new Uint32Array(this.length);
            this._partLengths = new Uint16Array(partCount);
        }
        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) {
            var partData = ((partIndex << 16 /* PART_INDEX_OFFSET */)
                | (charIndex << 0 /* CHAR_INDEX_OFFSET */)) >>> 0;
            this._data[charOffset] = partData;
        };
        CharacterMapping.prototype.setPartLength = function (partIndex, length) {
            this._partLengths[partIndex] = length;
        };
        CharacterMapping.prototype.getPartLengths = function () {
            return this._partLengths;
        };
        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 = (function () {
        function RenderLineOutput(characterMapping, html, containsRTL, containsForeignElements) {
            this.characterMapping = characterMapping;
            this.html = html;
            this.containsRTL = containsRTL;
            this.containsForeignElements = containsForeignElements;
        }
        return RenderLineOutput;
    }());
    exports.RenderLineOutput = RenderLineOutput;
    function renderViewLine(input) {
        if (input.lineContent.length === 0) {
            var containsForeignElements = false;
            // This is basically for IE's hit test to work
            var content = '<span><span>&nbsp;</span></span>';
            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.insertsBeforeOrAfter) {
                        classNames[i] = input.lineDecorations[i].className;
                        containsForeignElements = true;
                    }
                }
                if (containsForeignElements) {
                    content = "<span><span class=\"" + classNames.join(' ') + "\">&nbsp;</span></span>";
                }
            }
            return new RenderLineOutput(new CharacterMapping(0, 0), content, false, containsForeignElements);
        }
        return _renderLine(resolveRenderLineInput(input));
    }
    exports.renderViewLine = renderViewLine;
    var ResolvedRenderLineInput = (function () {
        function ResolvedRenderLineInput(fontIsMonospace, lineContent, len, isOverflowing, parts, containsForeignElements, tabSize, containsRTL, spaceWidth, renderWhitespace, renderControlCharacters) {
            this.fontIsMonospace = fontIsMonospace;
            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, tokens, input.fauxIndentLength, input.tabSize, useMonospaceOptimizations, input.renderWhitespace === 1 /* Boundary */);
        }
        var containsForeignElements = false;
        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.insertsBeforeOrAfter) {
                    containsForeignElements = true;
                    break;
                }
            }
            tokens = _applyInlineDecorations(lineContent, len, tokens, input.lineDecorations);
        }
        var containsRTL = false;
        if (input.mightContainRTL) {
            containsRTL = strings.containsRTL(lineContent);
        }
        if (!containsRTL && !input.fontLigatures) {
            tokens = splitLargeTokens(lineContent, tokens);
        }
        return new ResolvedRenderLineInput(useMonospaceOptimizations, lineContent, len, isOverflowing, tokens, containsForeignElements, input.tabSize, 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.length; tokenIndex < tokensLen; tokenIndex++) {
            var token = tokens[tokenIndex];
            var endIndex = token.endIndex;
            if (endIndex <= fauxIndentLength) {
                // The faux indent part of the line should have no token type
                continue;
            }
            var type = token.getType();
            if (endIndex >= len) {
                result[resultLen++] = new LinePart(len, type);
                break;
            }
            result[resultLen++] = new LinePart(endIndex, type);
        }
        return result;
    }
    /**
     * written as a const enum to get value inlining.
     */
    var Constants;
    (function (Constants) {
        Constants[Constants["LongToken"] = 50] = "LongToken";
    })(Constants || (Constants = {}));
    /**
     * 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) {
        var lastTokenEndIndex = 0;
        var result = [], resultLen = 0;
        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 */);
                    var lastCharInPiece = lineContent.charCodeAt(pieceEndIndex - 1);
                    if (strings.isHighSurrogate(lastCharInPiece)) {
                        // Don't cut in the middle of a surrogate pair
                        pieceEndIndex--;
                    }
                    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 (&rarr; or &middot;) do not have the same width as &nbsp;.
     * The rendering phase will generate `style="width:..."` for these tokens.
     */
    function _applyRenderWhitespace(lineContent, len, tokens, fauxIndentLength, tabSize, useMonospaceOptimizations, onlyBoundary) {
        var result = [], resultLen = 0;
        var tokenIndex = 0;
        var tokenType = tokens[tokenIndex].type;
        var tokenEndIndex = tokens[tokenIndex].endIndex;
        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 {
                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 {
                tmpIndent++;
            }
            wasInWhitespace = isInWhitespace;
            if (charIndex === tokenEndIndex) {
                tokenIndex++;
                tokenType = tokens[tokenIndex].type;
                tokenEndIndex = tokens[tokenIndex].endIndex;
            }
        }
        if (wasInWhitespace) {
            // was in whitespace token
            result[resultLen++] = new LinePart(len, 'vs-whitespace');
        }
        else {
            // was in regular token
            result[resultLen++] = new LinePart(len, 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(_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);
            }
        }
        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) {
        var fontIsMonospace = input.fontIsMonospace;
        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 out = '<span>';
        for (var partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) {
            var part = parts[partIndex];
            var partEndIndex = part.endIndex;
            var partType = part.type;
            var partRendersWhitespace = (renderWhitespace !== 0 /* None */ && (partType.indexOf('vs-whitespace') >= 0));
            charOffsetInPart = 0;
            if (partRendersWhitespace) {
                var partContentCnt = 0;
                var partContent = '';
                for (; charIndex < partEndIndex; charIndex++) {
                    characterMapping.setPartData(charIndex, partIndex, charOffsetInPart);
                    var charCode = lineContent.charCodeAt(charIndex);
                    if (charCode === 9 /* Tab */) {
                        var insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
                        tabsCharDelta += insertSpacesCount - 1;
                        charOffsetInPart += insertSpacesCount - 1;
                        if (insertSpacesCount > 0) {
                            partContent += '&rarr;';
                            partContentCnt++;
                            insertSpacesCount--;
                        }
                        while (insertSpacesCount > 0) {
                            partContent += '&nbsp;';
                            partContentCnt++;
                            insertSpacesCount--;
                        }
                    }
                    else {
                        // must be CharCode.Space
                        partContent += '&middot;';
                        partContentCnt++;
                    }
                    charOffsetInPart++;
                }
                characterMapping.setPartLength(partIndex, partContentCnt);
                if (fontIsMonospace || containsForeignElements) {
                    out += "<span class=\"" + partType + "\">" + partContent + "</span>";
                }
                else {
                    out += "<span class=\"" + partType + "\" style=\"width:" + spaceWidth * partContentCnt + "px\">" + partContent + "</span>";
                }
            }
            else {
                var partContentCnt = 0;
                var partContent = '';
                for (; charIndex < partEndIndex; charIndex++) {
                    characterMapping.setPartData(charIndex, partIndex, charOffsetInPart);
                    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) {
                                partContent += '&nbsp;';
                                partContentCnt++;
                                insertSpacesCount--;
                            }
                            break;
                        case 32 /* Space */:
                            partContent += '&nbsp;';
                            partContentCnt++;
                            break;
                        case 60 /* LessThan */:
                            partContent += '&lt;';
                            partContentCnt++;
                            break;
                        case 62 /* GreaterThan */:
                            partContent += '&gt;';
                            partContentCnt++;
                            break;
                        case 38 /* Ampersand */:
                            partContent += '&amp;';
                            partContentCnt++;
                            break;
                        case 0 /* Null */:
                            partContent += '&#00;';
                            partContentCnt++;
                            break;
                        case 65279 /* UTF8_BOM */:
                        case 8232 /* LINE_SEPARATOR_2028 */:
                            partContent += '\ufffd';
                            partContentCnt++;
                            break;
                        case 13 /* CarriageReturn */:
                            // zero width space, because carriage return would introduce a line break
                            partContent += '&#8203';
                            partContentCnt++;
                            break;
                        default:
                            if (renderControlCharacters && charCode < 32) {
                                partContent += String.fromCharCode(9216 + charCode);
                                partContentCnt++;
                            }
                            else {
                                partContent += String.fromCharCode(charCode);
                                partContentCnt++;
                            }
                    }
                    charOffsetInPart++;
                }
                characterMapping.setPartLength(partIndex, partContentCnt);
                if (containsRTL) {
                    out += "<span dir=\"ltr\" class=\"" + partType + "\">" + partContent + "</span>";
                }
                else {
                    out += "<span class=\"" + partType + "\">" + partContent + "</span>";
                }
            }
        }
        // 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);
        if (isOverflowing) {
            out += "<span>&hellip;</span>";
        }
        out += '</span>';
        return new RenderLineOutput(characterMapping, out, containsRTL, containsForeignElements);
    }
});

define(__m[221/*vs/editor/common/viewLayout/viewLinesViewportData*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/]), function (require, exports, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * Contains all data needed to render at a specific viewport.
     */
    var ViewportData = (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;
});

define(__m[222/*vs/editor/common/viewLayout/whitespaceComputer*/], __M([1/*require*/,0/*exports*/]), 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 });
    /**
     * Represent whitespaces in between lines and provide fast CRUD management methods.
     * The whitespaces are sorted ascending by `afterLineNumber`.
     */
    var WhitespaceComputer = (function () {
        function WhitespaceComputer() {
            this._heights = [];
            this._ids = [];
            this._afterLineNumbers = [];
            this._ordinals = [];
            this._prefixSum = [];
            this._prefixSumValidIndex = -1;
            this._whitespaceId2Index = {};
            this._lastWhitespaceId = 0;
        }
        /**
         * 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) {
            afterLineNumber = afterLineNumber | 0;
            ordinal = ordinal | 0;
            heightInPx = heightInPx | 0;
            var id = (++this._lastWhitespaceId);
            var insertionIndex = WhitespaceComputer.findInsertionIndex(this._afterLineNumbers, afterLineNumber, this._ordinals, ordinal);
            this._insertWhitespaceAtIndex(id, insertionIndex, afterLineNumber, ordinal, heightInPx);
            return id;
        };
        WhitespaceComputer.prototype._insertWhitespaceAtIndex = function (id, insertIndex, afterLineNumber, ordinal, heightInPx) {
            id = id | 0;
            insertIndex = insertIndex | 0;
            afterLineNumber = afterLineNumber | 0;
            ordinal = ordinal | 0;
            heightInPx = heightInPx | 0;
            this._heights.splice(insertIndex, 0, heightInPx);
            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];
                    // 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);
                    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);
                return true;
            }
            return false;
        };
        WhitespaceComputer.prototype._removeWhitespaceAtIndex = function (removeIndex) {
            removeIndex = removeIndex | 0;
            this._heights.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;
        };
        /**
         * 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;
});

define(__m[223/*vs/editor/common/viewLayout/linesLayout*/], __M([1/*require*/,0/*exports*/,222/*vs/editor/common/viewLayout/whitespaceComputer*/]), function (require, exports, whitespaceComputer_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * 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 = (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) {
            return this._whitespaces.insertWhitespace(afterLineNumber, ordinal, heightInPx);
        };
        /**
         * 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);
        };
        /**
         * Returns if there is any whitespace in the document.
         */
        LinesLayout.prototype.hasWhitespace = function () {
            return this._whitespaces.getCount() > 0;
        };
        /**
         * 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;
});

define(__m[104/*vs/editor/common/viewModel/prefixSumComputer*/], __M([1/*require*/,0/*exports*/,96/*vs/editor/common/core/uint*/]), function (require, exports, uint_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var PrefixSumIndexOfResult = (function () {
        function PrefixSumIndexOfResult(index, remainder) {
            this.index = index;
            this.remainder = remainder;
        }
        return PrefixSumIndexOfResult;
    }());
    exports.PrefixSumIndexOfResult = PrefixSumIndexOfResult;
    var PrefixSumComputer = (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;
            var midStop;
            var midStart;
            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 = (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.getCount = function () {
            return this._actual.getCount();
        };
        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;
});

define(__m[225/*vs/editor/common/model/mirrorModel*/], __M([1/*require*/,0/*exports*/,104/*vs/editor/common/viewModel/prefixSumComputer*/]), function (require, exports, prefixSumComputer_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MirrorModel = (function () {
        function MirrorModel(uri, lines, eol, versionId) {
            this._uri = uri;
            this._lines = lines;
            this._eol = eol;
            this._versionId = versionId;
        }
        MirrorModel.prototype.dispose = function () {
            this._lines.length = 0;
        };
        Object.defineProperty(MirrorModel.prototype, "version", {
            get: function () {
                return this._versionId;
            },
            enumerable: true,
            configurable: true
        });
        MirrorModel.prototype.getText = function () {
            return this._lines.join(this._eol);
        };
        MirrorModel.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, len = changes.length; i < len; i++) {
                var change = changes[i];
                this._acceptDeleteRange(change.range);
                this._acceptInsertText({
                    lineNumber: change.range.startLineNumber,
                    column: change.range.startColumn
                }, change.text);
            }
            this._versionId = e.versionId;
        };
        MirrorModel.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
         */
        MirrorModel.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);
            }
        };
        MirrorModel.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);
            }
        };
        MirrorModel.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 MirrorModel;
    }());
    exports.MirrorModel = MirrorModel;
});

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










define(__m[226/*vs/editor/common/services/editorSimpleWorker*/], __M([1/*require*/,0/*exports*/,24/*vs/base/common/uri*/,7/*vs/base/common/winjs.base*/,2/*vs/editor/common/core/range*/,457/*vs/editor/common/diff/diffComputer*/,139/*vs/base/common/diff/diff*/,12/*vs/editor/common/core/position*/,225/*vs/editor/common/model/mirrorModel*/,536/*vs/editor/common/modes/linkComputer*/,546/*vs/editor/common/modes/supports/inplaceReplaceSupport*/,95/*vs/editor/common/model/wordHelper*/,152/*vs/editor/common/standalone/standaloneBase*/]), function (require, exports, uri_1, winjs_base_1, range_1, diffComputer_1, diff_1, position_1, mirrorModel_1, linkComputer_1, inplaceReplaceSupport_1, wordHelper_1, standaloneBase_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * @internal
     */
    var MirrorModel = (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._getAllWords = function (wordDefinition) {
            var _this = this;
            var result = [];
            this._lines.forEach(function (line) {
                _this._wordenize(line, wordDefinition).forEach(function (info) {
                    result.push(line.substring(info.start, info.end));
                });
            });
            return result;
        };
        MirrorModel.prototype.getAllUniqueWords = function (wordDefinition, skipWordOnce) {
            var foundSkipWord = false;
            var uniqueWords = Object.create(null);
            return this._getAllWords(wordDefinition).filter(function (word) {
                if (skipWordOnce && !foundSkipWord && skipWordOnce === word) {
                    foundSkipWord = true;
                    return false;
                }
                else if (uniqueWords[word]) {
                    return false;
                }
                else {
                    uniqueWords[word] = true;
                    return true;
                }
            });
        };
        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, startLineIndex = range.startLineNumber - 1, endLineIndex = range.endLineNumber - 1, 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;
    }(mirrorModel_1.MirrorModel));
    /**
     * @internal
     */
    var BaseEditorSimpleWorker = (function () {
        function BaseEditorSimpleWorker() {
            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 null;
            }
            var originalLines = original.getLinesContent();
            var modifiedLines = modified.getLinesContent();
            var diffComputer = new diffComputer_1.DiffComputer(originalLines, modifiedLines, {
                shouldPostProcessCharChanges: true,
                shouldIgnoreTrimWhitespace: ignoreTrimWhitespace,
                shouldConsiderTrimWhitespaceInEmptyCase: true,
                shouldMakePrettyDiff: true
            });
            return winjs_base_1.TPromise.as(diffComputer.computeDiff());
        };
        BaseEditorSimpleWorker.prototype.computeDirtyDiff = function (originalUrl, modifiedUrl, ignoreTrimWhitespace) {
            var original = this._getModel(originalUrl);
            var modified = this._getModel(modifiedUrl);
            if (!original || !modified) {
                return null;
            }
            var originalLines = original.getLinesContent();
            var modifiedLines = modified.getLinesContent();
            var diffComputer = new diffComputer_1.DiffComputer(originalLines, modifiedLines, {
                shouldPostProcessCharChanges: false,
                shouldIgnoreTrimWhitespace: ignoreTrimWhitespace,
                shouldConsiderTrimWhitespaceInEmptyCase: false,
                shouldMakePrettyDiff: true
            });
            return winjs_base_1.TPromise.as(diffComputer.computeDiff());
        };
        BaseEditorSimpleWorker.prototype.computeMoreMinimalEdits = function (modelUrl, edits, ranges) {
            var model = this._getModel(modelUrl);
            if (!model) {
                return winjs_base_1.TPromise.as(edits);
            }
            var result = [];
            var lastEol;
            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) {
                    // eol-change only
                    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: undefined, range: undefined });
            }
            return winjs_base_1.TPromise.as(result);
        };
        // ---- END minimal edits ---------------------------------------------------------------
        BaseEditorSimpleWorker.prototype.computeLinks = function (modelUrl) {
            var model = this._getModel(modelUrl);
            if (!model) {
                return null;
            }
            return winjs_base_1.TPromise.as(linkComputer_1.computeLinks(model));
        };
        // ---- BEGIN suggest --------------------------------------------------------------------------
        BaseEditorSimpleWorker.prototype.textualSuggest = function (modelUrl, position, wordDef, wordDefFlags) {
            var model = this._getModel(modelUrl);
            if (model) {
                var suggestions = [];
                var wordDefRegExp = new RegExp(wordDef, wordDefFlags);
                var currentWord = model.getWordUntilPosition(position, wordDefRegExp).word;
                for (var _i = 0, _a = model.getAllUniqueWords(wordDefRegExp); _i < _a.length; _i++) {
                    var word = _a[_i];
                    if (word !== currentWord && isNaN(Number(word))) {
                        suggestions.push({
                            type: 'text',
                            label: word,
                            insertText: word,
                            noAutoAccept: true,
                            overwriteBefore: currentWord.length
                        });
                    }
                }
                return winjs_base_1.TPromise.as({ suggestions: suggestions });
            }
            return undefined;
        };
        // ---- END suggest --------------------------------------------------------------------------
        BaseEditorSimpleWorker.prototype.navigateValueSet = function (modelUrl, range, up, wordDef, wordDefFlags) {
            var model = this._getModel(modelUrl);
            if (!model) {
                return 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);
            var word = null;
            if (wordRange !== null) {
                word = model.getValueInRange(wordRange);
            }
            var result = inplaceReplaceSupport_1.BasicInplaceReplace.INSTANCE.navigateValueSet(range, selectionText, wordRange, word, up);
            return winjs_base_1.TPromise.as(result);
        };
        // ---- BEGIN foreign module support --------------------------------------------------------------------------
        BaseEditorSimpleWorker.prototype.loadForeignModule = function (moduleId, createData) {
            var _this = this;
            return new winjs_base_1.TPromise(function (c, e) {
                // Use the global require to be sure to get the global config
                self.require([moduleId], function (foreignModule) {
                    var ctx = {
                        getMirrorModels: function () {
                            return _this._getModels();
                        }
                    };
                    _this._foreignModule = foreignModule.create(ctx, createData);
                    var methods = [];
                    for (var prop in _this._foreignModule) {
                        if (typeof _this._foreignModule[prop] === 'function') {
                            methods.push(prop);
                        }
                    }
                    c(methods);
                }, e);
            });
        };
        // foreign method request
        BaseEditorSimpleWorker.prototype.fmr = function (method, args) {
            if (!this._foreignModule || typeof this._foreignModule[method] !== 'function') {
                return winjs_base_1.TPromise.wrapError(new Error('Missing requestHandler or method: ' + method));
            }
            try {
                return winjs_base_1.TPromise.as(this._foreignModule[method].apply(this._foreignModule, args));
            }
            catch (e) {
                return winjs_base_1.TPromise.wrapError(e);
            }
        };
        // ---- END diff --------------------------------------------------------------------------
        // ---- BEGIN minimal edits ---------------------------------------------------------------
        BaseEditorSimpleWorker._diffLimit = 10000;
        return BaseEditorSimpleWorker;
    }());
    exports.BaseEditorSimpleWorker = BaseEditorSimpleWorker;
    /**
     * @internal
     */
    var EditorSimpleWorkerImpl = (function (_super) {
        __extends(EditorSimpleWorkerImpl, _super);
        function EditorSimpleWorkerImpl() {
            var _this = _super.call(this) || 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.default.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();
    }
    exports.create = create;
    var global = self;
    var isWebWorker = (typeof global.importScripts === 'function');
    if (isWebWorker) {
        global.monaco = standaloneBase_1.createMonacoBaseAPI();
    }
});











define(__m[82/*vs/editor/common/viewModel/viewEventHandler*/], __M([1/*require*/,0/*exports*/,57/*vs/editor/common/view/viewEvents*/,3/*vs/base/common/lifecycle*/]), function (require, exports, viewEvents, lifecycle_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ViewEventHandler = (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.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 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[67/*vs/editor/browser/view/dynamicViewOverlay*/], __M([1/*require*/,0/*exports*/,82/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, viewEventHandler_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var DynamicViewOverlay = (function (_super) {
        __extends(DynamicViewOverlay, _super);
        function DynamicViewOverlay() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return DynamicViewOverlay;
    }(viewEventHandler_1.ViewEventHandler));
    exports.DynamicViewOverlay = DynamicViewOverlay;
});











define(__m[35/*vs/editor/browser/view/viewPart*/], __M([1/*require*/,0/*exports*/,82/*vs/editor/common/viewModel/viewEventHandler*/,27/*vs/base/browser/fastDomNode*/]), function (require, exports, viewEventHandler_1, fastDomNode_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ViewPart = (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);
            this._context = null;
            _super.prototype.dispose.call(this);
        };
        return ViewPart;
    }(viewEventHandler_1.ViewEventHandler));
    exports.ViewPart = ViewPart;
    var PartFingerprint;
    (function (PartFingerprint) {
        PartFingerprint[PartFingerprint["None"] = 0] = "None";
        PartFingerprint[PartFingerprint["ContentWidgets"] = 1] = "ContentWidgets";
        PartFingerprint[PartFingerprint["OverflowingContentWidgets"] = 2] = "OverflowingContentWidgets";
        PartFingerprint[PartFingerprint["OverflowGuard"] = 3] = "OverflowGuard";
        PartFingerprint[PartFingerprint["OverlayWidgets"] = 4] = "OverlayWidgets";
        PartFingerprint[PartFingerprint["ScrollableElement"] = 5] = "ScrollableElement";
        PartFingerprint[PartFingerprint["TextArea"] = 6] = "TextArea";
        PartFingerprint[PartFingerprint["ViewLines"] = 7] = "ViewLines";
        PartFingerprint[PartFingerprint["Minimap"] = 8] = "Minimap";
    })(PartFingerprint = exports.PartFingerprint || (exports.PartFingerprint = {}));
    var PartFingerprints = (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[230/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,27/*vs/base/browser/fastDomNode*/,25/*vs/editor/browser/editorBrowser*/,35/*vs/editor/browser/view/viewPart*/]), function (require, exports, dom, fastDomNode_1, editorBrowser_1, viewPart_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var Coordinate = (function () {
        function Coordinate(top, left) {
            this.top = top;
            this.left = left;
        }
        return Coordinate;
    }());
    var ViewContentWidgets = (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 = null;
            this.domNode = null;
        };
        // --- begin event handlers
        ViewContentWidgets.prototype.onConfigurationChanged = function (e) {
            var keys = Object.keys(this._widgets);
            for (var i = 0, len = keys.length; i < len; i++) {
                var widgetId = keys[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.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, preference) {
            var myWidget = this._widgets[widget.getId()];
            myWidget.setPosition(position, 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.prepareRender = function (ctx) {
            var keys = Object.keys(this._widgets);
            for (var i = 0, len = keys.length; i < len; i++) {
                var widgetId = keys[i];
                this._widgets[widgetId].prepareRender(ctx);
            }
        };
        ViewContentWidgets.prototype.render = function (ctx) {
            var keys = Object.keys(this._widgets);
            for (var i = 0, len = keys.length; i < len; i++) {
                var widgetId = keys[i];
                this._widgets[widgetId].render(ctx);
            }
        };
        return ViewContentWidgets;
    }(viewPart_1.ViewPart));
    exports.ViewContentWidgets = ViewContentWidgets;
    var Widget = (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._position = null;
            this._preference = null;
            this._isVisible = false;
            this._renderData = null;
            this.domNode.setPosition((this._fixedOverflowWidgets && this.allowEditorOverflow) ? 'fixed' : 'absolute');
            this._updateMaxWidth();
            this.domNode.setVisibility('hidden');
            this.domNode.setAttribute('widgetId', this.id);
        }
        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._updateMaxWidth();
            }
        };
        Widget.prototype._updateMaxWidth = function () {
            var maxWidth = this.allowEditorOverflow
                ? window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
                : this._contentWidth;
            this.domNode.setMaxWidth(maxWidth);
        };
        Widget.prototype.setPosition = function (position, preference) {
            this._position = position;
            this._preference = preference;
        };
        Widget.prototype._layoutBoxInViewport = function (topLeft, 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 = topLeft.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 actualLeft = topLeft.left;
            if (actualLeft + width > ctx.scrollLeft + ctx.viewportWidth) {
                actualLeft = ctx.scrollLeft + ctx.viewportWidth - width;
            }
            if (actualLeft < ctx.scrollLeft) {
                actualLeft = ctx.scrollLeft;
            }
            return {
                aboveTop: aboveTop,
                fitsAbove: fitsAbove,
                belowTop: belowTop,
                fitsBelow: fitsBelow,
                left: actualLeft
            };
        };
        Widget.prototype._layoutBoxInPage = function (topLeft, width, height, ctx) {
            var left0 = topLeft.left - ctx.scrollLeft;
            if (left0 + width < 0 || left0 > this._contentWidth) {
                return null;
            }
            var aboveTop = topLeft.top - height;
            var belowTop = topLeft.top + this._lineHeight;
            var left = left0 + 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 absoluteLeft = domNodePosition.left + left - 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 (absoluteLeft + width + 20 > INNER_WIDTH) {
                var delta = absoluteLeft - (INNER_WIDTH - width - 20);
                absoluteLeft -= delta;
                left -= delta;
            }
            if (absoluteLeft < 0) {
                var delta = absoluteLeft;
                absoluteLeft -= delta;
                left -= delta;
            }
            if (this._fixedOverflowWidgets) {
                aboveTop = absoluteAboveTop;
                belowTop = absoluteBelowTop;
                left = absoluteLeft;
            }
            return { aboveTop: aboveTop, fitsAbove: fitsAbove, belowTop: belowTop, fitsBelow: fitsBelow, left: left };
        };
        Widget.prototype._prepareRenderWidgetAtExactPositionOverflowing = function (topLeft) {
            return new Coordinate(topLeft.top, topLeft.left + this._contentLeft);
        };
        Widget.prototype._getTopLeft = function (ctx, position) {
            var visibleRange = ctx.visibleRangeForPosition(position);
            if (!visibleRange) {
                return null;
            }
            var top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.scrollTop;
            return new Coordinate(top, visibleRange.left);
        };
        Widget.prototype._prepareRenderWidget = function (ctx) {
            var _this = this;
            if (!this._position || !this._preference) {
                return null;
            }
            // Do not trust that widgets have a valid position
            var validModelPosition = this._context.model.validateModelPosition(this._position);
            if (!this._context.model.coordinatesConverter.modelPositionIsVisible(validModelPosition)) {
                // this position is hidden by the view model
                return null;
            }
            var position = this._context.model.coordinatesConverter.convertModelPositionToViewPosition(validModelPosition);
            var placement = null;
            var fetchPlacement = function () {
                if (placement) {
                    return;
                }
                var topLeft = _this._getTopLeft(ctx, position);
                if (!topLeft) {
                    return;
                }
                var domNode = _this.domNode.domNode;
                var width = domNode.clientWidth;
                var height = domNode.clientHeight;
                if (_this.allowEditorOverflow) {
                    placement = _this._layoutBoxInPage(topLeft, width, height, ctx);
                }
                else {
                    placement = _this._layoutBoxInViewport(topLeft, width, height, ctx);
                }
            };
            // Do two passes, first for perfect fit, second picks first option
            for (var pass = 1; pass <= 2; pass++) {
                for (var i = 0; i < this._preference.length; i++) {
                    var pref = this._preference[i];
                    if (pref === editorBrowser_1.ContentWidgetPositionPreference.ABOVE) {
                        fetchPlacement();
                        if (!placement) {
                            // Widget outside of viewport
                            return null;
                        }
                        if (pass === 2 || placement.fitsAbove) {
                            return new Coordinate(placement.aboveTop, placement.left);
                        }
                    }
                    else if (pref === editorBrowser_1.ContentWidgetPositionPreference.BELOW) {
                        fetchPlacement();
                        if (!placement) {
                            // Widget outside of viewport
                            return null;
                        }
                        if (pass === 2 || placement.fitsBelow) {
                            return new Coordinate(placement.belowTop, placement.left);
                        }
                    }
                    else {
                        var topLeft = this._getTopLeft(ctx, position);
                        if (!topLeft) {
                            // Widget outside of viewport
                            return null;
                        }
                        if (this.allowEditorOverflow) {
                            return this._prepareRenderWidgetAtExactPositionOverflowing(topLeft);
                        }
                        else {
                            return topLeft;
                        }
                    }
                }
            }
            return null;
        };
        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[231/*vs/editor/browser/viewParts/decorations/decorations*/], __M([1/*require*/,0/*exports*/,67/*vs/editor/browser/view/dynamicViewOverlay*/,2/*vs/editor/common/core/range*/,78/*vs/editor/common/view/renderingContext*/,278/*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 = (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._context = null;
            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.source.options.className) {
                    decorations[decorationsLen++] = d;
                }
            }
            // Sort decorations for consistent render output
            decorations = decorations.sort(function (a, b) {
                var aClassName = a.source.options.className;
                var bClassName = b.source.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.source.options.isWholeLine) {
                    continue;
                }
                var decorationOutput = ('<div class="cdr '
                    + d.source.options.className
                    + '" style="left:0;width:100%;height:'
                    + lineHeight
                    + 'px;"></div>');
                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;
            for (var i = 0, lenI = decorations.length; i < lenI; i++) {
                var d = decorations[i];
                if (d.source.options.isWholeLine) {
                    continue;
                }
                var className = d.source.options.className;
                var showIfCollapsed = d.source.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));
                }
                var linesVisibleRanges = ctx.linesVisibleRangesForRange(range, /*TODO@Alex*/ className === 'findMatch');
                if (!linesVisibleRanges) {
                    continue;
                }
                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 = ('<div class="cdr '
                            + className
                            + '" style="left:'
                            + String(visibleRange.left)
                            + 'px;width:'
                            + String(visibleRange.width)
                            + 'px;height:'
                            + lineHeight
                            + 'px;"></div>');
                        output[lineIndex] += decorationOutput;
                    }
                }
            }
        };
        DecorationsOverlay.prototype.render = function (startLineNumber, lineNumber) {
            if (!this._renderResult) {
                return '';
            }
            var lineIndex = lineNumber - startLineNumber;
            if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
                throw new Error('Unexpected render request');
            }
            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[113/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([1/*require*/,0/*exports*/,67/*vs/editor/browser/view/dynamicViewOverlay*/,279/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/]), function (require, exports, dynamicViewOverlay_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var DecorationToRender = (function () {
        function DecorationToRender(startLineNumber, endLineNumber, className) {
            this.startLineNumber = +startLineNumber;
            this.endLineNumber = +endLineNumber;
            this.className = String(className);
        }
        return DecorationToRender;
    }());
    exports.DecorationToRender = DecorationToRender;
    var DedupOverlay = (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 = (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._context = null;
            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 = [];
            for (var i = 0, len = decorations.length; i < len; i++) {
                var d = decorations[i];
                var glyphMarginClassName = d.source.options.glyphMarginClassName;
                if (glyphMarginClassName) {
                    r.push(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;"></div>';
            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] = ('<div class="cgmr '
                        + classNames.join(' ')
                        + common);
                }
            }
            this._renderResult = output;
        };
        GlyphMarginOverlay.prototype.render = function (startLineNumber, lineNumber) {
            if (!this._renderResult) {
                return '';
            }
            var lineIndex = lineNumber - startLineNumber;
            if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
                throw new Error('Unexpected render request');
            }
            return this._renderResult[lineIndex];
        };
        return GlyphMarginOverlay;
    }(DedupOverlay));
    exports.GlyphMarginOverlay = GlyphMarginOverlay;
});

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










define(__m[233/*vs/editor/browser/viewParts/linesDecorations/linesDecorations*/], __M([1/*require*/,0/*exports*/,113/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/,288/*vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations*/]), function (require, exports, glyphMargin_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var LinesDecorationsOverlay = (function (_super) {
        __extends(LinesDecorationsOverlay, _super);
        function LinesDecorationsOverlay(context) {
            var _this = _super.call(this) || this;
            _this._context = context;
            _this._decorationsLeft = _this._context.configuration.editor.layoutInfo.decorationsLeft;
            _this._decorationsWidth = _this._context.configuration.editor.layoutInfo.decorationsWidth;
            _this._renderResult = null;
            _this._context.addEventHandler(_this);
            return _this;
        }
        LinesDecorationsOverlay.prototype.dispose = function () {
            this._context.removeEventHandler(this);
            this._context = null;
            this._renderResult = null;
            _super.prototype.dispose.call(this);
        };
        // --- begin event handlers
        LinesDecorationsOverlay.prototype.onConfigurationChanged = function (e) {
            if (e.layoutInfo) {
                this._decorationsLeft = this._context.configuration.editor.layoutInfo.decorationsLeft;
                this._decorationsWidth = this._context.configuration.editor.layoutInfo.decorationsWidth;
            }
            return true;
        };
        LinesDecorationsOverlay.prototype.onDecorationsChanged = function (e) {
            return true;
        };
        LinesDecorationsOverlay.prototype.onFlushed = function (e) {
            return true;
        };
        LinesDecorationsOverlay.prototype.onLinesChanged = function (e) {
            return true;
        };
        LinesDecorationsOverlay.prototype.onLinesDeleted = function (e) {
            return true;
        };
        LinesDecorationsOverlay.prototype.onLinesInserted = function (e) {
            return true;
        };
        LinesDecorationsOverlay.prototype.onScrollChanged = function (e) {
            return e.scrollTopChanged;
        };
        LinesDecorationsOverlay.prototype.onZonesChanged = function (e) {
            return true;
        };
        // --- end event handlers
        LinesDecorationsOverlay.prototype._getDecorations = function (ctx) {
            var decorations = ctx.getDecorationsInViewport();
            var r = [];
            for (var i = 0, len = decorations.length; i < len; i++) {
                var d = decorations[i];
                var linesDecorationsClassName = d.source.options.linesDecorationsClassName;
                if (linesDecorationsClassName) {
                    r.push(new glyphMargin_1.DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, linesDecorationsClassName));
                }
            }
            return r;
        };
        LinesDecorationsOverlay.prototype.prepareRender = function (ctx) {
            var visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            var visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            var toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
            var left = this._decorationsLeft.toString();
            var width = this._decorationsWidth.toString();
            var common = '" style="left:' + left + 'px;width:' + width + 'px;"></div>';
            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 += '<div class="cldr ' + classNames[i] + common;
                }
                output[lineIndex] = lineOutput;
            }
            this._renderResult = output;
        };
        LinesDecorationsOverlay.prototype.render = function (startLineNumber, lineNumber) {
            if (!this._renderResult) {
                return '';
            }
            return this._renderResult[lineNumber - startLineNumber];
        };
        return LinesDecorationsOverlay;
    }(glyphMargin_1.DedupOverlay));
    exports.LinesDecorationsOverlay = LinesDecorationsOverlay;
});

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










define(__m[182/*vs/editor/browser/viewParts/margin/margin*/], __M([1/*require*/,0/*exports*/,27/*vs/base/browser/fastDomNode*/,35/*vs/editor/browser/view/viewPart*/]), function (require, exports, fastDomNode_1, viewPart_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var Margin = (function (_super) {
        __extends(Margin, _super);
        function Margin(context) {
            var _this = _super.call(this, context) || this;
            _this._canUseLayerHinting = _this._context.configuration.editor.canUseLayerHinting;
            _this._contentLeft = _this._context.configuration.editor.layoutInfo.contentLeft;
            _this._glyphMarginLeft = _this._context.configuration.editor.layoutInfo.glyphMarginLeft;
            _this._glyphMarginWidth = _this._context.configuration.editor.layoutInfo.glyphMarginWidth;
            _this._domNode = _this._createDomNode();
            return _this;
        }
        Margin.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
        };
        Margin.prototype.getDomNode = function () {
            return this._domNode;
        };
        Margin.prototype._createDomNode = function () {
            var domNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
            domNode.setClassName('margin');
            domNode.setPosition('absolute');
            domNode.setAttribute('role', 'presentation');
            domNode.setAttribute('aria-hidden', 'true');
            this._glyphMarginBackgroundDomNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
            this._glyphMarginBackgroundDomNode.setClassName(Margin.CLASS_NAME);
            domNode.appendChild(this._glyphMarginBackgroundDomNode);
            return domNode;
        };
        // --- begin event handlers
        Margin.prototype.onConfigurationChanged = function (e) {
            if (e.canUseLayerHinting) {
                this._canUseLayerHinting = this._context.configuration.editor.canUseLayerHinting;
            }
            if (e.layoutInfo) {
                this._contentLeft = this._context.configuration.editor.layoutInfo.contentLeft;
                this._glyphMarginLeft = this._context.configuration.editor.layoutInfo.glyphMarginLeft;
                this._glyphMarginWidth = this._context.configuration.editor.layoutInfo.glyphMarginWidth;
            }
            return true;
        };
        Margin.prototype.onScrollChanged = function (e) {
            return _super.prototype.onScrollChanged.call(this, e) || e.scrollTopChanged;
        };
        // --- end event handlers
        Margin.prototype.prepareRender = function (ctx) {
            // Nothing to read
        };
        Margin.prototype.render = function (ctx) {
            this._domNode.setLayerHinting(this._canUseLayerHinting);
            var adjustedScrollTop = ctx.scrollTop - ctx.bigNumbersDelta;
            this._domNode.setTop(-adjustedScrollTop);
            var height = Math.min(ctx.scrollHeight, 1000000);
            this._domNode.setHeight(height);
            this._domNode.setWidth(this._contentLeft);
            this._glyphMarginBackgroundDomNode.setLeft(this._glyphMarginLeft);
            this._glyphMarginBackgroundDomNode.setWidth(this._glyphMarginWidth);
            this._glyphMarginBackgroundDomNode.setHeight(height);
        };
        Margin.CLASS_NAME = 'glyph-margin';
        return Margin;
    }(viewPart_1.ViewPart));
    exports.Margin = Margin;
});

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










define(__m[235/*vs/editor/browser/viewParts/marginDecorations/marginDecorations*/], __M([1/*require*/,0/*exports*/,113/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/,291/*vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations*/]), function (require, exports, glyphMargin_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MarginViewLineDecorationsOverlay = (function (_super) {
        __extends(MarginViewLineDecorationsOverlay, _super);
        function MarginViewLineDecorationsOverlay(context) {
            var _this = _super.call(this) || this;
            _this._context = context;
            _this._renderResult = null;
            _this._context.addEventHandler(_this);
            return _this;
        }
        MarginViewLineDecorationsOverlay.prototype.dispose = function () {
            this._context.removeEventHandler(this);
            this._context = null;
            this._renderResult = null;
            _super.prototype.dispose.call(this);
        };
        // --- begin event handlers
        MarginViewLineDecorationsOverlay.prototype.onConfigurationChanged = function (e) {
            return true;
        };
        MarginViewLineDecorationsOverlay.prototype.onDecorationsChanged = function (e) {
            return true;
        };
        MarginViewLineDecorationsOverlay.prototype.onFlushed = function (e) {
            return true;
        };
        MarginViewLineDecorationsOverlay.prototype.onLinesChanged = function (e) {
            return true;
        };
        MarginViewLineDecorationsOverlay.prototype.onLinesDeleted = function (e) {
            return true;
        };
        MarginViewLineDecorationsOverlay.prototype.onLinesInserted = function (e) {
            return true;
        };
        MarginViewLineDecorationsOverlay.prototype.onScrollChanged = function (e) {
            return e.scrollTopChanged;
        };
        MarginViewLineDecorationsOverlay.prototype.onZonesChanged = function (e) {
            return true;
        };
        // --- end event handlers
        MarginViewLineDecorationsOverlay.prototype._getDecorations = function (ctx) {
            var decorations = ctx.getDecorationsInViewport();
            var r = [];
            for (var i = 0, len = decorations.length; i < len; i++) {
                var d = decorations[i];
                var marginClassName = d.source.options.marginClassName;
                if (marginClassName) {
                    r.push(new glyphMargin_1.DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, marginClassName));
                }
            }
            return r;
        };
        MarginViewLineDecorationsOverlay.prototype.prepareRender = function (ctx) {
            var visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            var visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            var toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
            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 += '<div class="cmdr ' + classNames[i] + '" style=""></div>';
                }
                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[236/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([1/*require*/,0/*exports*/,27/*vs/base/browser/fastDomNode*/,25/*vs/editor/browser/editorBrowser*/,35/*vs/editor/browser/view/viewPart*/,296/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/]), function (require, exports, fastDomNode_1, editorBrowser_1, viewPart_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ViewOverlayWidgets = (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 = null;
        };
        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 === editorBrowser_1.OverlayWidgetPositionPreference.TOP_RIGHT_CORNER) {
                domNode.setTop(0);
                domNode.setRight((2 * this._verticalScrollbarWidth) + this._minimapWidth);
            }
            else if (widgetData.preference === editorBrowser_1.OverlayWidgetPositionPreference.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 === editorBrowser_1.OverlayWidgetPositionPreference.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;
});











define(__m[237/*vs/editor/browser/viewParts/viewZones/viewZones*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,27/*vs/base/browser/fastDomNode*/,35/*vs/editor/browser/view/viewPart*/,12/*vs/editor/common/core/position*/]), function (require, exports, errors_1, fastDomNode_1, viewPart_1, position_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ViewZones = (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) {
            return this._recomputeWhitespacesProps();
        };
        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)
                };
            }
            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)
            };
        };
        ViewZones.prototype.addZone = function (zone) {
            var props = this._computeWhitespaceProps(zone);
            var whitespaceId = this._context.viewLayout.addWhitespace(props.afterViewLineNumber, this._getZoneOrdinal(zone), props.heightInPx);
            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);
                // let 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 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._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;
});

define(__m[86/*vs/editor/common/viewModel/viewModel*/], __M([1/*require*/,0/*exports*/]), 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 Viewport = (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 = (function () {
        function MinimapLinesRenderingData(tabSize, data) {
            this.tabSize = tabSize;
            this.data = data;
        }
        return MinimapLinesRenderingData;
    }());
    exports.MinimapLinesRenderingData = MinimapLinesRenderingData;
    var ViewLineData = (function () {
        function ViewLineData(content, minColumn, maxColumn, tokens) {
            this.content = content;
            this.minColumn = minColumn;
            this.maxColumn = maxColumn;
            this.tokens = tokens;
        }
        return ViewLineData;
    }());
    exports.ViewLineData = ViewLineData;
    var ViewLineRenderingData = (function () {
        function ViewLineRenderingData(minColumn, maxColumn, content, mightContainRTL, mightContainNonBasicASCII, tokens, inlineDecorations, tabSize) {
            this.minColumn = minColumn;
            this.maxColumn = maxColumn;
            this.content = content;
            this.mightContainRTL = mightContainRTL;
            this.mightContainNonBasicASCII = mightContainNonBasicASCII;
            this.tokens = tokens;
            this.inlineDecorations = inlineDecorations;
            this.tabSize = tabSize;
        }
        return ViewLineRenderingData;
    }());
    exports.ViewLineRenderingData = ViewLineRenderingData;
    var InlineDecoration = (function () {
        function InlineDecoration(range, inlineClassName, insertsBeforeOrAfter) {
            this.range = range;
            this.inlineClassName = inlineClassName;
            this.insertsBeforeOrAfter = insertsBeforeOrAfter;
        }
        return InlineDecoration;
    }());
    exports.InlineDecoration = InlineDecoration;
    var ViewModelDecoration = (function () {
        function ViewModelDecoration(source) {
            this.range = null;
            this.source = source;
        }
        return ViewModelDecoration;
    }());
    exports.ViewModelDecoration = ViewModelDecoration;
    var ViewEventsCollector = (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 = null;
            return result;
        };
        return ViewEventsCollector;
    }());
    exports.ViewEventsCollector = ViewEventsCollector;
});











define(__m[239/*vs/editor/common/viewLayout/viewLayout*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,48/*vs/base/common/scrollable*/,223/*vs/editor/common/viewLayout/linesLayout*/,86/*vs/editor/common/viewModel/viewModel*/]), function (require, exports, lifecycle_1, scrollable_1, linesLayout_1, viewModel_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ViewLayout = (function (_super) {
        __extends(ViewLayout, _super);
        function ViewLayout(configuration, lineCount) {
            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());
            _this.scrollable.updateState({
                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.getScrollable = function () {
            return this.scrollable;
        };
        ViewLayout.prototype.onHeightMaybeChanged = function () {
            this._updateHeight();
        };
        // ---- begin view event handlers
        ViewLayout.prototype.onConfigurationChanged = function (e) {
            if (e.lineHeight) {
                this._linesLayout.setLineHeight(this._configuration.editor.lineHeight);
            }
            if (e.layoutInfo) {
                this.scrollable.updateState({
                    width: this._configuration.editor.layoutInfo.contentWidth,
                    height: this._configuration.editor.layoutInfo.contentHeight
                });
            }
            this._updateHeight();
        };
        ViewLayout.prototype.onFlushed = function (lineCount) {
            this._linesLayout.onFlushed(lineCount);
            this._updateHeight();
        };
        ViewLayout.prototype.onLinesDeleted = function (fromLineNumber, toLineNumber) {
            this._linesLayout.onLinesDeleted(fromLineNumber, toLineNumber);
            this._updateHeight();
        };
        ViewLayout.prototype.onLinesInserted = function (fromLineNumber, toLineNumber) {
            this._linesLayout.onLinesInserted(fromLineNumber, toLineNumber);
            this._updateHeight();
        };
        // ---- end view event handlers
        ViewLayout.prototype._getHorizontalScrollbarHeight = function (scrollState) {
            if (this._configuration.editor.viewInfo.scrollbar.horizontal === scrollable_1.ScrollbarVisibility.Hidden) {
                // horizontal scrollbar not visible
                return 0;
            }
            if (scrollState.width >= scrollState.scrollWidth) {
                // horizontal scrollbar not visible
                return 0;
            }
            return this._configuration.editor.viewInfo.scrollbar.horizontalScrollbarSize;
        };
        ViewLayout.prototype._getTotalHeight = function () {
            var scrollState = this.scrollable.getState();
            var result = this._linesLayout.getLinesTotalHeight();
            if (this._configuration.editor.viewInfo.scrollBeyondLastLine) {
                result += scrollState.height - this._configuration.editor.lineHeight;
            }
            else {
                result += this._getHorizontalScrollbarHeight(scrollState);
            }
            return Math.max(scrollState.height, result);
        };
        ViewLayout.prototype._updateHeight = function () {
            this.scrollable.updateState({
                scrollHeight: this._getTotalHeight()
            });
        };
        // ---- Layouting logic
        ViewLayout.prototype.getCurrentViewport = function () {
            var scrollState = this.scrollable.getState();
            return new viewModel_1.Viewport(scrollState.scrollTop, scrollState.scrollLeft, scrollState.width, scrollState.height);
        };
        ViewLayout.prototype._computeScrollWidth = function (maxLineWidth, viewportWidth) {
            var isViewportWrapping = this._configuration.editor.wrappingInfo.isViewportWrapping;
            if (!isViewportWrapping) {
                return Math.max(maxLineWidth + ViewLayout.LINES_HORIZONTAL_EXTRA_PX, viewportWidth);
            }
            return Math.max(maxLineWidth, viewportWidth);
        };
        ViewLayout.prototype.onMaxLineWidthChanged = function (maxLineWidth) {
            var newScrollWidth = this._computeScrollWidth(maxLineWidth, this.getCurrentViewport().width);
            this.scrollable.updateState({
                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 scrollState = this.scrollable.getState();
            var scrollTop = scrollState.scrollTop;
            var firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop);
            var whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport);
            return {
                scrollTop: scrollTop,
                scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine,
                scrollLeft: scrollState.scrollLeft
            };
        };
        ViewLayout.prototype.restoreState = function (state) {
            var restoreScrollTop = state.scrollTop;
            if (typeof state.scrollTopWithoutViewZones === 'number' && !this._linesLayout.hasWhitespace()) {
                restoreScrollTop = state.scrollTopWithoutViewZones;
            }
            this.scrollable.updateState({
                scrollLeft: state.scrollLeft,
                scrollTop: restoreScrollTop
            });
        };
        // ---- IVerticalLayoutProvider
        ViewLayout.prototype.addWhitespace = function (afterLineNumber, ordinal, height) {
            return this._linesLayout.insertWhitespace(afterLineNumber, ordinal, height);
        };
        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 scrollState = this.scrollable.getState();
            if (scrollTop + scrollState.height > scrollState.scrollHeight) {
                scrollTop = scrollState.scrollHeight - scrollState.height;
            }
            if (scrollTop < 0) {
                scrollTop = 0;
            }
            return this._linesLayout.getLinesViewportData(scrollTop, scrollTop + scrollState.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 scrollState = this.scrollable.getState();
            return scrollState.scrollWidth;
        };
        ViewLayout.prototype.getScrollLeft = function () {
            var scrollState = this.scrollable.getState();
            return scrollState.scrollLeft;
        };
        ViewLayout.prototype.getScrollHeight = function () {
            var scrollState = this.scrollable.getState();
            return scrollState.scrollHeight;
        };
        ViewLayout.prototype.getScrollTop = function () {
            var scrollState = this.scrollable.getState();
            return scrollState.scrollTop;
        };
        ViewLayout.prototype.setScrollPosition = function (position) {
            this.scrollable.updateState(position);
        };
        ViewLayout.LINES_HORIZONTAL_EXTRA_PX = 30;
        return ViewLayout;
    }(lifecycle_1.Disposable));
    exports.ViewLayout = ViewLayout;
});

define(__m[240/*vs/editor/common/viewModel/viewModelDecorations*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/,12/*vs/editor/common/core/position*/,86/*vs/editor/common/viewModel/viewModel*/]), function (require, exports, range_1, position_1, viewModel_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ViewModelDecorations = (function () {
        function ViewModelDecorations(editorId, model, configuration, coordinatesConverter) {
            this.editorId = editorId;
            this.model = model;
            this.configuration = configuration;
            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 = null;
            this._clearCachedModelDecorationsResolver();
        };
        ViewModelDecorations.prototype.reset = function () {
            this._decorationsCache = Object.create(null);
            this._clearCachedModelDecorationsResolver();
        };
        ViewModelDecorations.prototype.onModelDecorationsChanged = function (e) {
            var changedDecorations = e.changedDecorations;
            for (var i = 0, len = changedDecorations.length; i < len; i++) {
                var changedDecoration = changedDecorations[i];
                var myDecoration = this._decorationsCache[changedDecoration];
                if (!myDecoration) {
                    continue;
                }
                myDecoration.range = null;
            }
            var removedDecorations = e.removedDecorations;
            if (this._decorationsCache !== null && this._decorationsCache !== undefined) {
                for (var i = 0, len = removedDecorations.length; i < len; i++) {
                    var removedDecoration = removedDecorations[i];
                    delete this._decorationsCache[removedDecoration];
                }
            }
            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) {
                r = new viewModel_1.ViewModelDecoration(modelDecoration);
                this._decorationsCache[id] = r;
            }
            if (r.range === null) {
                var modelRange = modelDecoration.range;
                if (modelDecoration.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)));
                    r.range = new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column);
                }
                else {
                    r.range = this._coordinatesConverter.convertModelRangeToViewRange(modelRange);
                }
            }
            return r;
        };
        ViewModelDecorations.prototype.getAllOverviewRulerDecorations = function () {
            var modelDecorations = this.model.getAllDecorations(this.editorId, this.configuration.editor.readOnly);
            var result = [], resultLen = 0;
            for (var i = 0, len = modelDecorations.length; i < len; i++) {
                var modelDecoration = modelDecorations[i];
                var decorationOptions = modelDecoration.options;
                if (!decorationOptions.overviewRuler.color) {
                    continue;
                }
                var viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration);
                result[resultLen++] = viewModelDecoration;
            }
            return result;
        };
        ViewModelDecorations.prototype.getDecorationsViewportData = function (viewRange) {
            var cacheIsValid = true;
            cacheIsValid = 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 viewportModelRange = this._coordinatesConverter.convertViewRangeToModelRange(viewportRange);
            var startLineNumber = viewportRange.startLineNumber;
            var endLineNumber = viewportRange.endLineNumber;
            var modelDecorations = this.model.getDecorationsInRange(viewportModelRange, this.editorId, this.configuration.editor.readOnly);
            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, false);
                    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) {
                        // TODO: What happens if the startLineNumber and startColumn is at the end of a line?
                        var inlineDecoration = new viewModel_1.InlineDecoration(new range_1.Range(viewRange.startLineNumber, viewRange.startColumn, viewRange.startLineNumber, viewRange.startColumn + 1), decorationOptions.beforeContentClassName, true);
                        inlineDecorations[viewRange.startLineNumber - startLineNumber].push(inlineDecoration);
                    }
                }
                if (decorationOptions.afterContentClassName) {
                    if (startLineNumber <= viewRange.endLineNumber && viewRange.endLineNumber <= endLineNumber && viewRange.endColumn > 1) {
                        var inlineDecoration = new viewModel_1.InlineDecoration(new range_1.Range(viewRange.endLineNumber, viewRange.endColumn - 1, viewRange.endLineNumber, viewRange.endColumn), decorationOptions.afterContentClassName, true);
                        inlineDecorations[viewRange.endLineNumber - startLineNumber].push(inlineDecoration);
                    }
                }
            }
            return {
                decorations: decorationsInViewport,
                inlineDecorations: inlineDecorations
            };
        };
        return ViewModelDecorations;
    }());
    exports.ViewModelDecorations = ViewModelDecorations;
});

define(__m[241/*vs/editor/contrib/caretOperations/common/moveCaretCommand*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/]), function (require, exports, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MoveCaretCommand = (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[242/*vs/editor/contrib/colorPicker/browser/colorPickerModel*/], __M([1/*require*/,0/*exports*/,32/*vs/base/common/color*/,2/*vs/editor/common/core/range*/]), function (require, exports, color_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function isAdvancedFormatter(formatter) {
        return !!formatter.transparentFormatter;
    }
    exports.isAdvancedFormatter = isAdvancedFormatter;
    var ColorPickerModel = (function () {
        function ColorPickerModel(originalColor, color, opaqueFormatter, transparentFormatter, availableFormatters, editorModel, range) {
            this.editorModel = editorModel;
            this.colorFormatters = [];
            this._colorModelIndex = 0;
            this.originalColor = originalColor;
            this._opaqueFormatter = opaqueFormatter;
            this.colorFormatters = availableFormatters;
            this.color = color;
            this.hue = color.getHue();
            this.saturation = color.getSaturation();
            this.value = color.getValue();
            this._colorRange = new range_1.Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
        }
        Object.defineProperty(ColorPickerModel.prototype, "color", {
            get: function () {
                return this._color;
            },
            set: function (color) {
                this._color = color;
                var alpha = color.toRGBA().a;
                if (!this._opacity) {
                    this._opacity = alpha / 255;
                }
                this.saturation = color.getSaturation();
                this.value = color.getValue();
                if (this._opacity === 1) {
                    this.selectedColorString = this._opaqueFormatter.toString(this._color);
                }
                else if (this._transparentFormatter) {
                    this.selectedColorString = this._transparentFormatter.toString(this._color);
                }
                else {
                    this.nextColorMode();
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorPickerModel.prototype, "selectedColorString", {
            get: function () {
                return this._selectedColor;
            },
            set: function (colorString) {
                if (this._selectedColor === colorString) {
                    return;
                }
                this._selectedColor = colorString;
                if (this.widget && this.widget.header && this.widget.body) {
                    this.widget.header.updatePickedColor();
                    this.widget.body.fillOpacityOverlay(this._color);
                    this.editorModel.pushEditOperations([], [{
                            identifier: null,
                            range: this._colorRange,
                            text: colorString,
                            forceMoveMarkers: false
                        }], function () { return []; });
                    this._colorRange = this._colorRange.setEndPosition(this._colorRange.endLineNumber, this._colorRange.startColumn + colorString.length);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorPickerModel.prototype, "hue", {
            get: function () {
                return this._hue;
            },
            set: function (hue) {
                this._hue = hue;
                if (this.widget && this.widget.body) {
                    this.widget.body.saturationBox.fillSaturationBox();
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorPickerModel.prototype, "opacity", {
            get: function () {
                return this._opacity;
            },
            set: function (opacity) {
                this._opacity = opacity;
                var rgba = this._color.toRGBA();
                this.color = color_1.Color.fromRGBA(new color_1.RGBA(rgba.r, rgba.g, rgba.b, opacity * 255));
                if (this.widget.header) {
                    this.widget.header.updatePickedColor();
                }
            },
            enumerable: true,
            configurable: true
        });
        ColorPickerModel.prototype.nextColorMode = function () {
            this._colorModelIndex++;
            if (this._colorModelIndex === this.colorFormatters.length) {
                this._colorModelIndex = 0;
            }
            var formatter = this.colorFormatters[this._colorModelIndex];
            if (isAdvancedFormatter(formatter)) {
                this._transparentFormatter = formatter.transparentFormatter;
                this._opaqueFormatter = formatter.opaqueFormatter;
                this.selectedColorString = this._opacity === 1 ? this._opaqueFormatter.toString(this._color) : this._transparentFormatter.toString(this._color);
            }
            else if (!this._transparentFormatter || this._opacity === 1) {
                this._transparentFormatter = null;
                this._opaqueFormatter = formatter;
                this.selectedColorString = this._opaqueFormatter.toString(this._color);
            }
            else {
                this.nextColorMode();
            }
        };
        ColorPickerModel.prototype.getHueColor = function (hue) {
            var hh = hue / 60;
            var X = 1 - Math.abs(hh % 2 - 1);
            var r = 0, g = 0, b = 0;
            if (hh >= 0 && hh < 1) {
                r = 1;
                g = X;
            }
            else if (hh >= 1 && hh < 2) {
                r = X;
                g = 1;
            }
            else if (hh >= 2 && hh < 3) {
                g = 1;
                b = X;
            }
            else if (hh >= 3 && hh < 4) {
                g = X;
                b = 1;
            }
            else if (hh >= 4 && hh < 5) {
                r = X;
                b = 1;
            }
            else {
                r = 1;
                b = X;
            }
            r = Math.round(r * 255);
            g = Math.round(g * 255);
            b = Math.round(b * 255);
            return color_1.Color.fromRGBA(new color_1.RGBA(r, g, b));
        };
        return ColorPickerModel;
    }());
    exports.ColorPickerModel = ColorPickerModel;
    var ISaturationState = (function () {
        function ISaturationState() {
        }
        return ISaturationState;
    }());
    exports.ISaturationState = ISaturationState;
});

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










define(__m[243/*vs/editor/contrib/colorPicker/browser/elements/colorPickerBody*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,3/*vs/base/common/lifecycle*/,83/*vs/base/browser/globalMouseMoveMonitor*/,15/*vs/base/common/platform*/,32/*vs/base/common/color*/]), function (require, exports, dom, lifecycle_1, globalMouseMoveMonitor_1, platform_1, color_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var $ = dom.$;
    var MOUSE_DRAG_RESET_DISTANCE = 140;
    var ColorPickerBody = (function (_super) {
        __extends(ColorPickerBody, _super);
        function ColorPickerBody(widget, model) {
            var _this = _super.call(this) || this;
            _this.widget = widget;
            _this.model = model;
            _this.pixelRatio = _this.widget.editor.getConfiguration().pixelRatio;
            _this.domNode = $('.colorpicker-body');
            dom.append(widget.getDomNode(), _this.domNode);
            _this.drawSaturationBox();
            _this.drawOpacityStrip();
            _this.drawHueStrip();
            _this.registerListeners();
            return _this;
        }
        ColorPickerBody.prototype.fillOpacityOverlay = function (color) {
            var c = color.toRGBA();
            var r = c.r;
            var g = c.g;
            var b = c.b;
            this.opacityOverlay.style.background = "linear-gradient(to bottom, rgba(" + r + ", " + g + ", " + b + ", 1) 0%, rgba(" + r + ", " + g + ", " + b + ", 0) 100%)";
        };
        ColorPickerBody.prototype.registerListeners = function () {
            var _this = this;
            var monitor = this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor());
            // Saturation box listener
            this._register(dom.addDisposableListener(this.saturationBox.domNode, dom.EventType.MOUSE_DOWN, function (e) {
                _this.saturationListener(e, monitor);
            }));
            // Hue and opacity strips listener
            this._register(dom.addDisposableListener(this.hueStrip, dom.EventType.MOUSE_DOWN, function (e) {
                _this.stripListener(_this.hueStrip, e, monitor);
            }));
            this._register(dom.addDisposableListener(this.opacityStrip, dom.EventType.MOUSE_DOWN, function (e) {
                _this.stripListener(_this.opacityStrip, e, monitor);
            }));
        };
        ColorPickerBody.prototype.saturationListener = function (e, monitor) {
            var _this = this;
            if (e.button !== 0) {
                return;
            }
            var updateModel = function (x, y) {
                var saturationRGBA = _this.saturationBox.extractColor(x, y).toRGBA();
                _this.widget.model.color = color_1.Color.fromRGBA(new color_1.RGBA(saturationRGBA.r, saturationRGBA.g, saturationRGBA.b, _this.widget.model.opacity * 255)); // TODO@Michel store opacity in [0-255] instead
                _this.saturationBox.focusSaturationSelection({ x: x, y: y });
            };
            var newSaturationX, newSaturationY;
            if (e.target !== this.saturationBox.saturationSelection) {
                newSaturationX = e.offsetX;
                newSaturationY = e.offsetY;
                updateModel(newSaturationX, newSaturationY);
            }
            else {
                newSaturationX = this.widget.model.saturationSelection.x;
                newSaturationY = this.widget.model.saturationSelection.y;
            }
            var initialMousePosition = e.clientY;
            var initialMouseOrthogonalPosition = e.clientX;
            monitor.startMonitoring(globalMouseMoveMonitor_1.standardMouseMoveMerger, function (mouseMoveData) {
                var deltaX = mouseMoveData.posx - initialMouseOrthogonalPosition;
                var deltaY = mouseMoveData.posy - initialMousePosition;
                var x = newSaturationX + deltaX;
                var y = newSaturationY + deltaY;
                updateModel(x, y);
            }, function () { return null; });
        };
        ColorPickerBody.prototype.stripListener = function (element, e, monitor) {
            var _this = this;
            if (e.button !== 0) {
                return;
            }
            var slider = element === this.hueStrip ? this.hueSlider : this.opacitySlider;
            var strip = element === this.hueStrip ? this.hueStrip : this.opacityStrip;
            // Update slider position if clicked on a strip itself
            if (e.target === this.hueStrip || e.target === this.opacityStrip) {
                slider.top = e.offsetY;
            }
            var updateModel = function () {
                if (slider === _this.hueSlider) {
                    _this.widget.model.hue = _this.calculateSliderHue(slider);
                }
                else if (slider === _this.opacitySlider) {
                    _this.widget.model.opacity = _this.calculateOpacity(slider);
                }
            };
            updateModel();
            var initialMousePosition = e.clientY;
            var initialMouseOrthogonalPosition = e.clientX;
            var initialSliderTop = slider.top;
            monitor.startMonitoring(globalMouseMoveMonitor_1.standardMouseMoveMerger, function (mouseMoveData) {
                strip.style.cursor = '-webkit-grabbing';
                // Do not move slider on Windows if it's outside of movable bounds
                var mouseOrthogonalDelta = Math.abs(mouseMoveData.posx - initialMouseOrthogonalPosition);
                if (platform_1.isWindows && mouseOrthogonalDelta > MOUSE_DRAG_RESET_DISTANCE) {
                    slider.top = 0;
                    if (slider === _this.hueSlider) {
                        _this.widget.model.hue = 0;
                    }
                    else if (slider === _this.opacitySlider) {
                        _this.widget.model.opacity = 1;
                    }
                    return;
                }
                var mouseDelta = mouseMoveData.posy - initialMousePosition;
                slider.top = initialSliderTop + mouseDelta;
                updateModel();
            }, function () {
                strip.style.cursor = '-webkit-grab';
            });
        };
        ColorPickerBody.prototype.drawSaturationBox = function () {
            this.saturationBox = new SaturationBox(this.model, this.domNode, this.pixelRatio);
        };
        ColorPickerBody.prototype.drawOpacityStrip = function () {
            this.opacityStrip = $('.strip.opacity-strip');
            dom.append(this.domNode, this.opacityStrip);
            this.opacityOverlay = $('.opacity-overlay');
            this.fillOpacityOverlay(this.model.color);
            dom.append(this.opacityStrip, this.opacityOverlay);
            this.opacitySlider = new Slider(this.opacityStrip);
            this.opacitySlider.top = this.model.opacity === 1 ? 0 : this.opacityStrip.offsetHeight * (1 - this.model.opacity);
            dom.append(this.opacityStrip, this.opacitySlider.domNode);
        };
        ColorPickerBody.prototype.drawHueStrip = function () {
            this.hueStrip = $('.strip.hue-strip');
            dom.append(this.domNode, this.hueStrip);
            this.hueSlider = new Slider(this.hueStrip);
            dom.append(this.hueStrip, this.hueSlider.domNode);
            this.hueSlider.top = (this.hueStrip.offsetHeight - this.hueSlider.domNode.offsetHeight) * (this.model.color.getHue() / 359);
        };
        ColorPickerBody.prototype.calculateSliderHue = function (slider) {
            var hueNormalizedHeight = this.hueStrip.offsetHeight - slider.domNode.offsetHeight;
            return (1 - ((hueNormalizedHeight - slider.top) / hueNormalizedHeight)) * 359;
        };
        ColorPickerBody.prototype.calculateOpacity = function (slider) {
            var opacityNormalizedHeight = this.opacityStrip.offsetHeight - slider.domNode.offsetHeight;
            return (opacityNormalizedHeight - slider.top) / opacityNormalizedHeight;
        };
        return ColorPickerBody;
    }(lifecycle_1.Disposable));
    exports.ColorPickerBody = ColorPickerBody;
    var SaturationBox = (function () {
        function SaturationBox(model, widgetNode, pixelRatio) {
            this.model = model;
            this.pixelRatio = pixelRatio;
            this.domNode = $('.saturation-wrap');
            dom.append(widgetNode, this.domNode);
            // Create canvas, draw selected color
            this.saturationCanvas = document.createElement('canvas');
            this.saturationCanvas.className = 'saturation-box';
            dom.append(this.domNode, this.saturationCanvas);
            // Add selection circle
            this.saturationSelection = $('.saturation-selection');
            dom.append(this.domNode, this.saturationSelection);
        }
        SaturationBox.prototype.layout = function () {
            var actualW = this.domNode.offsetWidth * this.pixelRatio, actualH = this.domNode.offsetHeight * this.pixelRatio;
            this.saturationCanvas.width = actualW;
            this.saturationCanvas.height = actualH;
            this.saturationCtx = this.saturationCanvas.getContext('2d');
            this.saturationCtx.rect(0, 0, actualW, actualH);
            // Create black and white gradients on top
            var ctx2 = document.createElement('canvas').getContext('2d');
            this.whiteGradient = ctx2.createLinearGradient(0, 0, actualW, 0);
            this.whiteGradient.addColorStop(0, 'rgba(255, 255, 255, 1)');
            this.whiteGradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
            this.blackGradient = ctx2.createLinearGradient(0, 0, 0, actualH);
            this.blackGradient.addColorStop(0, 'rgba(0, 0, 0, 0)');
            this.blackGradient.addColorStop(1, 'rgba(0, 0, 0, 1)');
            this.fillSaturationBox();
            var saturation = this.model.saturation * this.saturationCanvas.clientWidth;
            var selectionHeight = this.model.value * this.saturationCanvas.clientHeight;
            var value = selectionHeight === 0 ? this.saturationCanvas.clientHeight : this.saturationCanvas.clientHeight - selectionHeight;
            this.focusSaturationSelection({ x: saturation, y: value });
        };
        SaturationBox.prototype.fillSaturationBox = function () {
            this.saturationCtx.fillStyle = this.calculateHueColor(this.model.hue).toString();
            this.saturationCtx.fill();
            this.saturationCtx.fillStyle = this.whiteGradient;
            this.saturationCtx.fill();
            this.saturationCtx.fillStyle = this.blackGradient;
            this.saturationCtx.fill();
            // Update selected color if saturation selection was beforehand
            if (this.model.saturationSelection) {
                var newColor = color_1.Color.fromHSV(this.model.hue, this.model.saturation, this.model.value, this.model.opacity * 255);
                this.model.color = newColor;
            }
        };
        SaturationBox.prototype.focusSaturationSelection = function (state) {
            var x = state.x, y = state.y;
            if (x < 0) {
                x = 0;
            }
            else if (x > this.domNode.offsetWidth) {
                x = this.domNode.offsetWidth;
            }
            if (y < 0) {
                y = 0;
            }
            else if (y > this.domNode.offsetHeight) {
                y = this.domNode.offsetHeight;
            }
            this.saturationSelection.style.left = x + 'px';
            this.saturationSelection.style.top = y + 'px';
            this.model.saturationSelection = { x: x, y: y };
        };
        SaturationBox.prototype.extractColor = function (offsetX, offsetY) {
            var opacityX = 1 - (offsetX / this.domNode.offsetWidth);
            var opacityY = offsetY / this.domNode.offsetHeight;
            var whiteGradientColor = color_1.Color.fromRGBA(new color_1.RGBA(255, 255, 255, opacityX * 255));
            var blackGradientColor = color_1.Color.fromRGBA(new color_1.RGBA(0, 0, 0, opacityY * 255));
            var gradientsMix = blackGradientColor.blend(whiteGradientColor);
            return gradientsMix.blend(this.calculateHueColor(this.model.hue));
        };
        SaturationBox.prototype.calculateHueColor = function (hue) {
            var hh = hue / 60;
            var X = 1 - Math.abs(hh % 2 - 1);
            var r = 0, g = 0, b = 0;
            if (hh >= 0 && hh < 1) {
                r = 1;
                g = X;
            }
            else if (hh >= 1 && hh < 2) {
                r = X;
                g = 1;
            }
            else if (hh >= 2 && hh < 3) {
                g = 1;
                b = X;
            }
            else if (hh >= 3 && hh < 4) {
                g = X;
                b = 1;
            }
            else if (hh >= 4 && hh < 5) {
                r = X;
                b = 1;
            }
            else {
                r = 1;
                b = X;
            }
            r = Math.round(r * 255);
            g = Math.round(g * 255);
            b = Math.round(b * 255);
            return color_1.Color.fromRGBA(new color_1.RGBA(r, g, b));
        };
        return SaturationBox;
    }());
    exports.SaturationBox = SaturationBox;
    var Slider = (function () {
        function Slider(strip) {
            this.strip = strip;
            this.domNode = $('.slider');
            this._top = 0;
        }
        Object.defineProperty(Slider.prototype, "top", {
            get: function () {
                return this._top;
            },
            // Sets style.top in 'px'
            set: function (top) {
                if (top < 0) {
                    top = 0;
                }
                else if (top > this.strip.offsetHeight - this.domNode.offsetHeight) {
                    top = this.strip.offsetHeight - this.domNode.offsetHeight;
                }
                this.domNode.style.top = top + 'px';
                this._top = top;
            },
            enumerable: true,
            configurable: true
        });
        return Slider;
    }());
});

/*---------------------------------------------------------------------------------------------
 *  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/browser/elements/colorPickerHeader*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,3/*vs/base/common/lifecycle*/]), function (require, exports, dom, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var $ = dom.$;
    var ColorPickerHeader = (function (_super) {
        __extends(ColorPickerHeader, _super);
        function ColorPickerHeader(widget, model) {
            var _this = _super.call(this) || this;
            _this.widget = widget;
            _this.model = model;
            _this.domNode = $('.colorpicker-header');
            dom.append(widget.getDomNode(), _this.domNode);
            _this.drawPickedColorBox();
            _this.drawOriginalColorBox();
            dom.addDisposableListener(_this.pickedColorNode, dom.EventType.CLICK, function () {
                if (_this.model.colorFormatters.length === 0) {
                    return;
                }
                _this.model.nextColorMode();
            });
            return _this;
        }
        ColorPickerHeader.prototype.updatePickedColor = function () {
            this.pickedColorNode.textContent = this.model.selectedColorString;
            this.pickedColorNode.style.backgroundColor = this.model.color.toString();
        };
        ColorPickerHeader.prototype.drawPickedColorBox = function () {
            this.pickedColorNode = $('.picked-color');
            this.pickedColorNode.style.backgroundColor = this.model.color.toString();
            this.pickedColorNode.textContent = this.model.selectedColorString;
            dom.append(this.domNode, this.pickedColorNode);
        };
        ColorPickerHeader.prototype.drawOriginalColorBox = function () {
            var colorBox = $('.original-color');
            colorBox.style.backgroundColor = this.model.originalColor;
            dom.append(this.domNode, colorBox);
        };
        return ColorPickerHeader;
    }(lifecycle_1.Disposable));
    exports.ColorPickerHeader = ColorPickerHeader;
});

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










define(__m[245/*vs/editor/contrib/colorPicker/browser/colorPickerWidget*/], __M([1/*require*/,0/*exports*/,41/*vs/base/browser/ui/widget*/,4/*vs/base/browser/dom*/,28/*vs/base/browser/browser*/,244/*vs/editor/contrib/colorPicker/browser/elements/colorPickerHeader*/,243/*vs/editor/contrib/colorPicker/browser/elements/colorPickerBody*/,316/*vs/css!vs/editor/contrib/colorPicker/browser/colorPicker*/]), function (require, exports, widget_1, dom, browser_1, colorPickerHeader_1, colorPickerBody_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var $ = dom.$;
    var ColorPickerWidget = (function (_super) {
        __extends(ColorPickerWidget, _super);
        function ColorPickerWidget(model, editor) {
            var _this = _super.call(this) || this;
            _this.model = model;
            _this.editor = editor;
            _this.visible = false;
            _this._register(browser_1.onDidChangeZoomLevel(function () { return _this.layout(); }));
            _this.domNode = $('.editor-widget.colorpicker-widget');
            return _this;
        }
        ColorPickerWidget.prototype.layout = function () {
            if (this.visible) {
                return;
            }
            this.header = new colorPickerHeader_1.ColorPickerHeader(this, this.model);
            this.body = new colorPickerBody_1.ColorPickerBody(this, this.model);
            this.visible = true;
        };
        ColorPickerWidget.prototype.layoutSaturationBox = function () {
            this.body.saturationBox.layout();
        };
        ColorPickerWidget.prototype.dispose = function () {
            this.visible = false;
            this.domNode = null;
            _super.prototype.dispose.call(this);
        };
        ColorPickerWidget.prototype.getId = function () {
            return ColorPickerWidget.ID;
        };
        ColorPickerWidget.prototype.getDomNode = function () {
            return this.domNode;
        };
        ColorPickerWidget.ID = 'editor.contrib.colorPickerWidget';
        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[246/*vs/editor/contrib/colorPicker/common/color*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function isColorDecorationOptions(options) {
        return !!(options && options.color);
    }
    exports.isColorDecorationOptions = isColorDecorationOptions;
});

/*---------------------------------------------------------------------------------------------
 *  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/colorPicker/common/colorFormatter*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function createLiteralNode(value) {
        return function () { return value; };
    }
    var RGBA_ENDRANGE = 255;
    var HSL_HUERANGE = 360;
    var HSL_ENDRANGE = 1;
    function normalize(value, start, end, currentEndRange) {
        var val = value;
        if (start || end) {
            // More safety checks
            // if (!start) {
            // 	throw new Error('Color format range defined is not correct. There is no range start.');
            // }
            // if (!end) {
            // 	throw new Error('Color format range defined is not correct. There is no range end.');
            // }
            if (start > end) {
                throw new Error('Color format range defined is not correct. Range start is bigger than end.');
            }
            if (start === end) {
                throw new Error('Color format range defined is not correct. Range start is the same as end.');
            }
            var ratio = val / currentEndRange;
            val = ratio * (end - start) + start;
        }
        return val;
    }
    ;
    function createPropertyNode(variable, fractionDigits, type, min, max) {
        return function (color) {
            var absoluteValue;
            switch (variable) {
                case 'red':
                    absoluteValue = normalize(color.toRGBA().r, min, max, RGBA_ENDRANGE);
                    break;
                case 'green':
                    absoluteValue = normalize(color.toRGBA().g, min, max, RGBA_ENDRANGE);
                    break;
                case 'blue':
                    absoluteValue = normalize(color.toRGBA().b, min, max, RGBA_ENDRANGE);
                    break;
                case 'alpha':
                    absoluteValue = normalize(color.toRGBA().a, min, max, RGBA_ENDRANGE);
                    break;
                case 'hue':
                    absoluteValue = normalize(color.toHSLA().h, min, max, HSL_HUERANGE);
                    break;
                case 'saturation':
                    absoluteValue = normalize(color.toHSLA().s, min, max, HSL_ENDRANGE);
                    break;
                case 'luminosity':
                    absoluteValue = normalize(color.toHSLA().l, min, max, HSL_ENDRANGE);
                    break;
            }
            if (absoluteValue === undefined) {
                throw new Error(variable + " is not supported as a color format.");
            }
            var value;
            if (type === 'f') {
                fractionDigits = fractionDigits ? fractionDigits : 2; // 2 is default
                value = absoluteValue.toFixed(fractionDigits);
            }
            else if (type === 'x' || type === 'X') {
                value = normalize(absoluteValue, min, max, RGBA_ENDRANGE).toString(16);
                if (value.length !== 2) {
                    value = '0' + value;
                }
                if (type === 'X') {
                    value = value.toUpperCase();
                }
            }
            else {
                value = absoluteValue.toFixed(0);
            }
            return value.toString();
        };
    }
    var ColorFormatter = (function () {
        function ColorFormatter(format) {
            /*
                Variables
                - red
                - green
                - blue
                - hue
                - saturation
                - luminosity
                - alpha
        
                Number formats
                - decimal - d
                - float - f
                - hex - x X
        
                Number ranges
                - 0-1
                - 0-255
                - 0-100
                - arbitrary
        
                Examples
                "{red}" - 123
                "{red:d}" - 123
                "{red:x}" - af
                "{red:X}" - AF
                "{red:d[0-255]}" - AF
                "{red:x[0-255]}" - AF
                "{red:X[0-1024]}" - FEFE
                "{red:2f}" - 123.51
                "{red:1f}" - 123.5
                "{red:2f[0-1]}" - 1.23
        
                - default format: decimal
                - default range: 0-255
            */
            this.tree = [];
            this.parse(format);
        }
        ColorFormatter.prototype.parse = function (format) {
            var match = ColorFormatter.PATTERN.exec(format);
            var startIndex = 0;
            // if no match -> erroor	throw new Error(`${format} is not consistent with color format syntax.`);
            while (match !== null) {
                var index = match.index;
                if (startIndex < index) {
                    this.tree.push(createLiteralNode(format.substring(startIndex, index)));
                }
                // add more parser catches
                var variable = match[1];
                if (!variable) {
                    throw new Error(variable + " is not defined.");
                }
                var decimals = parseInt(match[2]);
                var type = match[3];
                var startRange = parseInt(match[4]);
                var endRange = parseInt(match[5]);
                this.tree.push(createPropertyNode(variable, decimals, type, startRange, endRange));
                startIndex = index + match[0].length;
                match = ColorFormatter.PATTERN.exec(format);
            }
            this.tree.push(createLiteralNode(format.substring(startIndex, format.length)));
        };
        ColorFormatter.prototype.toString = function (color) {
            var colorString = [];
            this.tree.forEach(function (node) {
                colorString.push(node(color));
            });
            return colorString.join('');
        };
        // Group 0: variable
        // Group 1: decimal digits
        // Group 2: floating/integer/hex
        // Group 3: range begin
        // Group 4: range end
        ColorFormatter.PATTERN = /{(\w+)(?::(\d*)(\w)+(?:\[(\d+)-(\d+)\])?)?}/g;
        return ColorFormatter;
    }());
    exports.ColorFormatter = ColorFormatter;
});

/*---------------------------------------------------------------------------------------------
 *  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/colorPicker/common/colorPicker*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,17/*vs/editor/common/modes*/,18/*vs/base/common/async*/,10/*vs/base/common/errors*/]), function (require, exports, winjs_base_1, modes_1, async_1, errors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function getColors(model) {
        var colorInfo = [];
        // ask all providers for colors in parallel
        var promises = modes_1.ColorProviderRegistry.ordered(model).reverse().map(function (provider) {
            return async_1.asWinJsPromise(function (token) { return provider.provideColorRanges(model, token); }).then(function (result) {
                if (Array.isArray(result)) {
                    colorInfo = colorInfo.concat(result);
                }
            }, errors_1.onUnexpectedExternalError);
        });
        return winjs_base_1.TPromise.join(promises).then(function () {
            return colorInfo;
        });
    }
    exports.getColors = getColors;
});

define(__m[189/*vs/editor/contrib/comment/common/blockCommentCommand*/], __M([1/*require*/,0/*exports*/,59/*vs/editor/common/core/editOperation*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, editOperation_1, position_1, range_1, selection_1, languageConfigurationRegistry_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var BlockCommentCommand = (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++) {
                if (haystack.charCodeAt(offset + i) !== needle.charCodeAt(i)) {
                    return false;
                }
            }
            return true;
        };
        BlockCommentCommand.prototype._createOperationsForBlockComment = function (selection, config, model, builder) {
            var startLineNumber = selection.startLineNumber;
            var startColumn = selection.startColumn;
            var endLineNumber = selection.endLineNumber;
            var endColumn = selection.endColumn;
            var startToken = config.blockCommentStartToken;
            var endToken = config.blockCommentEndToken;
            var startTokenIndex = model.getLineContent(startLineNumber).lastIndexOf(startToken, startColumn - 1 + startToken.length);
            var endTokenIndex = model.getLineContent(endLineNumber).indexOf(endToken, endColumn - 1 - endToken.length);
            var ops;
            if (startTokenIndex !== -1 && endTokenIndex !== -1) {
                // We have to adjust to possible inner white space
                // For Space after startToken, add Space to startToken - range math will work out
                if (model.getLineContent(startLineNumber).charCodeAt(startTokenIndex + startToken.length) === 32 /* Space */) {
                    startToken += ' ';
                }
                // For Space before endToken, add Space before endToken and shift index one left
                if (model.getLineContent(endLineNumber).charCodeAt(endTokenIndex - 1) === 32 /* Space */) {
                    endToken = ' ' + endToken;
                    endTokenIndex -= 1;
                }
                ops = BlockCommentCommand._createRemoveBlockCommentOperations(new range_1.Range(startLineNumber, startTokenIndex + 1 + startToken.length, endLineNumber, endTokenIndex + 1), startToken, endToken);
            }
            else {
                ops = BlockCommentCommand._createAddBlockCommentOperations(selection, startToken, endToken);
                this._usedEndToken = ops.length === 1 ? endToken : null;
            }
            for (var i = 0; i < ops.length; i++) {
                builder.addTrackedEditOperation(ops[i].range, ops[i].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;
            var endLineNumber = this._selection.endLineNumber;
            var endColumn = this._selection.endColumn;
            model.forceTokenization(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(new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn), config, 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;
});

define(__m[250/*vs/editor/contrib/comment/common/lineCommentCommand*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,59/*vs/editor/common/core/editOperation*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,189/*vs/editor/contrib/comment/common/blockCommentCommand*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, strings, editOperation_1, position_1, range_1, selection_1, blockCommentCommand_1, languageConfigurationRegistry_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var Type;
    (function (Type) {
        Type[Type["Toggle"] = 0] = "Toggle";
        Type[Type["ForceAdd"] = 1] = "ForceAdd";
        Type[Type["ForceRemove"] = 2] = "ForceRemove";
    })(Type = exports.Type || (exports.Type = {}));
    var LineCommentCommand = (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.forceTokenization(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 lineData, lineContentStartOffset, commentStrEndOffset, i, lineCount, lineNumber, shouldRemoveComments, lineContent, onlyWhitespaceLines = true;
            if (type === 0 /* Toggle */) {
                shouldRemoveComments = true;
            }
            else if (type === 1 /* ForceAdd */) {
                shouldRemoveComments = false;
            }
            else {
                shouldRemoveComments = true;
            }
            for (i = 0, lineCount = lines.length; i < lineCount; i++) {
                lineData = lines[i];
                lineNumber = startLineNumber + i;
                lineContent = model.getLineContent(lineNumber);
                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) {
                    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 (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,
                    shouldRemoveComments: false,
                    lines: null
                };
            }
            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)) {
                    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.forceTokenization(s.startLineNumber);
            var languageId = model.getLanguageIdAtPosition(s.startLineNumber, s.startColumn);
            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; i < ops.length; i++) {
                builder.addEditOperation(ops[i].range, ops[i].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.startLineNumber, result.startColumn + this._deltaColumn, result.endLineNumber, result.endColumn + this._deltaColumn);
        };
        /**
         * Generate edit operations in the remove line comment case
         */
        LineCommentCommand._createRemoveLineCommentsOperations = function (lines, startLineNumber) {
            var i, len, lineData, res = [];
            for (i = 0, len = lines.length; i < len; i++) {
                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 i, len, lineData, res = [];
            for (i = 0, len = lines.length; i < len; i++) {
                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, i, len, lineContent, j, lenJ, currentVisibleColumn;
            for (i = 0, len = lines.length; i < len; i++) {
                if (lines[i].ignore) {
                    continue;
                }
                lineContent = model.getLineContent(startLineNumber + i);
                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) {
                    minVisibleColumn = currentVisibleColumn;
                }
            }
            minVisibleColumn = Math.floor(minVisibleColumn / tabSize) * tabSize;
            for (i = 0, len = lines.length; i < len; i++) {
                if (lines[i].ignore) {
                    continue;
                }
                lineContent = model.getLineContent(startLineNumber + i);
                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;
});

define(__m[251/*vs/editor/contrib/dnd/common/dragAndDropCommand*/], __M([1/*require*/,0/*exports*/,22/*vs/editor/common/core/selection*/,2/*vs/editor/common/core/range*/]), function (require, exports, selection_1, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var DragAndDropCommand = (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;
});

define(__m[252/*vs/editor/contrib/find/common/find*/], __M([1/*require*/,0/*exports*/]), 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 });
    function getSelectionSearchString(editor) {
        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 {
                return editor.getModel().getValueInRange(selection);
            }
        }
        return null;
    }
    exports.getSelectionSearchString = getSelectionSearchString;
});

define(__m[253/*vs/editor/contrib/find/common/findState*/], __M([1/*require*/,0/*exports*/,38/*vs/base/common/eventEmitter*/,2/*vs/editor/common/core/range*/]), function (require, exports, eventEmitter_1, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var FindReplaceState = (function () {
        function FindReplaceState() {
            this._searchString = '';
            this._replaceString = '';
            this._isRevealed = false;
            this._isReplaceRevealed = false;
            this._isRegex = false;
            this._wholeWord = false;
            this._matchCase = false;
            this._searchScope = null;
            this._matchesPosition = 0;
            this._matchesCount = 0;
            this._currentMatch = null;
            this._eventEmitter = new eventEmitter_1.EventEmitter();
        }
        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 this._isRegex; },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FindReplaceState.prototype, "wholeWord", {
            get: function () { return this._wholeWord; },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FindReplaceState.prototype, "matchCase", {
            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
        });
        FindReplaceState.prototype.dispose = function () {
            this._eventEmitter.dispose();
        };
        FindReplaceState.prototype.addChangeListener = function (listener) {
            return this._eventEmitter.addListener(FindReplaceState._CHANGED_EVENT, listener);
        };
        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._eventEmitter.emit(FindReplaceState._CHANGED_EVENT, 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;
            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') {
                if (this._isRegex !== newState.isRegex) {
                    this._isRegex = newState.isRegex;
                    changeEvent.isRegex = true;
                    somethingChanged = true;
                }
            }
            if (typeof newState.wholeWord !== 'undefined') {
                if (this._wholeWord !== newState.wholeWord) {
                    this._wholeWord = newState.wholeWord;
                    changeEvent.wholeWord = true;
                    somethingChanged = true;
                }
            }
            if (typeof newState.matchCase !== 'undefined') {
                if (this._matchCase !== newState.matchCase) {
                    this._matchCase = newState.matchCase;
                    changeEvent.matchCase = true;
                    somethingChanged = true;
                }
            }
            if (typeof newState.searchScope !== 'undefined') {
                if (!range_1.Range.equalsRange(this._searchScope, newState.searchScope)) {
                    this._searchScope = newState.searchScope;
                    changeEvent.searchScope = true;
                    somethingChanged = true;
                }
            }
            if (somethingChanged) {
                this._eventEmitter.emit(FindReplaceState._CHANGED_EVENT, changeEvent);
            }
        };
        FindReplaceState._CHANGED_EVENT = 'changed';
        return FindReplaceState;
    }());
    exports.FindReplaceState = FindReplaceState;
});

define(__m[254/*vs/editor/contrib/find/common/replaceAllCommand*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/]), function (require, exports, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ReplaceAllCommand = (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; i < resultOps.length; i++) {
                    builder.addEditOperation(resultOps[i].range, resultOps[i].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[255/*vs/editor/contrib/find/common/replacePattern*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var ReplacePattern = (function () {
        function ReplacePattern(pieces) {
            if (!pieces || pieces.length === 0) {
                this._staticValue = '';
                this._pieces = null;
            }
            else if (pieces.length === 1 && pieces[0].staticValue !== null) {
                this._staticValue = pieces[0].staticValue;
                this._pieces = null;
            }
            else {
                this._staticValue = null;
                this._pieces = pieces;
            }
        }
        ReplacePattern.fromStaticValue = function (value) {
            return new ReplacePattern([ReplacePiece.staticValue(value)]);
        };
        Object.defineProperty(ReplacePattern.prototype, "hasReplacementPatterns", {
            get: function () {
                return this._staticValue === null;
            },
            enumerable: true,
            configurable: true
        });
        ReplacePattern.prototype.buildReplaceString = function (matches) {
            if (this._staticValue !== null) {
                return this._staticValue;
            }
            var result = '';
            for (var i = 0, len = this._pieces.length; i < len; i++) {
                var piece = this._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 (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 = (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 = (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;
                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[256/*vs/editor/contrib/folding/common/folding*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ID = 'editor.contrib.folding';
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[257/*vs/editor/contrib/folding/common/indentFoldStrategy*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function computeRanges(model) {
        // we get here a clone of the model's indent ranges
        return model.getIndentRanges();
    }
    exports.computeRanges = computeRanges;
    /**
     * Limits the number of folding ranges by removing ranges with larger indent levels
     */
    function limitByIndent(ranges, maxEntries) {
        if (ranges.length <= maxEntries) {
            return ranges;
        }
        var indentOccurrences = [];
        ranges.forEach(function (r) {
            if (r.indent < 1000) {
                indentOccurrences[r.indent] = (indentOccurrences[r.indent] || 0) + 1;
            }
        });
        var maxIndent = indentOccurrences.length;
        for (var i = 0; i < indentOccurrences.length; i++) {
            if (indentOccurrences[i]) {
                maxEntries -= indentOccurrences[i];
                if (maxEntries < 0) {
                    maxIndent = i;
                    break;
                }
            }
        }
        return ranges.filter(function (r) { return r.indent < maxIndent; });
    }
    exports.limitByIndent = limitByIndent;
});

define(__m[258/*vs/editor/contrib/format/common/formatCommand*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,2/*vs/editor/common/core/range*/]), function (require, exports, strings, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var EditOperationsCommand = (function () {
        function EditOperationsCommand(edits, initialSelection) {
            this._initialSelection = initialSelection;
            this._edits = [];
            this._newEol = undefined;
            for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
                var edit = edits_1[_i];
                if (typeof edit.eol === 'number') {
                    this._newEol = edit.eol;
                }
                if (edit.range && typeof edit.text === 'string') {
                    this._edits.push(edit);
                }
            }
        }
        EditOperationsCommand.execute = function (editor, edits) {
            var cmd = new EditOperationsCommand(edits, editor.getSelection());
            if (typeof cmd._newEol === 'number') {
                editor.getModel().setEOL(cmd._newEol);
            }
            editor.pushUndoStop();
            editor.executeCommand('formatEditsCommand', cmd);
            editor.pushUndoStop();
        };
        EditOperationsCommand.prototype.getEditOperations = function (model, builder) {
            for (var _i = 0, _a = this._edits; _i < _a.length; _i++) {
                var edit = _a[_i];
                // We know that this edit.range comes from the mirror model, so it should only contain \n and no \r's
                var trimEdit = EditOperationsCommand.trimEdit(edit, model);
                if (trimEdit !== null) {
                    builder.addEditOperation(range_1.Range.lift(edit.range), edit.text);
                }
            }
            var selectionIsSet = false;
            if (Array.isArray(this._edits) && this._edits.length === 1 && this._initialSelection.isEmpty()) {
                if (this._edits[0].range.startColumn === this._initialSelection.endColumn &&
                    this._edits[0].range.startLineNumber === this._initialSelection.endLineNumber) {
                    selectionIsSet = true;
                    this._selectionId = builder.trackSelection(this._initialSelection, true);
                }
                else if (this._edits[0].range.endColumn === this._initialSelection.startColumn &&
                    this._edits[0].range.endLineNumber === this._initialSelection.startLineNumber) {
                    selectionIsSet = true;
                    this._selectionId = builder.trackSelection(this._initialSelection, false);
                }
            }
            if (!selectionIsSet) {
                this._selectionId = builder.trackSelection(this._initialSelection);
            }
        };
        EditOperationsCommand.prototype.computeCursorState = function (model, helper) {
            return helper.getTrackedSelection(this._selectionId);
        };
        EditOperationsCommand.fixLineTerminators = function (edit, model) {
            edit.text = edit.text.replace(/\r\n|\r|\n/g, model.getEOL());
        };
        /**
         * This is used to minimize the edits by removing changes that appear on the edges of the range which are identical
         * to the current text.
         *
         * The reason this was introduced is to allow better selection tracking of the current cursor and solve
         * bug #15108. There the cursor was jumping since the tracked selection was in the middle of the range edit
         * and was lost.
         */
        EditOperationsCommand.trimEdit = function (edit, model) {
            this.fixLineTerminators(edit, model);
            return this._trimEdit(model.validateRange(edit.range), edit.text, edit.forceMoveMarkers, model);
        };
        EditOperationsCommand._trimEdit = function (editRange, editText, editForceMoveMarkers, model) {
            var currentText = model.getValueInRange(editRange);
            // Find the equal characters in the front
            var commonPrefixLength = strings.commonPrefixLength(editText, currentText);
            // If the two strings are identical, return no edit (no-op)
            if (commonPrefixLength === currentText.length && commonPrefixLength === editText.length) {
                return null;
            }
            if (commonPrefixLength > 0) {
                // Apply front trimming
                var newStartPosition = model.modifyPosition(editRange.getStartPosition(), commonPrefixLength);
                editRange = new range_1.Range(newStartPosition.lineNumber, newStartPosition.column, editRange.endLineNumber, editRange.endColumn);
                editText = editText.substring(commonPrefixLength);
                currentText = currentText.substr(commonPrefixLength);
            }
            // Find the equal characters in the rear
            var commonSuffixLength = strings.commonSuffixLength(editText, currentText);
            if (commonSuffixLength > 0) {
                // Apply rear trimming
                var newEndPosition = model.modifyPosition(editRange.getEndPosition(), -commonSuffixLength);
                editRange = new range_1.Range(editRange.startLineNumber, editRange.startColumn, newEndPosition.lineNumber, newEndPosition.column);
                editText = editText.substring(0, editText.length - commonSuffixLength);
                currentText = currentText.substring(0, currentText.length - commonSuffixLength);
            }
            return {
                text: editText,
                range: editRange,
                forceMoveMarkers: editForceMoveMarkers
            };
        };
        return EditOperationsCommand;
    }());
    exports.EditOperationsCommand = EditOperationsCommand;
});

/*---------------------------------------------------------------------------------------------
 *  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/contrib/goToDeclaration/browser/clickLinkGesture*/], __M([1/*require*/,0/*exports*/,28/*vs/base/browser/browser*/,3/*vs/base/common/lifecycle*/,11/*vs/base/common/event*/,15/*vs/base/common/platform*/,171/*vs/css!vs/editor/contrib/goToDeclaration/browser/goToDeclarationMouse*/]), 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 = (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 = (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 = (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 = (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;
});

define(__m[195/*vs/editor/contrib/hover/browser/hoverOperation*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/async*/,10/*vs/base/common/errors*/]), function (require, exports, async_1, errors_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ComputeHoverOperationState;
    (function (ComputeHoverOperationState) {
        ComputeHoverOperationState[ComputeHoverOperationState["IDLE"] = 0] = "IDLE";
        ComputeHoverOperationState[ComputeHoverOperationState["FIRST_WAIT"] = 1] = "FIRST_WAIT";
        ComputeHoverOperationState[ComputeHoverOperationState["SECOND_WAIT"] = 2] = "SECOND_WAIT";
        ComputeHoverOperationState[ComputeHoverOperationState["WAITING_FOR_ASYNC_COMPUTATION"] = 3] = "WAITING_FOR_ASYNC_COMPUTATION";
    })(ComputeHoverOperationState || (ComputeHoverOperationState = {}));
    var HoverOperation = (function () {
        function HoverOperation(computer, success, error, progress) {
            var _this = this;
            this._computer = computer;
            this._state = 0 /* IDLE */;
            this._firstWaitScheduler = new async_1.RunOnceScheduler(function () { return _this._triggerAsyncComputation(); }, this._getHoverTimeMillis() / 2);
            this._secondWaitScheduler = new async_1.RunOnceScheduler(function () { return _this._triggerSyncComputation(); }, this._getHoverTimeMillis() / 2);
            this._loadingMessageScheduler = new async_1.RunOnceScheduler(function () { return _this._showLoadingMessage(); }, 3 * this._getHoverTimeMillis());
            this._asyncComputationPromise = null;
            this._asyncComputationPromiseDone = false;
            this._completeCallback = success;
            this._errorCallback = error;
            this._progressCallback = progress;
        }
        HoverOperation.prototype.getComputer = function () {
            return this._computer;
        };
        HoverOperation.prototype._getHoverTimeMillis = function () {
            if (this._computer.getHoverTimeMillis) {
                return this._computer.getHoverTimeMillis();
            }
            return HoverOperation.HOVER_TIME;
        };
        HoverOperation.prototype._triggerAsyncComputation = function () {
            var _this = this;
            this._state = 2 /* SECOND_WAIT */;
            this._secondWaitScheduler.schedule();
            if (this._computer.computeAsync) {
                this._asyncComputationPromiseDone = false;
                this._asyncComputationPromise = this._computer.computeAsync().then(function (asyncResult) {
                    _this._asyncComputationPromiseDone = true;
                    _this._withAsyncResult(asyncResult);
                }, function () { return _this._onError; });
            }
            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 () {
            if (this._state === 0 /* IDLE */) {
                this._state = 1 /* FIRST_WAIT */;
                this._firstWaitScheduler.schedule();
                this._loadingMessageScheduler.schedule();
            }
        };
        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 */;
        };
        HoverOperation.HOVER_TIME = 300;
        return HoverOperation;
    }());
    exports.HoverOperation = HoverOperation;
});











define(__m[196/*vs/editor/contrib/hover/browser/hoverWidgets*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,12/*vs/editor/common/core/position*/,25/*vs/editor/browser/editorBrowser*/,41/*vs/base/browser/ui/widget*/,63/*vs/base/browser/ui/scrollbar/scrollableElement*/,3/*vs/base/common/lifecycle*/]), function (require, exports, dom_1, position_1, editorBrowser, widget_1, scrollableElement_1, lifecycle_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ContentHoverWidget = (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.updateMaxHeight(); });
            _this.updateMaxHeight();
            _this._editor.addContentWidget(_this);
            _this._showAtPosition = 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, focus) {
            // Position has changed
            this._showAtPosition = new position_1.Position(position.lineNumber, position.column);
            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,
                    preference: [
                        editorBrowser.ContentWidgetPositionPreference.ABOVE,
                        editorBrowser.ContentWidgetPositionPreference.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 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); });
        };
        ContentHoverWidget.prototype.updateContents = function (node) {
            this._domNode.textContent = '';
            this._domNode.appendChild(node);
            this.updateFont();
            this._editor.layoutContentWidget(this);
            this.scrollbar.scanDomNode();
        };
        ContentHoverWidget.prototype.updateMaxHeight = 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";
        };
        return ContentHoverWidget;
    }(widget_1.Widget));
    exports.ContentHoverWidget = ContentHoverWidget;
    var GlyphHoverWidget = (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;
});

define(__m[262/*vs/editor/contrib/inPlaceReplace/common/inPlaceReplaceCommand*/], __M([1/*require*/,0/*exports*/,22/*vs/editor/common/core/selection*/]), function (require, exports, selection_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var InPlaceReplaceCommand = (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[263/*vs/editor/contrib/indentation/common/indentUtils*/], __M([1/*require*/,0/*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;
});

define(__m[264/*vs/editor/contrib/linesOperations/common/copyLinesCommand*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CopyLinesCommand = (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, startColumn = result.startColumn, endLineNumber = result.endLineNumber, 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;
});

define(__m[265/*vs/editor/contrib/linesOperations/common/deleteLinesCommand*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var DeleteLinesCommand = (function () {
        function DeleteLinesCommand(startLineNumber, endLineNumber, restoreCursorToColumn) {
            this.startLineNumber = startLineNumber;
            this.endLineNumber = endLineNumber;
            this.restoreCursorToColumn = restoreCursorToColumn;
        }
        DeleteLinesCommand.createFromSelection = function (selection) {
            var endLineNumber = selection.endLineNumber;
            if (selection.startLineNumber < selection.endLineNumber && selection.endColumn === 1) {
                endLineNumber -= 1;
            }
            return new DeleteLinesCommand(selection.startLineNumber, endLineNumber, selection.positionColumn);
        };
        DeleteLinesCommand.prototype.getEditOperations = function (model, builder) {
            if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
                // Model is empty
                return;
            }
            var startLineNumber = this.startLineNumber;
            var endLineNumber = this.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);
            }
            builder.addTrackedEditOperation(new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn), null);
        };
        DeleteLinesCommand.prototype.computeCursorState = function (model, helper) {
            var inverseEditOperations = helper.getInverseEditOperations();
            var srcRange = inverseEditOperations[0].range;
            return new selection_1.Selection(srcRange.endLineNumber, this.restoreCursorToColumn, srcRange.endLineNumber, this.restoreCursorToColumn);
        };
        return DeleteLinesCommand;
    }());
    exports.DeleteLinesCommand = DeleteLinesCommand;
});

define(__m[266/*vs/editor/contrib/linesOperations/common/sortLinesCommand*/], __M([1/*require*/,0/*exports*/,59/*vs/editor/common/core/editOperation*/,2/*vs/editor/common/core/range*/]), function (require, exports, editOperation_1, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var SortLinesCommand = (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) {
            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'));
    }
});

var __assign = (this && this.__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;
};
define(__m[267/*vs/editor/contrib/quickFix/browser/lightBulbWidget*/], __M([1/*require*/,0/*exports*/,123/*vs/base/common/cancellation*/,11/*vs/base/common/event*/,4/*vs/base/browser/dom*/,20/*vs/editor/common/editorCommon*/,25/*vs/editor/browser/editorBrowser*/,391/*vs/css!vs/editor/contrib/quickFix/browser/lightBulbWidget*/]), function (require, exports, cancellation_1, event_1, dom, editorCommon_1, editorBrowser_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var LightBulbWidget = (function () {
        function LightBulbWidget(editor) {
            var _this = this;
            this._options = {
                stickiness: editorCommon_1.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
                glyphMarginClassName: 'lightbulb-glyph',
                glyphMarginHoverMessage: undefined
            };
            this._onClick = new event_1.Emitter();
            this._decorationIds = [];
            this._futureFixes = new cancellation_1.CancellationTokenSource();
            this._editor = editor;
            this._mouseDownSubscription = this._editor.onMouseDown(function (e) {
                // not on glyh margin or not on 💡
                if (e.target.type !== editorBrowser_1.MouseTargetType.GUTTER_GLYPH_MARGIN
                    || _this._currentLine === undefined
                    || _this._currentLine !== e.target.position.lineNumber) {
                    return;
                }
                // a bit of extra work to make sure the menu
                // doesn't cover the line-text
                var _a = dom.getDomNodePagePosition(e.target.element), top = _a.top, height = _a.height;
                var lineHeight = _this._editor.getConfiguration().lineHeight;
                _this._onClick.fire({
                    x: e.event.posx,
                    y: top + height + Math.floor(lineHeight / 3)
                });
            });
        }
        LightBulbWidget.prototype.dispose = function () {
            this._mouseDownSubscription.dispose();
            this.hide();
        };
        Object.defineProperty(LightBulbWidget.prototype, "onClick", {
            get: function () {
                return this._onClick.event;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(LightBulbWidget.prototype, "model", {
            get: function () {
                return this._model;
            },
            set: function (e) {
                var _this = this;
                this._model = e;
                this.hide();
                this._futureFixes = new cancellation_1.CancellationTokenSource();
                var token = this._futureFixes.token;
                e.fixes.done(function (fixes) {
                    if (!token.isCancellationRequested && fixes && fixes.length > 0) {
                        _this.show(e);
                    }
                    else {
                        _this.hide();
                    }
                }, function (err) {
                    _this.hide();
                });
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(LightBulbWidget.prototype, "title", {
            get: function () {
                return this._options.glyphMarginHoverMessage;
            },
            set: function (value) {
                // TODO(joh,alex) this isn't working well because the hover hover
                // message sticks around after clicking the light bulb
                // this._options.glyphMarginHoverMessage = value;
            },
            enumerable: true,
            configurable: true
        });
        LightBulbWidget.prototype.show = function (e) {
            this._currentLine = e.range.startLineNumber;
            this._decorationIds = this._editor.deltaDecorations(this._decorationIds, [{
                    options: this._options,
                    range: __assign({}, e.range, { endLineNumber: e.range.startLineNumber })
                }]);
        };
        LightBulbWidget.prototype.hide = function () {
            this._decorationIds = this._editor.deltaDecorations(this._decorationIds, []);
            this._futureFixes.cancel();
            this._currentLine = undefined;
        };
        return LightBulbWidget;
    }());
    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[268/*vs/editor/contrib/quickFix/browser/quickFixWidget*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/async*/,4/*vs/base/browser/dom*/,12/*vs/editor/common/core/position*/,53/*vs/base/common/actions*/,11/*vs/base/common/event*/]), function (require, exports, async_1, dom_1, position_1, actions_1, event_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var QuickFixContextMenu = (function () {
        function QuickFixContextMenu(editor, contextMenuService, commandService) {
            this._onDidExecuteCodeAction = new event_1.Emitter();
            this.onDidExecuteCodeAction = this._onDidExecuteCodeAction.event;
            this._editor = editor;
            this._contextMenuService = contextMenuService;
            this._commandService = commandService;
        }
        QuickFixContextMenu.prototype.show = function (fixes, at) {
            var _this = this;
            var actions = fixes.then(function (value) {
                return value.map(function (command) {
                    return new actions_1.Action(command.id, command.title, undefined, true, function () {
                        return async_1.always((_a = _this._commandService).executeCommand.apply(_a, [command.id].concat(command.arguments)), function () { return _this._onDidExecuteCodeAction.fire(undefined); });
                        var _a;
                    });
                });
            });
            this._contextMenuService.showContextMenu({
                getAnchor: function () {
                    if (position_1.Position.isIPosition(at)) {
                        at = _this._toCoords(at);
                    }
                    return at;
                },
                getActions: function () { return actions; },
                onHide: function () { _this._visible = false; }
            });
        };
        Object.defineProperty(QuickFixContextMenu.prototype, "isVisible", {
            get: function () {
                return this._visible;
            },
            enumerable: true,
            configurable: true
        });
        QuickFixContextMenu.prototype._toCoords = function (position) {
            this._editor.revealPosition(position);
            this._editor.render();
            // Translate to absolute editor position
            var cursorCoords = this._editor.getScrolledVisiblePosition(this._editor.getPosition());
            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 QuickFixContextMenu;
    }());
    exports.QuickFixContextMenu = QuickFixContextMenu;
});











define(__m[269/*vs/editor/contrib/smartSelect/common/tokenTree*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/,91/*vs/editor/common/modes/supports*/,98/*vs/editor/common/modes/supports/richEditBrackets*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, range_1, supports_1, richEditBrackets_1, languageConfigurationRegistry_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var TokenTreeBracket;
    (function (TokenTreeBracket) {
        TokenTreeBracket[TokenTreeBracket["None"] = 0] = "None";
        TokenTreeBracket[TokenTreeBracket["Open"] = 1] = "Open";
        TokenTreeBracket[TokenTreeBracket["Close"] = -1] = "Close";
    })(TokenTreeBracket = exports.TokenTreeBracket || (exports.TokenTreeBracket = {}));
    var Node = (function () {
        function Node() {
        }
        Object.defineProperty(Node.prototype, "range", {
            get: function () {
                return new range_1.Range(this.start.lineNumber, this.start.column, this.end.lineNumber, this.end.column);
            },
            enumerable: true,
            configurable: true
        });
        return Node;
    }());
    exports.Node = Node;
    var NodeList = (function (_super) {
        __extends(NodeList, _super);
        function NodeList() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(NodeList.prototype, "start", {
            get: function () {
                return this.hasChildren
                    ? this.children[0].start
                    : this.parent.start;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(NodeList.prototype, "end", {
            get: function () {
                return this.hasChildren
                    ? this.children[this.children.length - 1].end
                    : this.parent.end;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(NodeList.prototype, "hasChildren", {
            get: function () {
                return this.children && this.children.length > 0;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(NodeList.prototype, "isEmpty", {
            get: function () {
                return !this.hasChildren && !this.parent;
            },
            enumerable: true,
            configurable: true
        });
        NodeList.prototype.append = function (node) {
            if (!node) {
                return false;
            }
            node.parent = this;
            if (!this.children) {
                this.children = [];
            }
            if (node instanceof NodeList) {
                if (node.children) {
                    this.children.push.apply(this.children, node.children);
                }
            }
            else {
                this.children.push(node);
            }
            return true;
        };
        return NodeList;
    }(Node));
    exports.NodeList = NodeList;
    var Block = (function (_super) {
        __extends(Block, _super);
        function Block() {
            var _this = _super.call(this) || this;
            _this.elements = new NodeList();
            _this.elements.parent = _this;
            return _this;
        }
        Object.defineProperty(Block.prototype, "start", {
            get: function () {
                return this.open.start;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Block.prototype, "end", {
            get: function () {
                return this.close.end;
            },
            enumerable: true,
            configurable: true
        });
        return Block;
    }(Node));
    exports.Block = Block;
    var Token = (function () {
        function Token(range, bracket, bracketType) {
            this.range = range;
            this.bracket = bracket;
            this.bracketType = bracketType;
        }
        return Token;
    }());
    function newNode(token) {
        var node = new Node();
        node.start = token.range.getStartPosition();
        node.end = token.range.getEndPosition();
        return node;
    }
    var RawToken = (function () {
        function RawToken(source, lineNumber, lineText) {
            this.lineNumber = lineNumber;
            this.lineText = lineText;
            this.startOffset = source.startOffset;
            this.endOffset = source.endOffset;
            this.type = source.tokenType;
            this.languageId = source.languageId;
        }
        return RawToken;
    }());
    var ModelRawTokenScanner = (function () {
        function ModelRawTokenScanner(model) {
            this._model = model;
            this._lineCount = this._model.getLineCount();
            this._versionId = this._model.getVersionId();
            this._lineNumber = 0;
            this._lineText = null;
            this._advance();
        }
        ModelRawTokenScanner.prototype._advance = function () {
            this._next = (this._next ? this._next.next() : null);
            while (!this._next && this._lineNumber < this._lineCount) {
                this._lineNumber++;
                this._lineText = this._model.getLineContent(this._lineNumber);
                this._model.forceTokenization(this._lineNumber);
                var currentLineTokens = this._model.getLineTokens(this._lineNumber);
                this._next = currentLineTokens.firstToken();
            }
        };
        ModelRawTokenScanner.prototype.next = function () {
            if (!this._next) {
                return null;
            }
            if (this._model.getVersionId() !== this._versionId) {
                return null;
            }
            var result = new RawToken(this._next, this._lineNumber, this._lineText);
            this._advance();
            return result;
        };
        return ModelRawTokenScanner;
    }());
    var TokenScanner = (function () {
        function TokenScanner(model) {
            this._rawTokenScanner = new ModelRawTokenScanner(model);
            this._nextBuff = [];
            this._cachedLanguageBrackets = null;
            this._cachedLanguageId = -1;
        }
        TokenScanner.prototype.next = function () {
            if (this._nextBuff.length > 0) {
                return this._nextBuff.shift();
            }
            var token = this._rawTokenScanner.next();
            if (!token) {
                return null;
            }
            var lineNumber = token.lineNumber;
            var lineText = token.lineText;
            var tokenType = token.type;
            var startOffset = token.startOffset;
            var endOffset = token.endOffset;
            if (this._cachedLanguageId !== token.languageId) {
                this._cachedLanguageId = token.languageId;
                this._cachedLanguageBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(this._cachedLanguageId);
            }
            var modeBrackets = this._cachedLanguageBrackets;
            if (!modeBrackets || supports_1.ignoreBracketsInToken(tokenType)) {
                return new Token(new range_1.Range(lineNumber, startOffset + 1, lineNumber, endOffset + 1), 0 /* None */, null);
            }
            var foundBracket;
            do {
                foundBracket = richEditBrackets_1.BracketsUtils.findNextBracketInToken(modeBrackets.forwardRegex, lineNumber, lineText, startOffset, endOffset);
                if (foundBracket) {
                    var foundBracketStartOffset = foundBracket.startColumn - 1;
                    var foundBracketEndOffset = foundBracket.endColumn - 1;
                    if (startOffset < foundBracketStartOffset) {
                        // there is some text before this bracket in this token
                        this._nextBuff.push(new Token(new range_1.Range(lineNumber, startOffset + 1, lineNumber, foundBracketStartOffset + 1), 0 /* None */, null));
                    }
                    var bracketText = lineText.substring(foundBracketStartOffset, foundBracketEndOffset);
                    bracketText = bracketText.toLowerCase();
                    var bracketData = modeBrackets.textIsBracket[bracketText];
                    var bracketIsOpen = modeBrackets.textIsOpenBracket[bracketText];
                    this._nextBuff.push(new Token(new range_1.Range(lineNumber, foundBracketStartOffset + 1, lineNumber, foundBracketEndOffset + 1), bracketIsOpen ? 1 /* Open */ : -1 /* Close */, bracketData.languageIdentifier.language + ";" + bracketData.open + ";" + bracketData.close));
                    startOffset = foundBracketEndOffset;
                }
            } while (foundBracket);
            if (startOffset < endOffset) {
                // there is some remaining none-bracket text in this token
                this._nextBuff.push(new Token(new range_1.Range(lineNumber, startOffset + 1, lineNumber, endOffset + 1), 0 /* None */, null));
            }
            return this._nextBuff.shift();
        };
        return TokenScanner;
    }());
    var TokenTreeBuilder = (function () {
        function TokenTreeBuilder(model) {
            this._stack = [];
            this._scanner = new TokenScanner(model);
        }
        TokenTreeBuilder.prototype.build = function () {
            var node = new NodeList();
            while (node.append(this._line() || this._any())) {
                // accept all
            }
            return node;
        };
        TokenTreeBuilder.prototype._accept = function (condt) {
            var token = this._stack.pop() || this._scanner.next();
            if (!token) {
                return false;
            }
            var accepted = condt(token);
            if (!accepted) {
                this._stack.push(token);
                this._currentToken = null;
            }
            else {
                this._currentToken = token;
                //			console.log('accepted: ' + token.__debugContent);
            }
            return accepted;
        };
        TokenTreeBuilder.prototype._peek = function (condt) {
            var ret = false;
            this._accept(function (info) {
                ret = condt(info);
                return false;
            });
            return ret;
        };
        TokenTreeBuilder.prototype._line = function () {
            var node = new NodeList(), lineNumber;
            // capture current linenumber
            this._peek(function (info) {
                lineNumber = info.range.startLineNumber;
                return false;
            });
            while (this._peek(function (info) { return info.range.startLineNumber === lineNumber; })
                && node.append(this._token() || this._block())) {
                // all children that started on this line
            }
            if (!node.children || node.children.length === 0) {
                return null;
            }
            else if (node.children.length === 1) {
                return node.children[0];
            }
            else {
                return node;
            }
        };
        TokenTreeBuilder.prototype._token = function () {
            if (!this._accept(function (token) { return token.bracket === 0 /* None */; })) {
                return null;
            }
            return newNode(this._currentToken);
        };
        TokenTreeBuilder.prototype._block = function () {
            var bracketType, accepted;
            accepted = this._accept(function (token) {
                bracketType = token.bracketType;
                return token.bracket === 1 /* Open */;
            });
            if (!accepted) {
                return null;
            }
            var bracket = new Block();
            bracket.open = newNode(this._currentToken);
            while (bracket.elements.append(this._line())) {
                // inside brackets
            }
            if (!this._accept(function (token) { return token.bracket === -1 /* Close */ && token.bracketType === bracketType; })) {
                // missing closing bracket -> return just a node list
                var nodelist = new NodeList();
                nodelist.append(bracket.open);
                nodelist.append(bracket.elements);
                return nodelist;
            }
            bracket.close = newNode(this._currentToken);
            return bracket;
        };
        TokenTreeBuilder.prototype._any = function () {
            if (!this._accept(function (_) { return true; })) {
                return null;
            }
            return newNode(this._currentToken);
        };
        return TokenTreeBuilder;
    }());
    /**
     * Parses this grammar:
     *	grammer = { line }
     *	line = { block | "token" }
     *	block = "open_bracket" { line } "close_bracket"
     */
    function build(model) {
        var node = new TokenTreeBuilder(model).build();
        return node;
    }
    exports.build = build;
    function find(node, position) {
        if (node instanceof NodeList && node.isEmpty) {
            return null;
        }
        if (!range_1.Range.containsPosition(node.range, position)) {
            return null;
        }
        var result;
        if (node instanceof NodeList) {
            if (node.hasChildren) {
                for (var i = 0, len = node.children.length; i < len && !result; i++) {
                    result = find(node.children[i], position);
                }
            }
        }
        else if (node instanceof Block) {
            result = find(node.open, position) || find(node.elements, position) || find(node.close, position);
        }
        return result || node;
    }
    exports.find = find;
});

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










define(__m[142/*vs/editor/contrib/snippet/browser/snippetParser*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var TokenType;
    (function (TokenType) {
        TokenType[TokenType["Dollar"] = 0] = "Dollar";
        TokenType[TokenType["Colon"] = 1] = "Colon";
        TokenType[TokenType["Comma"] = 2] = "Comma";
        TokenType[TokenType["CurlyOpen"] = 3] = "CurlyOpen";
        TokenType[TokenType["CurlyClose"] = 4] = "CurlyClose";
        TokenType[TokenType["Backslash"] = 5] = "Backslash";
        TokenType[TokenType["Forwardslash"] = 6] = "Forwardslash";
        TokenType[TokenType["Pipe"] = 7] = "Pipe";
        TokenType[TokenType["Int"] = 8] = "Int";
        TokenType[TokenType["VariableName"] = 9] = "VariableName";
        TokenType[TokenType["Format"] = 10] = "Format";
        TokenType[TokenType["EOF"] = 11] = "EOF";
    })(TokenType = exports.TokenType || (exports.TokenType = {}));
    var Scanner = (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: TokenType.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 = TokenType.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 = TokenType.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 = TokenType.Format;
            do {
                len += 1;
                ch = this.value.charCodeAt(pos + len);
            } while (!isNaN(ch)
                && typeof Scanner._table[ch] === 'undefined' // not static token
                && !Scanner.isDigitCharacter(ch) // not number
                && !Scanner.isVariableCharacter(ch) // not variable
            );
            this.pos += len;
            return { type: type, pos: pos, len: len };
        };
        Scanner._table = (_a = {},
            _a[36 /* DollarSign */] = TokenType.Dollar,
            _a[58 /* Colon */] = TokenType.Colon,
            _a[44 /* Comma */] = TokenType.Comma,
            _a[123 /* OpenCurlyBrace */] = TokenType.CurlyOpen,
            _a[125 /* CloseCurlyBrace */] = TokenType.CurlyClose,
            _a[92 /* Backslash */] = TokenType.Backslash,
            _a[47 /* Slash */] = TokenType.Forwardslash,
            _a[124 /* Pipe */] = TokenType.Pipe,
            _a);
        return Scanner;
    }());
    exports.Scanner = Scanner;
    var Marker = (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;
            others.forEach(function (node) { return node.parent = 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 = (function (_super) {
        __extends(Text, _super);
        function Text(value) {
            var _this = _super.call(this) || this;
            _this.value = value;
            return _this;
        }
        Text.prototype.toString = function () {
            return this.value;
        };
        Text.prototype.toTextmateString = function () {
            return this.value.replace(/\$|}|\\/g, '\\$&');
        };
        Text.prototype.len = function () {
            return this.value.length;
        };
        Text.prototype.clone = function () {
            return new Text(this.value);
        };
        return Text;
    }(Marker));
    exports.Text = Text;
    var Placeholder = (function (_super) {
        __extends(Placeholder, _super);
        function Placeholder(index) {
            var _this = _super.call(this) || this;
            _this.index = index;
            return _this;
        }
        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.toTextmateString = function () {
            if (this.children.length === 0) {
                return "$" + this.index;
            }
            else if (this.choice) {
                return "${" + this.index + "|" + this.choice.toTextmateString() + "|}";
            }
            else {
                return "${" + this.index + ":" + this.children.map(function (child) { return child.toTextmateString(); }).join('') + "}";
            }
        };
        Placeholder.prototype.clone = function () {
            var ret = new Placeholder(this.index);
            ret._children = this.children.map(function (child) { return child.clone(); });
            return ret;
        };
        return Placeholder;
    }(Marker));
    exports.Placeholder = Placeholder;
    var Choice = (function (_super) {
        __extends(Choice, _super);
        function Choice() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.options = [];
            return _this;
        }
        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.toTextmateString = function () {
            return this.options
                .map(function (option) { return option.value.replace(/\||,/g, '\\$&'); })
                .join(',');
        };
        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 Variable = (function (_super) {
        __extends(Variable, _super);
        function Variable(name) {
            var _this = _super.call(this) || this;
            _this.name = name;
            return _this;
        }
        Variable.prototype.resolve = function (resolver) {
            var value = resolver.resolve(this);
            if (value !== undefined) {
                this._children = [new Text(value)];
                return true;
            }
            return false;
        };
        Variable.prototype.toTextmateString = function () {
            if (this.children.length === 0) {
                return "${" + this.name + "}";
            }
            else {
                return "${" + this.name + ":" + this.children.map(function (child) { return child.toTextmateString(); }).join('') + "}";
            }
        };
        Variable.prototype.clone = function () {
            var ret = new Variable(this.name);
            ret._children = this.children.map(function (child) { return child.clone(); });
            return ret;
        };
        return Variable;
    }(Marker));
    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 = (function (_super) {
        __extends(TextmateSnippet, _super);
        function TextmateSnippet() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(TextmateSnippet.prototype, "placeholders", {
            get: function () {
                var _this = this;
                if (!this._placeholders) {
                    // fill in placeholders
                    this._placeholders = [];
                    this.walk(function (candidate) {
                        if (candidate instanceof Placeholder) {
                            _this.placeholders.push(candidate);
                        }
                        return true;
                    });
                }
                return this._placeholders;
            },
            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 = this;
            this.walk(function (candidate) {
                if (candidate instanceof Variable) {
                    if (candidate.resolve(resolver)) {
                        _this._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.toTextmateString = function () {
            return this.children.reduce(function (prev, cur) { return prev + cur.toTextmateString(); }, '');
        };
        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 = (function () {
        function SnippetParser() {
            this._scanner = new Scanner();
        }
        SnippetParser.escape = function (value) {
            return value.replace(/\$|}|\\/g, '\\$&');
        };
        SnippetParser.prototype.text = function (value) {
            return this.parse(value).toString();
        };
        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 = [];
            snippet.walk(function (marker) {
                if (marker instanceof Placeholder) {
                    if (marker.isFinalTabstop) {
                        placeholderDefaultValues.set(0);
                    }
                    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];
                if (placeholderDefaultValues.has(placeholder.index)) {
                    var clone = new Placeholder(placeholder.index);
                    for (var _a = 0, _b = placeholderDefaultValues.get(placeholder.index); _a < _b.length; _a++) {
                        var child = _b[_a];
                        clone.appendChild(child.clone());
                    }
                    snippet.replace(placeholder, [clone]);
                }
            }
            if (!placeholderDefaultValues.has(0) &&
                (insertFinalTabstop && placeholderDefaultValues.size > 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._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(TokenType.Backslash, true)) {
                // saw a backslash, append escaped token or that backslash
                value = this._accept(TokenType.Dollar, true)
                    || this._accept(TokenType.CurlyClose, true)
                    || this._accept(TokenType.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(TokenType.Dollar)
                && (value = this._accept(TokenType.VariableName, true) || this._accept(TokenType.Int, true));
            if (!match) {
                return this._backTo(token);
            }
            parent.appendChild(/^\d+$/.test(value)
                ? new Placeholder(Number(value))
                : new Variable(value));
            return true;
        };
        // ${1:<children>}, ${1} -> placeholder
        SnippetParser.prototype._parseComplexPlaceholder = function (parent) {
            var index;
            var token = this._token;
            var match = this._accept(TokenType.Dollar)
                && this._accept(TokenType.CurlyOpen)
                && (index = this._accept(TokenType.Int, true));
            if (!match) {
                return this._backTo(token);
            }
            var placeholder = new Placeholder(Number(index));
            if (this._accept(TokenType.Colon)) {
                // ${1:<children>}
                while (true) {
                    // ...} -> done
                    if (this._accept(TokenType.CurlyClose)) {
                        parent.appendChild(placeholder);
                        return true;
                    }
                    if (this._parse(placeholder)) {
                        continue;
                    }
                    // fallback
                    parent.appendChild(new Text('${' + index + ':'));
                    placeholder.children.forEach(parent.appendChild, parent);
                    return true;
                }
            }
            else if (this._accept(TokenType.Pipe)) {
                // ${1|one,two,three|}
                var choice = new Choice();
                while (true) {
                    if (this._parseChoiceElement(choice)) {
                        if (this._accept(TokenType.Comma)) {
                            // opt, -> more
                            continue;
                        }
                        if (this._accept(TokenType.Pipe) && this._accept(TokenType.CurlyClose)) {
                            // ..|} -> done
                            placeholder.appendChild(choice);
                            parent.appendChild(placeholder);
                            return true;
                        }
                    }
                    this._backTo(token);
                    return false;
                }
            }
            else if (this._accept(TokenType.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 === TokenType.Comma || this._token.type === TokenType.Pipe) {
                    break;
                }
                var value = void 0;
                if (value = this._accept(TokenType.Backslash, true)) {
                    // \, or \|
                    value = this._accept(TokenType.Comma, true)
                        || this._accept(TokenType.Pipe, true)
                        || value;
                }
                else {
                    value = this._accept(undefined, true);
                }
                if (!value) {
                    // EOF
                    this._backTo(token);
                    return false;
                }
                values.push(value);
            }
            if (values.length === 0) {
                this._backTo(token);
                return false;
            }
            parent.appendChild(new Text(values.join('')));
            return true;
        };
        // ${foo:<children>}, ${foo} -> variable
        SnippetParser.prototype._parseComplexVariable = function (parent) {
            var name;
            var token = this._token;
            var match = this._accept(TokenType.Dollar)
                && this._accept(TokenType.CurlyOpen)
                && (name = this._accept(TokenType.VariableName, true));
            if (!match) {
                return this._backTo(token);
            }
            var variable = new Variable(name);
            if (this._accept(TokenType.Colon)) {
                // ${foo:<children>}
                while (true) {
                    // ...} -> done
                    if (this._accept(TokenType.CurlyClose)) {
                        parent.appendChild(variable);
                        return true;
                    }
                    if (this._parse(variable)) {
                        continue;
                    }
                    // fallback
                    parent.appendChild(new Text('${' + name + ':'));
                    variable.children.forEach(parent.appendChild, parent);
                    return true;
                }
            }
            else if (this._accept(TokenType.CurlyClose)) {
                // ${foo}
                parent.appendChild(variable);
                return true;
            }
            else {
                // ${foo <- missing curly or colon
                return this._backTo(token);
            }
        };
        SnippetParser.prototype._parseAnything = function (marker) {
            if (this._token.type !== TokenType.EOF) {
                marker.appendChild(new Text(this._scanner.tokenText(this._token)));
                this._accept(undefined);
                return true;
            }
            return false;
        };
        return SnippetParser;
    }());
    exports.SnippetParser = SnippetParser;
    var _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[271/*vs/editor/contrib/snippet/browser/snippetVariables*/], __M([1/*require*/,0/*exports*/,45/*vs/base/common/paths*/,142/*vs/editor/contrib/snippet/browser/snippetParser*/,9/*vs/base/common/strings*/]), function (require, exports, paths_1, snippetParser_1, strings_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var EditorSnippetVariableResolver = (function () {
        function EditorSnippetVariableResolver(_model, _selection) {
            this._model = _model;
            this._selection = _selection;
            //
        }
        EditorSnippetVariableResolver.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) {
                    // 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);
            }
            else if (name === 'TM_FILENAME') {
                return paths_1.basename(this._model.uri.fsPath);
            }
            else if (name === 'TM_DIRECTORY') {
                var dir = paths_1.dirname(this._model.uri.fsPath);
                return dir !== '.' ? dir : '';
            }
            else if (name === 'TM_FILEPATH') {
                return this._model.uri.fsPath;
            }
            else {
                return undefined;
            }
        };
        EditorSnippetVariableResolver.VariableNames = Object.freeze({
            'SELECTION': true,
            'TM_SELECTED_TEXT': true,
            'TM_CURRENT_LINE': true,
            'TM_CURRENT_WORD': true,
            'TM_LINE_INDEX': true,
            'TM_LINE_NUMBER': true,
            'TM_FILENAME': true,
            'TM_DIRECTORY': true,
            'TM_FILEPATH': true,
        });
        return EditorSnippetVariableResolver;
    }());
    exports.EditorSnippetVariableResolver = EditorSnippetVariableResolver;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[272/*vs/editor/contrib/suggest/browser/completionModel*/], __M([1/*require*/,0/*exports*/,81/*vs/base/common/filters*/]), function (require, exports, filters_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var LineContext = (function () {
        function LineContext() {
        }
        return LineContext;
    }());
    exports.LineContext = LineContext;
    var CompletionModel = (function () {
        function CompletionModel(items, column, lineContext, snippetConfig) {
            this._snippetCompareFn = CompletionModel._compareCompletionItems;
            this._items = items;
            this._column = column;
            this._lineContext = lineContext;
            if (snippetConfig === 'top') {
                this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsUp;
            }
            else if (snippetConfig === 'bottom') {
                this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsDown;
            }
        }
        Object.defineProperty(CompletionModel.prototype, "lineContext", {
            get: function () {
                return this._lineContext;
            },
            set: function (value) {
                if (this._lineContext.leadingLineContent !== value.leadingLineContent
                    || this._lineContext.characterCountDelta !== value.characterCountDelta) {
                    this._lineContext = value;
                    this._filteredItems = undefined;
                }
            },
            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.resolveIncompleteInfo = function () {
            var incomplete = [];
            var complete = [];
            for (var _i = 0, _a = this._items; _i < _a.length; _i++) {
                var item = _a[_i];
                if (!item.container.incomplete) {
                    complete.push(item);
                }
                else if (incomplete.indexOf(item.support) < 0) {
                    incomplete.push(item.support);
                }
            }
            return { incomplete: incomplete, complete: complete };
        };
        Object.defineProperty(CompletionModel.prototype, "stats", {
            get: function () {
                this._ensureCachedState();
                return this._stats;
            },
            enumerable: true,
            configurable: true
        });
        CompletionModel.prototype._ensureCachedState = function () {
            if (!this._filteredItems) {
                this._createCachedState();
            }
        };
        CompletionModel.prototype._createCachedState = function () {
            this._filteredItems = [];
            this._isIncomplete = false;
            this._stats = { suggestionCount: 0, snippetCount: 0, textCount: 0 };
            var _a = this._lineContext, leadingLineContent = _a.leadingLineContent, characterCountDelta = _a.characterCountDelta;
            var word = '';
            for (var i = 0; i < this._items.length; i++) {
                var item = this._items[i];
                var suggestion = item.suggestion, container = item.container;
                // collect those supports that signaled having
                // an incomplete result
                this._isIncomplete = this._isIncomplete || container.incomplete;
                // 'word' is that remainder of the current line that we
                // filter and score against. In theory each suggestion uses a
                // differnet word, but in practice not - that's why we cache
                var wordLen = suggestion.overwriteBefore + characterCountDelta - (item.position.column - this._column);
                if (word.length !== wordLen) {
                    word = wordLen === 0 ? '' : leadingLineContent.slice(-wordLen);
                }
                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 = -100;
                }
                else if (typeof suggestion.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 = filters_1.fuzzyScore(word, suggestion.filterText, suggestion.overwriteBefore);
                    if (!match) {
                        continue;
                    }
                    item.score = match[0];
                    item.matches = [];
                    match = filters_1.fuzzyScore(word, suggestion.label, suggestion.overwriteBefore);
                    if (match) {
                        item.matches = match[1];
                    }
                }
                else {
                    // by default match `word` against the `label`
                    var match = filters_1.fuzzyScore(word, suggestion.label, suggestion.overwriteBefore);
                    if (match) {
                        item.score = match[0];
                        item.matches = match[1];
                    }
                    else {
                        continue;
                    }
                }
                item.idx = i;
                this._filteredItems.push(item);
                // update stats
                this._stats.suggestionCount++;
                switch (suggestion.type) {
                    case 'snippet':
                        this._stats.snippetCount++;
                        break;
                    case 'text':
                        this._stats.textCount++;
                        break;
                }
            }
            this._filteredItems.sort(this._snippetCompareFn);
        };
        CompletionModel._compareCompletionItems = function (a, b) {
            if (a.score > b.score) {
                return -1;
            }
            else if (a.score < b.score) {
                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.suggestion.type !== b.suggestion.type) {
                if (a.suggestion.type === 'snippet') {
                    return 1;
                }
                else if (b.suggestion.type === 'snippet') {
                    return -1;
                }
            }
            return CompletionModel._compareCompletionItems(a, b);
        };
        CompletionModel._compareCompletionItemsSnippetsUp = function (a, b) {
            if (a.suggestion.type !== b.suggestion.type) {
                if (a.suggestion.type === 'snippet') {
                    return -1;
                }
                else if (b.suggestion.type === 'snippet') {
                    return 1;
                }
            }
            return CompletionModel._compareCompletionItems(a, b);
        };
        return CompletionModel;
    }());
    exports.CompletionModel = CompletionModel;
});

define(__m[273/*vs/editor/standalone/browser/colorizer*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,17/*vs/editor/common/modes*/,106/*vs/editor/common/viewLayout/viewLineRenderer*/,90/*vs/editor/common/core/viewLineToken*/,130/*vs/editor/common/core/lineTokens*/,9/*vs/base/common/strings*/]), function (require, exports, winjs_base_1, modes_1, viewLineRenderer_1, viewLineToken_1, lineTokens_1, strings) {
    /*---------------------------------------------------------------------------------------------
     *  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 Colorizer = (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 undefined;
            }
            themeService.setTheme(theme);
            var text = domNode.firstChild.nodeValue;
            domNode.className += 'monaco-editor ' + theme;
            var render = function (str) {
                domNode.innerHTML = str;
            };
            return this.colorize(modeService, text, mimeType, options).then(render, function (err) { return console.error(err); }, render);
        };
        Colorizer._tokenizationSupportChangedPromise = function (language) {
            var listener = null;
            var stopListening = function () {
                if (listener) {
                    listener.dispose();
                    listener = null;
                }
            };
            return new winjs_base_1.TPromise(function (c, e, p) {
                listener = modes_1.TokenizationRegistry.onDidChange(function (e) {
                    if (e.changedLanguages.indexOf(language) >= 0) {
                        stopListening();
                        c(void 0);
                    }
                });
            }, stopListening);
        };
        Colorizer.colorize = function (modeService, text, mimeType, options) {
            if (strings.startsWithUTF8BOM(text)) {
                text = text.substr(1);
            }
            var lines = text.split(/\r\n|\r|\n/);
            var language = modeService.getModeId(mimeType);
            options = options || {};
            if (typeof options.tabSize === 'undefined') {
                options.tabSize = 4;
            }
            // Send out the event to create the mode
            modeService.getOrCreateMode(language);
            var tokenizationSupport = modes_1.TokenizationRegistry.get(language);
            if (tokenizationSupport) {
                return winjs_base_1.TPromise.as(_colorize(lines, options.tabSize, tokenizationSupport));
            }
            // wait 500ms for mode to load, then give up
            return winjs_base_1.TPromise.any([this._tokenizationSupportChangedPromise(language), winjs_base_1.TPromise.timeout(500)]).then(function (_) {
                var tokenizationSupport = modes_1.TokenizationRegistry.get(language);
                if (tokenizationSupport) {
                    return _colorize(lines, options.tabSize, tokenizationSupport);
                }
                return _fakeColorize(lines, options.tabSize);
            });
        };
        Colorizer.colorizeLine = function (line, mightContainRTL, tokens, tabSize) {
            if (tabSize === void 0) { tabSize = 4; }
            var renderResult = viewLineRenderer_1.renderViewLine(new viewLineRenderer_1.RenderLineInput(false, line, mightContainRTL, 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.mightContainRTL(), inflatedTokens, tabSize);
        };
        return Colorizer;
    }());
    exports.Colorizer = Colorizer;
    function _colorize(lines, tabSize, tokenizationSupport) {
        return _actualColorize(lines, tabSize, tokenizationSupport);
    }
    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;
        for (var i = 0, length_1 = lines.length; i < length_1; i++) {
            var line = lines[i];
            var renderResult = viewLineRenderer_1.renderViewLine(new viewLineRenderer_1.RenderLineInput(false, line, false, 0, [new viewLineToken_1.ViewLineToken(line.length, defaultMetadata)], [], tabSize, 0, -1, 'none', false, false));
            html = html.concat(renderResult.html);
            html.push('<br/>');
        }
        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);
            var lineTokens = new lineTokens_1.LineTokens(tokenizeResult.tokens, line);
            var renderResult = viewLineRenderer_1.renderViewLine(new viewLineRenderer_1.RenderLineInput(false, line, true /* check for RTL */, 0, lineTokens.inflate(), [], tabSize, 0, -1, 'none', false, false));
            html = html.concat(renderResult.html);
            html.push('<br/>');
            state = tokenizeResult.endState;
        }
        return html.join('');
    }
});

define(__m[145/*vs/editor/standalone/common/monarch/monarchCommon*/], __M([1/*require*/,0/*exports*/]), 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 });
    /*
     * This module exports common types and functionality shared between
     * the Monarch compiler that compiles JSON to ILexer, and the Monarch
     * Tokenizer (that highlights at runtime)
     */
    /*
     * Type definitions to be used internally to Monarch.
     * Inside monarch we use fully typed definitions and compiled versions of the more abstract JSON descriptions.
     */
    var MonarchBracket;
    (function (MonarchBracket) {
        MonarchBracket[MonarchBracket["None"] = 0] = "None";
        MonarchBracket[MonarchBracket["Open"] = 1] = "Open";
        MonarchBracket[MonarchBracket["Close"] = -1] = "Close";
    })(MonarchBracket = exports.MonarchBracket || (exports.MonarchBracket = {}));
    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
    /**
     * Throws error. May actually just log the error and continue.
     */
    function throwError(lexer, msg) {
        throw new Error(lexer.languageId + ": " + msg);
    }
    exports.throwError = throwError;
    // 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) {
                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, state) {
        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, state) {
        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;
});

define(__m[275/*vs/editor/standalone/common/monarch/monarchCompile*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/objects*/,145/*vs/editor/standalone/common/monarch/monarchCommon*/]), function (require, exports, objects, monarchCommon) {
    /*---------------------------------------------------------------------------------------------
     *  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 });
    /*
     * 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;
        }
        var idx;
        for (idx in obj) {
            if (obj.hasOwnProperty(idx)) {
                if (!(elemType(obj[idx]))) {
                    return false;
                }
            }
        }
        return true;
    }
    function bool(prop, def, onerr) {
        if (typeof (prop) === 'boolean') {
            return prop;
        }
        if (onerr && (prop || def === undefined)) {
            onerr(); // type is wrong, or there is no default
        }
        return (def === undefined ? null : def);
    }
    function string(prop, def, onerr) {
        if (typeof (prop) === 'string') {
            return prop;
        }
        if (onerr && (prop || def === undefined)) {
            onerr(); // type is wrong, or there is no default
        }
        return (def === undefined ? null : def);
    }
    // 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) {
        if (typeof (str) !== 'string') {
            return null;
        }
        var n = 0;
        while (str.indexOf('@') >= 0 && n < 5) {
            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) {
                        monarchCommon.throwError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str);
                    }
                    else {
                        monarchCommon.throwError(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]) {
                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)) {
            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 = objects.createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
            tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); };
        }
        else if (op === '@' || op === '!@') {
            var words = lexer[pat];
            if (!words) {
                monarchCommon.throwError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName);
            }
            if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) {
                monarchCommon.throwError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName);
            }
            var inWords = objects.createKeywordMatcher(words, lexer.ignoreCase);
            tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); };
        }
        else if (op === '~' || op === '!~') {
            if (pat.indexOf('$') < 0) {
                // precompile regular expression
                var re = compileRegExp(lexer, '^' + pat + '$');
                tester = function (s) { return (op === '~' ? re.test(s) : !re.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 (pat.indexOf('$') < 0) {
                var patx = monarchCommon.fixCase(lexer, pat);
                tester = function (s) { return (op === '==' ? s === patx : s !== patx); };
            }
            else {
                var patx = monarchCommon.fixCase(lexer, pat);
                tester = function (s, id, matches, state, eos) {
                    var patexp = monarchCommon.substituteMatches(lexer, patx, id, matches, state);
                    return (op === '==' ? s === patexp : s !== patexp);
                };
            }
        }
        // return the branch object
        if (scrut === -1) {
            return {
                name: tkey, value: val, test: function (id, matches, state, eos) {
                    return tester(id, id, matches, state, eos);
                }
            };
        }
        else {
            return {
                name: tkey, value: val, test: function (id, matches, state, eos) {
                    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') {
                monarchCommon.throwError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName);
                return { token: '' };
            }
            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 {
                        monarchCommon.throwError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName);
                    }
                }
                if (action.next) {
                    if (typeof (action.next) !== 'string') {
                        monarchCommon.throwError(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) {
                                if (!monarchCommon.stateExists(lexer, monarchCommon.substituteMatches(lexer, next, '', [], ''))) {
                                    monarchCommon.throwError(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 = [];
            var idx;
            for (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 = [];
            // for each case, push a test function and result value
            var tkey;
            for (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.push({ test: null, value: val, name: tkey });
                    }
                    else if (tkey === '@eos') {
                        cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });
                    }
                    else {
                        cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture
                    }
                }
            }
            // create a matching function
            var def = lexer.defaultToken;
            return {
                test: function (id, matches, state, eos) {
                    var idx;
                    for (idx in cases) {
                        if (cases.hasOwnProperty(idx)) {
                            var didmatch = (!cases[idx].test || cases[idx].test(id, matches, state, eos));
                            if (didmatch) {
                                return cases[idx].value;
                            }
                        }
                    }
                    return def;
                }
            };
        }
        else {
            monarchCommon.throwError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName);
            return '';
        }
    }
    /**
     * Helper class for creating matching rules
     */
    var Rule = (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 {
                monarchCommon.throwError(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 = string(json.start);
        lexer.ignoreCase = bool(json.ignoreCase, false);
        lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);
        lexer.defaultToken = string(json.defaultToken, 'source', function () { monarchCommon.throwError(lexer, 'the \'defaultToken\' must be a string'); });
        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) {
            var idx;
            for (idx in rules) {
                if (rules.hasOwnProperty(idx)) {
                    var rule = rules[idx];
                    var include = rule.include;
                    if (include) {
                        if (typeof (include) !== 'string') {
                            monarchCommon.throwError(lexer, 'an \'include\' attribute must be a string at: ' + state);
                        }
                        if (include[0] === '@') {
                            include = include.substr(1); // peel off starting @
                        }
                        if (!json.tokenizer[include]) {
                            monarchCommon.throwError(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 {
                                    monarchCommon.throwError(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) {
                                monarchCommon.throwError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state);
                            }
                            if (rule.name) {
                                newrule.name = string(rule.name);
                            }
                            if (rule.matchOnlyAtStart) {
                                newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart);
                            }
                            newrule.setRegex(lexerMin, rule.regex);
                            newrule.setAction(lexerMin, rule.action);
                        }
                        newrules.push(newrule);
                    }
                }
            }
        }
        // compile the tokenizer rules
        if (!json.tokenizer || typeof (json.tokenizer) !== 'object') {
            monarchCommon.throwError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object');
        }
        lexer.tokenizer = [];
        var key;
        for (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))) {
                monarchCommon.throwError(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) {
                    monarchCommon.throwError(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') {
                    brackets.push({
                        token: string(desc.token) + lexer.tokenPostfix,
                        open: monarchCommon.fixCase(lexer, string(desc.open)),
                        close: monarchCommon.fixCase(lexer, string(desc.close))
                    });
                }
                else {
                    monarchCommon.throwError(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[276/*vs/editor/standalone/common/monarch/monarchLexer*/], __M([1/*require*/,0/*exports*/,17/*vs/editor/common/modes*/,145/*vs/editor/standalone/common/monarch/monarchCommon*/,97/*vs/editor/common/core/token*/,68/*vs/editor/common/modes/nullMode*/]), function (require, exports, modes, monarchCommon, token_1, nullMode_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CACHE_STACK_DEPTH = 5;
    /**
     * Reuse the same stack elements up to a certain depth.
     */
    var MonarchStackElementFactory = (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 = (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 = (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 = (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 = (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 = (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 = (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 = (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);
            // 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.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) {
                    monarchCommon.throwError(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) {
                monarchCommon.throwError(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._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;
            // regular expression group matching
            // these never need cloning or equality since they are only used within a line match
            var groupActions = null;
            var groupMatches = null;
            var groupMatched = null;
            var groupRule = null;
            while (pos < lineLength) {
                var pos0 = pos;
                var stackLen0 = stack.depth;
                var groupLen0 = groupActions ? groupActions.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 (groupActions) {
                    matches = groupMatches;
                    matched = groupMatched.shift();
                    action = groupActions.shift();
                    rule = groupRule;
                    // cleanup if necessary
                    if (groupActions.length === 0) {
                        groupActions = null;
                        groupMatches = null;
                        groupMatched = null;
                        groupRule = null;
                    }
                }
                else {
                    // otherwise we match on the token stream
                    if (pos >= lineLength) {
                        // nothing to do
                        break;
                    }
                    // 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) {
                            monarchCommon.throwError(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;
                }
                // 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) {
                                monarchCommon.throwError(this._lexer, 'cannot pop embedded mode if not inside one');
                            }
                            embeddedModeData = null;
                        }
                        else if (embeddedModeData) {
                            monarchCommon.throwError(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) {
                        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)) {
                            monarchCommon.throwError(this._lexer, 'trying to switch to a state \'' + nextState + '\' that is undefined in rule: ' + rule.name);
                        }
                        else {
                            stack = stack.switchTo(nextState);
                        }
                    }
                    else if (action.transform && typeof action.transform === 'function') {
                        monarchCommon.throwError(this._lexer, 'action.transform not supported');
                    }
                    else if (action.next) {
                        if (action.next === '@push') {
                            if (stack.depth >= this._lexer.maxStack) {
                                monarchCommon.throwError(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) {
                                monarchCommon.throwError(this._lexer, 'trying to pop an empty stack in rule: ' + rule.name);
                            }
                            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)) {
                                monarchCommon.throwError(this._lexer, 'trying to set a next state \'' + nextState + '\' that is undefined in rule: ' + rule.name);
                            }
                            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) {
                    monarchCommon.throwError(this._lexer, 'lexer rule has no well-defined action in rule: ' + rule.name);
                }
                // is the result a group match?
                if (Array.isArray(result)) {
                    if (groupActions && groupActions.length > 0) {
                        monarchCommon.throwError(this._lexer, 'groups cannot be nested: ' + rule.name);
                    }
                    if (matches.length !== result.length + 1) {
                        monarchCommon.throwError(this._lexer, 'matched number of groups does not match the number of actions in rule: ' + rule.name);
                    }
                    var totalLen = 0;
                    for (var i = 1; i < matches.length; i++) {
                        totalLen += matches[i].length;
                    }
                    if (totalLen !== matched.length) {
                        monarchCommon.throwError(this._lexer, 'with groups, all characters should be matched in consecutive groups in rule: ' + rule.name);
                    }
                    groupMatches = matches;
                    groupMatched = matches.slice(1);
                    groupActions = result.slice(0);
                    groupRule = rule;
                    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 (stackLen0 !== stack.depth || state !== stack.state || (!groupActions ? 0 : groupActions.length) !== groupLen0) {
                            continue;
                        }
                        else {
                            monarchCommon.throwError(this._lexer, 'no progress in tokenizer in rule: ' + rule.name);
                            pos = lineLength; // must make progress or editor loops
                        }
                    }
                    // 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) {
                            monarchCommon.throwError(this._lexer, '@brackets token returned but no bracket defined as: ' + matched);
                            bracket = { token: '', bracketType: 0 /* None */ };
                        }
                        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 nestedMode = this._locateMode(mimetypeOrModeId);
            if (nestedMode) {
                var tokenizationSupport = modes.TokenizationRegistry.get(nestedMode.getId());
                if (tokenizationSupport) {
                    return new EmbeddedModeData(nestedMode.getId(), tokenizationSupport.getInitialState());
                }
            }
            var nestedModeId = nestedMode ? nestedMode.getId() : nullMode_1.NULL_MODE_ID;
            return new EmbeddedModeData(nestedModeId, nullMode_1.NULL_STATE);
        };
        MonarchTokenizer.prototype._locateMode = function (mimetypeOrModeId) {
            if (!mimetypeOrModeId || !this._modeService.isRegisteredMode(mimetypeOrModeId)) {
                return null;
            }
            var modeId = this._modeService.getModeId(mimetypeOrModeId);
            // Fire mode loading event
            this._modeService.getOrCreateMode(modeId);
            var mode = this._modeService.getMode(modeId);
            if (mode) {
                // Re-emit tokenizationSupport change events from all modes that I ever embedded
                this._embeddedModes[modeId] = true;
                return mode;
            }
            this._embeddedModes[modeId] = true;
            return null;
        };
        return 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; i < brackets.length; i++) {
            var bracket = brackets[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;
});

define(__m[427/*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[75/*vs/base/browser/ui/actionbar/actionbar*/], __M([1/*require*/,0/*exports*/,427/*vs/nls!vs/base/browser/ui/actionbar/actionbar*/,3/*vs/base/common/lifecycle*/,52/*vs/base/browser/builder*/,259/*vs/base/browser/ui/selectBox/selectBox*/,53/*vs/base/common/actions*/,4/*vs/base/browser/dom*/,79/*vs/base/common/events*/,29/*vs/base/common/types*/,38/*vs/base/common/eventEmitter*/,74/*vs/base/browser/touch*/,65/*vs/base/browser/keyboardEvent*/,496/*vs/css!vs/base/browser/ui/actionbar/actionbar*/]), function (require, exports, nls, lifecycle, builder_1, selectBox_1, actions_1, DOM, events_1, types, eventEmitter_1, touch_1, keyboardEvent_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var BaseActionItem = (function (_super) {
        __extends(BaseActionItem, _super);
        function BaseActionItem(context, action, options) {
            var _this = _super.call(this) || this;
            _this.options = options;
            _this._callOnDispose = [];
            _this._context = context || _this;
            _this._action = action;
            if (action instanceof actions_1.Action) {
                _this._callOnDispose.push(action.onDidChange(function (event) {
                    if (!_this.builder) {
                        // 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 !== void 0) {
                this._updateEnabled();
            }
            if (event.checked !== void 0) {
                this._updateChecked();
            }
            if (event.class !== void 0) {
                this._updateClass();
            }
            if (event.label !== void 0) {
                this._updateLabel();
                this._updateTooltip();
            }
            if (event.tooltip !== void 0) {
                this._updateTooltip();
            }
        };
        Object.defineProperty(BaseActionItem.prototype, "callOnDispose", {
            get: function () {
                return this._callOnDispose;
            },
            enumerable: true,
            configurable: true
        });
        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.builder = builder_1.$(container);
            this.gesture = new touch_1.Gesture(container);
            var enableDragging = this.options && this.options.draggable;
            if (enableDragging) {
                container.draggable = true;
            }
            this.builder.on(touch_1.EventType.Tap, function (e) { return _this.onClick(e); });
            this.builder.on(DOM.EventType.MOUSE_DOWN, function (e) {
                if (!enableDragging) {
                    DOM.EventHelper.stop(e); // do not run when dragging is on because that would disable it
                }
                if (_this._action.enabled && e.button === 0) {
                    _this.builder.addClass('active');
                }
            });
            this.builder.on(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 {
                    setTimeout(function () { return _this.onClick(e); }, 50);
                }
            });
            this.builder.on([DOM.EventType.MOUSE_UP, DOM.EventType.MOUSE_OUT], function (e) {
                DOM.EventHelper.stop(e);
                _this.builder.removeClass('active');
            });
        };
        BaseActionItem.prototype.onClick = function (event) {
            DOM.EventHelper.stop(event, true);
            var context;
            if (types.isUndefinedOrNull(this._context)) {
                context = event;
            }
            else {
                context = this._context;
                context.event = event;
            }
            this._actionRunner.run(this._action, context);
        };
        BaseActionItem.prototype.focus = function () {
            if (this.builder) {
                this.builder.domFocus();
            }
        };
        BaseActionItem.prototype.blur = function () {
            if (this.builder) {
                this.builder.domBlur();
            }
        };
        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 () {
            _super.prototype.dispose.call(this);
            if (this.builder) {
                this.builder.destroy();
                this.builder = null;
            }
            if (this.gesture) {
                this.gesture.dispose();
                this.gesture = null;
            }
            this._callOnDispose = lifecycle.dispose(this._callOnDispose);
        };
        return BaseActionItem;
    }(eventEmitter_1.EventEmitter));
    exports.BaseActionItem = BaseActionItem;
    var Separator = (function (_super) {
        __extends(Separator, _super);
        function Separator(label, order) {
            var _this = _super.call(this, Separator.ID, label, label ? 'separator text' : 'separator') || this;
            _this.checked = false;
            _this.radio = false;
            _this.enabled = false;
            _this.order = order;
            return _this;
        }
        Separator.ID = 'vs.actions.separator';
        return Separator;
    }(actions_1.Action));
    exports.Separator = Separator;
    var ActionItem = (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);
            this.$e = builder_1.$('a.action-label').appendTo(this.builder);
            if (this._action.id === Separator.ID) {
                // A separator is a presentation item
                this.$e.attr({ role: 'presentation' });
            }
            else {
                if (this.options.isMenu) {
                    this.$e.attr({ role: 'menuitem' });
                }
                else {
                    this.$e.attr({ role: 'button' });
                }
            }
            if (this.options.label && this.options.keybinding) {
                builder_1.$('span.keybinding').text(this.options.keybinding).appendTo(this.builder);
            }
            this._updateClass();
            this._updateLabel();
            this._updateTooltip();
            this._updateEnabled();
            this._updateChecked();
        };
        ActionItem.prototype.focus = function () {
            _super.prototype.focus.call(this);
            this.$e.domFocus();
        };
        ActionItem.prototype._updateLabel = function () {
            if (this.options.label) {
                this.$e.text(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.$e.attr({ title: title });
            }
        };
        ActionItem.prototype._updateClass = function () {
            if (this.cssClass) {
                this.$e.removeClass(this.cssClass);
            }
            if (this.options.icon) {
                this.cssClass = this.getAction().class;
                this.$e.addClass('icon');
                if (this.cssClass) {
                    this.$e.addClass(this.cssClass);
                }
                this._updateEnabled();
            }
            else {
                this.$e.removeClass('icon');
            }
        };
        ActionItem.prototype._updateEnabled = function () {
            if (this.getAction().enabled) {
                this.builder.removeClass('disabled');
                this.$e.removeClass('disabled');
                this.$e.attr({ tabindex: 0 });
            }
            else {
                this.builder.addClass('disabled');
                this.$e.addClass('disabled');
                DOM.removeTabIndexAndUpdateFocus(this.$e.getHTMLElement());
            }
        };
        ActionItem.prototype._updateChecked = function () {
            if (this.getAction().checked) {
                this.$e.addClass('checked');
            }
            else {
                this.$e.removeClass('checked');
            }
        };
        ActionItem.prototype._updateRadio = function () {
            if (this.getAction().radio) {
                this.$e.addClass('radio');
            }
            else {
                this.$e.removeClass('radio');
            }
        };
        return ActionItem;
    }(BaseActionItem));
    exports.ActionItem = ActionItem;
    var ActionsOrientation;
    (function (ActionsOrientation) {
        ActionsOrientation[ActionsOrientation["HORIZONTAL"] = 1] = "HORIZONTAL";
        ActionsOrientation[ActionsOrientation["VERTICAL"] = 2] = "VERTICAL";
    })(ActionsOrientation = exports.ActionsOrientation || (exports.ActionsOrientation = {}));
    var defaultOptions = {
        orientation: ActionsOrientation.HORIZONTAL,
        context: null
    };
    var ActionBar = (function (_super) {
        __extends(ActionBar, _super);
        function ActionBar(container, options) {
            if (options === void 0) { options = defaultOptions; }
            var _this = _super.call(this) || this;
            _this.options = options;
            _this._context = options.context;
            _this.toDispose = [];
            _this._actionRunner = _this.options.actionRunner;
            if (!_this._actionRunner) {
                _this._actionRunner = new actions_1.ActionRunner();
                _this.toDispose.push(_this._actionRunner);
            }
            _this.toDispose.push(_this.addEmitter(_this._actionRunner));
            _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 isVertical = _this.options.orientation === ActionsOrientation.VERTICAL;
            if (isVertical) {
                _this.domNode.className += ' vertical';
            }
            builder_1.$(_this.domNode).on(DOM.EventType.KEY_DOWN, function (e) {
                var event = new keyboardEvent_1.StandardKeyboardEvent(e);
                var eventHandled = true;
                if (event.equals(isVertical ? 16 /* UpArrow */ : 15 /* LeftArrow */)) {
                    _this.focusPrevious();
                }
                else if (event.equals(isVertical ? 18 /* DownArrow */ : 17 /* RightArrow */)) {
                    _this.focusNext();
                }
                else if (event.equals(9 /* Escape */)) {
                    _this.cancel();
                }
                else if (event.equals(3 /* Enter */) || event.equals(10 /* Space */)) {
                    // Nothing, just staying out of the else branch
                }
                else {
                    eventHandled = false;
                }
                if (eventHandled) {
                    event.preventDefault();
                    event.stopPropagation();
                }
            });
            builder_1.$(_this.domNode).on(DOM.EventType.KEY_UP, function (e) {
                var event = new keyboardEvent_1.StandardKeyboardEvent(e);
                // Run action on Enter/Space
                if (event.equals(3 /* Enter */) || event.equals(10 /* Space */)) {
                    _this.doTrigger(event);
                    event.preventDefault();
                    event.stopPropagation();
                }
                else if (event.equals(2 /* Tab */) || event.equals(1024 /* Shift */ | 2 /* Tab */)) {
                    _this.updateFocusedItem();
                }
            });
            _this.focusTracker = DOM.trackFocus(_this.domNode);
            _this.focusTracker.addBlurListener(function () {
                if (document.activeElement === _this.domNode || !DOM.isAncestor(document.activeElement, _this.domNode)) {
                    _this.emit(DOM.EventType.BLUR, {});
                    _this.focusedItem = undefined;
                }
            });
            _this.focusTracker.addFocusListener(function () { return _this.updateFocusedItem(); });
            _this.actionsList = document.createElement('ul');
            _this.actionsList.className = 'actions-container';
            if (_this.options.isMenu) {
                _this.actionsList.setAttribute('role', 'menubar');
            }
            else {
                _this.actionsList.setAttribute('role', 'toolbar');
            }
            if (_this.options.ariaLabel) {
                _this.actionsList.setAttribute('aria-label', _this.options.ariaLabel);
            }
            _this.domNode.appendChild(_this.actionsList);
            ((container instanceof builder_1.Builder) ? container.getHTMLElement() : container).appendChild(_this.domNode);
            return _this;
        }
        ActionBar.prototype.setAriaLabel = function (label) {
            if (label) {
                this.actionsList.setAttribute('aria-label', label);
            }
            else {
                this.actionsList.removeAttribute('aria-label');
            }
        };
        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
        });
        Object.defineProperty(ActionBar.prototype, "actionRunner", {
            get: function () {
                return this._actionRunner;
            },
            set: function (actionRunner) {
                if (actionRunner) {
                    this._actionRunner = actionRunner;
                    this.items.forEach(function (item) { return item.actionRunner = actionRunner; });
                }
            },
            enumerable: true,
            configurable: true
        });
        ActionBar.prototype.getContainer = function () {
            return builder_1.$(this.domNode);
        };
        ActionBar.prototype.push = function (arg, options) {
            var _this = this;
            if (options === void 0) { options = {}; }
            var actions = !Array.isArray(arg) ? [arg] : arg;
            var index = types.isNumber(options.index) ? options.index : null;
            actions.forEach(function (action) {
                var actionItemElement = document.createElement('li');
                actionItemElement.className = 'action-item';
                actionItemElement.setAttribute('role', 'presentation');
                // Prevent native context menu on actions
                builder_1.$(actionItemElement).on(DOM.EventType.CONTEXT_MENU, function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                });
                var item = null;
                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);
                _this.addEmitter(item);
                item.render(actionItemElement);
                if (index === null || index < 0 || index >= _this.actionsList.children.length) {
                    _this.actionsList.appendChild(actionItemElement);
                }
                else {
                    _this.actionsList.insertBefore(actionItemElement, _this.actionsList.children[index++]);
                }
                _this.items.push(item);
            });
        };
        ActionBar.prototype.pull = function (index) {
            if (index >= 0 && index < this.items.length) {
                this.items.splice(index, 1);
                this.actionsList.removeChild(this.actionsList.childNodes[index]);
            }
        };
        ActionBar.prototype.clear = function () {
            this.items = lifecycle.dispose(this.items);
            builder_1.$(this.actionsList).empty();
        };
        ActionBar.prototype.length = function () {
            return this.items.length;
        };
        ActionBar.prototype.isEmpty = function () {
            return this.items.length === 0;
        };
        ActionBar.prototype.focus = function (selectFirst) {
            if (selectFirst && typeof this.focusedItem === 'undefined') {
                this.focusedItem = 0;
            }
            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.domNode.focus();
                return;
            }
            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.focus)) {
                        actionItem.focus(fromRight);
                    }
                }
                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).done();
            }
        };
        ActionBar.prototype.cancel = function () {
            if (document.activeElement instanceof HTMLElement) {
                document.activeElement.blur(); // remove focus from focussed action
            }
            this.emit(events_1.EventType.CANCEL);
        };
        ActionBar.prototype.run = function (action, context) {
            return this._actionRunner.run(action, context);
        };
        ActionBar.prototype.dispose = function () {
            if (this.items !== null) {
                lifecycle.dispose(this.items);
            }
            this.items = null;
            if (this.focusTracker) {
                this.focusTracker.dispose();
                this.focusTracker = null;
            }
            this.toDispose = lifecycle.dispose(this.toDispose);
            this.getContainer().destroy();
            _super.prototype.dispose.call(this);
        };
        return ActionBar;
    }(eventEmitter_1.EventEmitter));
    exports.ActionBar = ActionBar;
    var SelectActionItem = (function (_super) {
        __extends(SelectActionItem, _super);
        function SelectActionItem(ctx, action, options, selected) {
            var _this = _super.call(this, ctx, action) || this;
            _this.selectBox = new selectBox_1.SelectBox(options, selected);
            _this.toDispose = [];
            _this.toDispose.push(_this.selectBox);
            _this.registerListeners();
            return _this;
        }
        SelectActionItem.prototype.setOptions = function (options, selected) {
            this.selectBox.setOptions(options, selected);
        };
        SelectActionItem.prototype.select = function (index) {
            this.selectBox.select(index);
        };
        SelectActionItem.prototype.registerListeners = function () {
            var _this = this;
            this.toDispose.push(this.selectBox.onDidSelect(function (e) {
                _this.actionRunner.run(_this._action, _this.getActionContext(e.selected)).done();
            }));
        };
        SelectActionItem.prototype.getActionContext = function (option) {
            return option;
        };
        SelectActionItem.prototype.focus = function () {
            if (this.selectBox) {
                this.selectBox.focus();
            }
        };
        SelectActionItem.prototype.blur = function () {
            if (this.selectBox) {
                this.selectBox.blur();
            }
        };
        SelectActionItem.prototype.render = function (container) {
            this.selectBox.render(container);
        };
        SelectActionItem.prototype.dispose = function () {
            this.toDispose = lifecycle.dispose(this.toDispose);
            _super.prototype.dispose.call(this);
        };
        return SelectActionItem;
    }(BaseActionItem));
    exports.SelectActionItem = SelectActionItem;
});

/*---------------------------------------------------------------------------------------------
 *  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/menu/menu*/], __M([1/*require*/,0/*exports*/,52/*vs/base/browser/builder*/,75/*vs/base/browser/ui/actionbar/actionbar*/,38/*vs/base/common/eventEmitter*/,218/*vs/css!vs/base/browser/ui/menu/menu*/]), function (require, exports, builder_1, actionbar_1, eventEmitter_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var Menu = (function (_super) {
        __extends(Menu, _super);
        function Menu(container, actions, options) {
            if (options === void 0) { options = {}; }
            var _this = _super.call(this) || this;
            builder_1.$(container).addClass('monaco-menu-container');
            var $menu = builder_1.$('.monaco-menu').appendTo(container);
            _this.actionBar = new actionbar_1.ActionBar($menu, {
                orientation: actionbar_1.ActionsOrientation.VERTICAL,
                actionItemProvider: options.actionItemProvider,
                context: options.context,
                actionRunner: options.actionRunner,
                isMenu: true
            });
            _this.listener = _this.addEmitter(_this.actionBar);
            _this.actionBar.push(actions, { icon: true, label: true });
            return _this;
        }
        Menu.prototype.focus = function () {
            this.actionBar.focus(true);
        };
        Menu.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            if (this.actionBar) {
                this.actionBar.dispose();
                this.actionBar = null;
            }
            if (this.listener) {
                this.listener.dispose();
                this.listener = null;
            }
        };
        return Menu;
    }(eventEmitter_1.EventEmitter));
    exports.Menu = Menu;
});

define(__m[282/*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[51/*vs/base/browser/ui/aria/aria*/], __M([1/*require*/,0/*exports*/,282/*vs/nls!vs/base/browser/ui/aria/aria*/,15/*vs/base/common/platform*/,4/*vs/base/browser/dom*/,500/*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) {
        insertMessage(alertContainer, msg);
    }
    exports.alert = alert;
    /**
     * Given the provided message, will make sure that it is read as status to screen readers.
     */
    function status(msg) {
        if (platform_1.isMacintosh) {
            alert(msg); // VoiceOver does not seem to support status role
        }
        else {
            insertMessage(statusContainer, msg);
        }
    }
    exports.status = status;
    function insertMessage(target, msg) {
        if (!ariaContainer) {
            // console.warn('ARIA support needs a container. Call setARIAContainer() first.');
            return;
        }
        if (target.textContent === msg) {
            msg = nls.localize(0, null, msg);
        }
        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[284/*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[285/*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); });










define(__m[153/*vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([1/*require*/,0/*exports*/,285/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/,506/*vs/base/browser/ui/checkbox/checkbox*/,206/*vs/css!vs/base/browser/ui/findinput/findInputCheckboxes*/]), function (require, exports, nls, checkbox_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var 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 = (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,
                onChange: opts.onChange,
                onKeyDown: opts.onKeyDown,
                inputActiveOptionBorder: opts.inputActiveOptionBorder
            }) || this;
        }
        return CaseSensitiveCheckbox;
    }(checkbox_1.Checkbox));
    exports.CaseSensitiveCheckbox = CaseSensitiveCheckbox;
    var WholeWordsCheckbox = (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,
                onChange: opts.onChange,
                onKeyDown: opts.onKeyDown,
                inputActiveOptionBorder: opts.inputActiveOptionBorder
            }) || this;
        }
        return WholeWordsCheckbox;
    }(checkbox_1.Checkbox));
    exports.WholeWordsCheckbox = WholeWordsCheckbox;
    var RegexCheckbox = (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,
                onChange: opts.onChange,
                onKeyDown: opts.onKeyDown,
                inputActiveOptionBorder: opts.inputActiveOptionBorder
            }) || this;
        }
        return RegexCheckbox;
    }(checkbox_1.Checkbox));
    exports.RegexCheckbox = RegexCheckbox;
});

define(__m[287/*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); });










define(__m[115/*vs/base/browser/ui/inputbox/inputBox*/], __M([1/*require*/,0/*exports*/,287/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/,28/*vs/base/browser/browser*/,4/*vs/base/browser/dom*/,102/*vs/base/browser/htmlContentRenderer*/,51/*vs/base/browser/ui/aria/aria*/,75/*vs/base/browser/ui/actionbar/actionbar*/,160/*vs/base/browser/ui/contextview/contextview*/,11/*vs/base/common/event*/,41/*vs/base/browser/ui/widget*/,32/*vs/base/common/color*/,26/*vs/base/common/objects*/,211/*vs/css!vs/base/browser/ui/inputbox/inputBox*/]), function (require, exports, nls, Bal, dom, htmlContentRenderer_1, aria, actionbar_1, contextview_1, event_1, widget_1, color_1, objects_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var $ = dom.$;
    var MessageType;
    (function (MessageType) {
        MessageType[MessageType["INFO"] = 1] = "INFO";
        MessageType[MessageType["WARNING"] = 2] = "WARNING";
        MessageType[MessageType["ERROR"] = 3] = "ERROR";
    })(MessageType = exports.MessageType || (exports.MessageType = {}));
    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 = (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.onDidHeightChange = _this._onDidHeightChange.event;
            _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.inputValidationWarningBorder = _this.options.inputValidationWarningBorder;
            _this.inputValidationWarningBackground = _this.options.inputValidationWarningBackground;
            _this.inputValidationErrorBorder = _this.options.inputValidationErrorBorder;
            _this.inputValidationErrorBackground = _this.options.inputValidationErrorBackground;
            if (_this.options.validationOptions) {
                _this.validation = _this.options.validationOptions.validation;
                _this.showValidationMessage = _this.options.validationOptions.showMessage || false;
            }
            _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'));
            }
            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.input.setAttribute('placeholder', _this.placeholder);
                _this.input.title = _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 () { 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);
            }
        };
        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');
                }
            }
        };
        InputBox.prototype.setContextViewProvider = function (contextViewProvider) {
            this.contextViewProvider = contextViewProvider;
        };
        Object.defineProperty(InputBox.prototype, "inputElement", {
            get: function () {
                return this.input;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(InputBox.prototype, "value", {
            get: function () {
                return this.input.value;
            },
            set: function (newValue) {
                if (this.input.value !== newValue) {
                    this.input.value = newValue;
                    this.onValueChange();
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(InputBox.prototype, "height", {
            get: function () {
                return this.cachedHeight === null ? dom.getTotalHeight(this.element) : this.cachedHeight;
            },
            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';
            },
            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 === MessageType.ERROR) {
                alertText = nls.localize(0, null, message.content);
            }
            else if (message.type === MessageType.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.isInputValid = function () {
            return !!this.validation && !this.validation(this.value);
        };
        InputBox.prototype.validate = function () {
            var result = null;
            if (this.validation) {
                result = this.validation(this.value);
                if (!result) {
                    this.inputElement.removeAttribute('aria-invalid');
                    this.hideMessage();
                }
                else {
                    this.inputElement.setAttribute('aria-invalid', 'true');
                    this.showMessage(result);
                }
            }
            return !result;
        };
        InputBox.prototype.stylesForType = function (type) {
            switch (type) {
                case MessageType.INFO: return { border: this.inputValidationInfoBorder, background: this.inputValidationInfoBackground };
                case MessageType.WARNING: return { border: this.inputValidationWarningBorder, background: this.inputValidationWarningBackground };
                default: return { border: this.inputValidationErrorBorder, background: this.inputValidationErrorBackground };
            }
        };
        InputBox.prototype.classForType = function (type) {
            switch (type) {
                case MessageType.INFO: return 'info';
                case MessageType.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: contextview_1.AnchorAlignment.RIGHT,
                render: function (container) {
                    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.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.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 ? ' ' : '';
            this.mirror.textContent = value + suffix;
            this.layout();
        };
        InputBox.prototype.style = function (styles) {
            this.inputBackground = styles.inputBackground;
            this.inputForeground = styles.inputForeground;
            this.inputBorder = styles.inputBorder;
            this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
            this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
            this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
            this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
            this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
            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;
            this.input = null;
            this.contextViewProvider = null;
            this.message = null;
            this.placeholder = null;
            this.ariaLabel = null;
            this.validation = null;
            this.showValidationMessage = null;
            this.state = null;
            this.actionbar = null;
            _super.prototype.dispose.call(this);
        };
        return InputBox;
    }(widget_1.Widget));
    exports.InputBox = InputBox;
});











define(__m[289/*vs/base/browser/ui/findinput/findInput*/], __M([1/*require*/,0/*exports*/,284/*vs/nls!vs/base/browser/ui/findinput/findInput*/,4/*vs/base/browser/dom*/,115/*vs/base/browser/ui/inputbox/inputBox*/,41/*vs/base/browser/ui/widget*/,11/*vs/base/common/event*/,153/*vs/base/browser/ui/findinput/findInputCheckboxes*/,205/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, nls, dom, inputBox_1, widget_1, event_1, findInputCheckboxes_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var NLS_DEFAULT_LABEL = nls.localize(0, null);
    var FindInput = (function (_super) {
        __extends(FindInput, _super);
        function FindInput(parent, contextViewProvider, options) {
            var _this = _super.call(this) || this;
            _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.onInput = _this._onInput.event;
            _this._onKeyUp = _this._register(new event_1.Emitter());
            _this.onKeyUp = _this._onKeyUp.event;
            _this._onCaseSensitiveKeyDown = _this._register(new event_1.Emitter());
            _this.onCaseSensitiveKeyDown = _this._onCaseSensitiveKeyDown.event;
            _this._lastHighlightFindOptions = 0;
            _this.contextViewProvider = contextViewProvider;
            _this.width = options.width || 100;
            _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.inputValidationWarningBorder = options.inputValidationWarningBorder;
            _this.inputValidationWarningBackground = options.inputValidationWarningBackground;
            _this.inputValidationErrorBorder = options.inputValidationErrorBorder;
            _this.inputValidationErrorBackground = options.inputValidationErrorBackground;
            _this.regex = null;
            _this.wholeWords = null;
            _this.caseSensitive = null;
            _this.domNode = null;
            _this.inputBox = null;
            _this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '');
            if (Boolean(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.setEnabled = function (enabled) {
            if (enabled) {
                this.enable();
            }
            else {
                this.disable();
            }
        };
        FindInput.prototype.clear = function () {
            this.clearValidation();
            this.setValue('');
            this.focus();
        };
        FindInput.prototype.setWidth = function (newWidth) {
            this.width = newWidth;
            this.domNode.style.width = this.width + 'px';
            this.contextViewProvider.layout();
            this.setInputWidth();
        };
        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.inputValidationInfoBorder = styles.inputValidationInfoBorder;
            this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
            this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
            this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
            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,
                    inputValidationInfoBorder: this.inputValidationInfoBorder,
                    inputValidationWarningBackground: this.inputValidationWarningBackground,
                    inputValidationWarningBorder: this.inputValidationWarningBorder,
                    inputValidationErrorBackground: this.inputValidationErrorBackground,
                    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;
            this.setInputWidth();
        };
        FindInput.prototype.getWholeWords = function () {
            return this.wholeWords.checked;
        };
        FindInput.prototype.setWholeWords = function (value) {
            this.wholeWords.checked = value;
            this.setInputWidth();
        };
        FindInput.prototype.getRegex = function () {
            return this.regex.checked;
        };
        FindInput.prototype.setRegex = function (value) {
            this.regex.checked = value;
            this.setInputWidth();
        };
        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.setInputWidth = function () {
            var w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();
            this.inputBox.width = w;
        };
        FindInput.prototype.buildDomNode = function (appendCaseSensitiveLabel, appendWholeWordsLabel, appendRegexLabel) {
            var _this = this;
            this.domNode = document.createElement('div');
            this.domNode.style.width = this.width + 'px';
            dom.addClass(this.domNode, 'monaco-findInput');
            this.inputBox = this._register(new inputBox_1.InputBox(this.domNode, this.contextViewProvider, {
                placeholder: this.placeholder || '',
                ariaLabel: this.label || '',
                validationOptions: {
                    validation: this.validation || null,
                    showMessage: true
                },
                inputBackground: this.inputBackground,
                inputForeground: this.inputForeground,
                inputBorder: this.inputBorder,
                inputValidationInfoBackground: this.inputValidationInfoBackground,
                inputValidationInfoBorder: this.inputValidationInfoBorder,
                inputValidationWarningBackground: this.inputValidationWarningBackground,
                inputValidationWarningBorder: this.inputValidationWarningBorder,
                inputValidationErrorBackground: this.inputValidationErrorBackground,
                inputValidationErrorBorder: this.inputValidationErrorBorder
            }));
            this.regex = this._register(new findInputCheckboxes_1.RegexCheckbox({
                appendTitle: appendRegexLabel,
                isChecked: false,
                onChange: function (viaKeyboard) {
                    _this._onDidOptionChange.fire(viaKeyboard);
                    if (!viaKeyboard) {
                        _this.inputBox.focus();
                    }
                    _this.setInputWidth();
                    _this.validate();
                },
                inputActiveOptionBorder: this.inputActiveOptionBorder
            }));
            this.wholeWords = this._register(new findInputCheckboxes_1.WholeWordsCheckbox({
                appendTitle: appendWholeWordsLabel,
                isChecked: false,
                onChange: function (viaKeyboard) {
                    _this._onDidOptionChange.fire(viaKeyboard);
                    if (!viaKeyboard) {
                        _this.inputBox.focus();
                    }
                    _this.setInputWidth();
                    _this.validate();
                },
                inputActiveOptionBorder: this.inputActiveOptionBorder
            }));
            this.caseSensitive = this._register(new findInputCheckboxes_1.CaseSensitiveCheckbox({
                appendTitle: appendCaseSensitiveLabel,
                isChecked: false,
                onChange: function (viaKeyboard) {
                    _this._onDidOptionChange.fire(viaKeyboard);
                    if (!viaKeyboard) {
                        _this.inputBox.focus();
                    }
                    _this.setInputWidth();
                    _this.validate();
                },
                onKeyDown: function (e) {
                    _this._onCaseSensitiveKeyDown.fire(e);
                },
                inputActiveOptionBorder: this.inputActiveOptionBorder
            }));
            // 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 = void 0;
                        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);
                    }
                }
            });
            this.setInputWidth();
            var controls = document.createElement('div');
            controls.className = 'controls';
            controls.appendChild(this.caseSensitive.domNode);
            controls.appendChild(this.wholeWords.domNode);
            controls.appendChild(this.regex.domNode);
            this.domNode.appendChild(controls);
        };
        FindInput.prototype.validate = function () {
            this.inputBox.validate();
        };
        FindInput.prototype.showMessage = function (message) {
            this.inputBox.showMessage(message);
        };
        FindInput.prototype.clearMessage = function () {
            this.inputBox.hideMessage();
        };
        FindInput.prototype.clearValidation = function () {
            this.inputBox.hideMessage();
        };
        FindInput.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
        };
        FindInput.OPTION_CHANGE = 'optionChange';
        return FindInput;
    }(widget_1.Widget));
    exports.FindInput = FindInput;
});

define(__m[290/*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[155/*vs/base/common/keybindingLabels*/], __M([1/*require*/,0/*exports*/,290/*vs/nls!vs/base/common/keybindingLabels*/]), function (require, exports, nls) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ModifierLabelProvider = (function () {
        function ModifierLabelProvider(mac, windows, linux) {
            if (linux === void 0) { linux = windows; }
            this.modifierLabels = [null];
            this.modifierLabels[2 /* Macintosh */] = mac;
            this.modifierLabels[1 /* Windows */] = windows;
            this.modifierLabels[3 /* Linux */] = linux;
        }
        ModifierLabelProvider.prototype.toLabel = function (firstPartMod, firstPartKey, chordPartMod, chordPartKey, OS) {
            if (firstPartKey === null && chordPartKey === null) {
                return null;
            }
            return _asString(firstPartMod, firstPartKey, chordPartMod, chordPartKey, this.modifierLabels[OS]);
        };
        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: '+',
    });
    /**
     * A label provider that prints modifiers in a suitable format for ARIA.
     */
    exports.AriaLabelProvider = new ModifierLabelProvider({
        ctrlKey: nls.localize(4, null),
        shiftKey: nls.localize(5, null),
        altKey: nls.localize(6, null),
        metaKey: nls.localize(7, null),
        separator: '+',
    }, {
        ctrlKey: nls.localize(8, null),
        shiftKey: nls.localize(9, null),
        altKey: nls.localize(10, null),
        metaKey: nls.localize(11, null),
        separator: '+',
    });
    /**
     * A label provider that prints modifiers in a suitable format for Electron Accelerators.
     * See https://github.com/electron/electron/blob/master/docs/api/accelerator.md
     */
    exports.ElectronAcceleratorLabelProvider = new ModifierLabelProvider({
        ctrlKey: 'Ctrl',
        shiftKey: 'Shift',
        altKey: 'Alt',
        metaKey: 'Cmd',
        separator: '+',
    }, {
        ctrlKey: 'Ctrl',
        shiftKey: 'Shift',
        altKey: 'Alt',
        metaKey: 'Super',
        separator: '+',
    });
    /**
     * A label provider that prints modifiers in a suitable format for user settings.
     */
    exports.UserSettingsLabelProvider = new ModifierLabelProvider({
        ctrlKey: 'ctrl',
        shiftKey: 'shift',
        altKey: 'alt',
        metaKey: 'cmd',
        separator: '+',
    }, {
        ctrlKey: 'ctrl',
        shiftKey: 'shift',
        altKey: 'alt',
        metaKey: 'win',
        separator: '+',
    }, {
        ctrlKey: 'ctrl',
        shiftKey: 'shift',
        altKey: 'alt',
        metaKey: 'meta',
        separator: '+',
    });
    function _simpleAsString(modifiers, key, labels) {
        if (key === null) {
            return '';
        }
        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);
    }
    function _asString(firstPartMod, firstPartKey, chordPartMod, chordPartKey, labels) {
        var result = _simpleAsString(firstPartMod, firstPartKey, labels);
        if (chordPartKey !== null) {
            result += ' ';
            result += _simpleAsString(chordPartMod, chordPartKey, labels);
        }
        return result;
    }
});

define(__m[292/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/objects*/,155/*vs/base/common/keybindingLabels*/,4/*vs/base/browser/dom*/,212/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/]), function (require, exports, objects_1, keybindingLabels_1, dom) {
    /*---------------------------------------------------------------------------------------------
     *  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 $ = dom.$;
    var KeybindingLabel = (function () {
        function KeybindingLabel(container, os) {
            this.os = os;
            this.domNode = dom.append(container, $('.monaco-keybinding'));
            this.didEverRender = false;
            container.appendChild(this.domNode);
        }
        Object.defineProperty(KeybindingLabel.prototype, "element", {
            get: function () {
                return this.domNode;
            },
            enumerable: true,
            configurable: true
        });
        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', null, ' '));
                    this.renderPart(this.domNode, chordPart, this.matches ? this.matches.chordPart : null);
                }
                this.domNode.title = this.keybinding.getAriaLabel();
            }
            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, match && match.ctrlKey, modifierLabels.separator);
            }
            if (part.shiftKey) {
                this.renderKey(parent, modifierLabels.shiftKey, match && match.shiftKey, modifierLabels.separator);
            }
            if (part.altKey) {
                this.renderKey(parent, modifierLabels.altKey, match && match.altKey, modifierLabels.separator);
            }
            if (part.metaKey) {
                this.renderKey(parent, modifierLabels.metaKey, match && match.metaKey, modifierLabels.separator);
            }
            var keyLabel = part.keyLabel;
            if (keyLabel) {
                this.renderKey(parent, keyLabel, match && match.keyCode, '');
            }
        };
        KeybindingLabel.prototype.renderKey = function (parent, label, highlight, separator) {
            dom.append(parent, $('span.monaco-keybinding-key' + (highlight ? '.highlight' : ''), null, label));
            if (separator) {
                dom.append(parent, $('span.monaco-keybinding-key-separator', null, separator));
            }
        };
        KeybindingLabel.prototype.dispose = function () {
            this.keybinding = 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[293/*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); });
define(__m[36/*vs/base/common/severity*/], __M([1/*require*/,0/*exports*/,293/*vs/nls!vs/base/common/severity*/,9/*vs/base/common/strings*/]), function (require, exports, nls, strings) {
    /*---------------------------------------------------------------------------------------------
     *  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 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', _warning = 'warning', _warn = 'warn', _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;
        function toString(value) {
            return _displayStrings[value] || strings.empty;
        }
        Severity.toString = toString;
        function compare(a, b) {
            return b - a;
        }
        Severity.compare = compare;
    })(Severity || (Severity = {}));
    exports.default = Severity;
});

define(__m[295/*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([1/*require*/,0/*exports*/,295/*vs/nls!vs/base/parts/quickopen/browser/quickOpenModel*/,7/*vs/base/common/winjs.base*/,29/*vs/base/common/types*/,81/*vs/base/common/filters*/,9/*vs/base/common/strings*/,45/*vs/base/common/paths*/,162/*vs/base/browser/ui/iconLabel/iconLabel*/,229/*vs/base/common/comparers*/,75/*vs/base/browser/ui/actionbar/actionbar*/,110/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,4/*vs/base/browser/dom*/,292/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/,15/*vs/base/common/platform*/]), function (require, exports, nls, winjs_base_1, types, filters, strings, paths, iconLabel_1, comparers_1, actionbar_1, highlightedLabel_1, DOM, keybindingLabel_1, platform_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var IDS = 0;
    var EntryAccessor = (function () {
        function EntryAccessor() {
        }
        EntryAccessor.getLabel = function (entry) {
            return entry.getLabel();
        };
        EntryAccessor.getResourcePath = function (entry) {
            var resource = entry.getResource();
            return resource && resource.fsPath;
        };
        return EntryAccessor;
    }());
    var QuickOpenEntry = (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 this.getLabel();
        };
        /**
         * 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;
        };
        /**
         * An optional keybinding to show for an entry.
         */
        QuickOpenEntry.prototype.getKeybinding = function () {
            return null;
        };
        /**
         * A resource for this entry. Resource URIs can be used to compare different kinds of entries and group
         * them together.
         */
        QuickOpenEntry.prototype.getResource = 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 reuse the same model while filtering. Hidden entries will not show up in the viewer.
         */
        QuickOpenEntry.prototype.setHidden = function (hidden) {
            this.hidden = 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;
        };
        /**
         * A good default sort implementation for quick open entries respecting highlight information
         * as well as associated resources.
         */
        QuickOpenEntry.compare = function (elementA, elementB, lookFor) {
            // Give matches with label highlights higher priority over
            // those with only description highlights
            var labelHighlightsA = elementA.getHighlights()[0] || [];
            var labelHighlightsB = elementB.getHighlights()[0] || [];
            if (labelHighlightsA.length && !labelHighlightsB.length) {
                return -1;
            }
            else if (!labelHighlightsA.length && labelHighlightsB.length) {
                return 1;
            }
            // Fallback to the full path if labels are identical and we have associated resources
            var nameA = elementA.getLabel();
            var nameB = elementB.getLabel();
            if (nameA === nameB) {
                var resourceA = elementA.getResource();
                var resourceB = elementB.getResource();
                if (resourceA && resourceB) {
                    nameA = resourceA.fsPath;
                    nameB = resourceB.fsPath;
                }
            }
            return comparers_1.compareAnything(nameA, nameB, lookFor);
        };
        QuickOpenEntry.compareByScore = function (elementA, elementB, lookFor, lookForNormalizedLower, scorerCache) {
            return comparers_1.compareByScore(elementA, elementB, EntryAccessor, lookFor, lookForNormalizedLower, scorerCache);
        };
        /**
         * A good default highlight implementation for an entry with label and description.
         */
        QuickOpenEntry.highlight = function (entry, lookFor, fuzzyHighlight) {
            if (fuzzyHighlight === void 0) { fuzzyHighlight = false; }
            var labelHighlights = [];
            var descriptionHighlights = [];
            var normalizedLookFor = strings.stripWildcards(lookFor);
            var label = entry.getLabel();
            var description = entry.getDescription();
            // Highlight file aware
            if (entry.getResource()) {
                // Highlight entire label and description if searching for full absolute path
                var fsPath = entry.getResource().fsPath;
                if (lookFor.length === fsPath.length && lookFor.toLowerCase() === fsPath.toLowerCase()) {
                    labelHighlights.push({ start: 0, end: label.length });
                    descriptionHighlights.push({ start: 0, end: description.length });
                }
                else if (fuzzyHighlight || lookFor.indexOf(paths.nativeSep) >= 0) {
                    var candidateLabelHighlights = filters.matchesFuzzy(lookFor, label, fuzzyHighlight);
                    if (!candidateLabelHighlights) {
                        var pathPrefix = description ? (description + paths.nativeSep) : '';
                        var pathPrefixLength_1 = pathPrefix.length;
                        // If there are no highlights in the label, build a path out of description and highlight and match on both,
                        // then extract the individual label and description highlights back to the original positions
                        var pathHighlights = filters.matchesFuzzy(lookFor, pathPrefix + label, fuzzyHighlight);
                        if (!pathHighlights && lookFor !== normalizedLookFor) {
                            pathHighlights = filters.matchesFuzzy(normalizedLookFor, pathPrefix + label, fuzzyHighlight);
                        }
                        if (pathHighlights) {
                            pathHighlights.forEach(function (h) {
                                // Match overlaps label and description part, we need to split it up
                                if (h.start < pathPrefixLength_1 && h.end > pathPrefixLength_1) {
                                    labelHighlights.push({ start: 0, end: h.end - pathPrefixLength_1 });
                                    descriptionHighlights.push({ start: h.start, end: pathPrefixLength_1 });
                                }
                                else if (h.start >= pathPrefixLength_1) {
                                    labelHighlights.push({ start: h.start - pathPrefixLength_1, end: h.end - pathPrefixLength_1 });
                                }
                                else {
                                    descriptionHighlights.push(h);
                                }
                            });
                        }
                    }
                    else {
                        labelHighlights = candidateLabelHighlights;
                    }
                }
                else {
                    labelHighlights = filters.matchesFuzzy(lookFor, label);
                }
            }
            else {
                labelHighlights = filters.matchesFuzzy(lookFor, label);
            }
            return { labelHighlights: labelHighlights, descriptionHighlights: descriptionHighlights };
        };
        QuickOpenEntry.prototype.isFile = function () {
            return false; // TODO@Ben debt with editor history merging
        };
        return QuickOpenEntry;
    }());
    exports.QuickOpenEntry = QuickOpenEntry;
    var QuickOpenEntryGroup = (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.getResource = function () {
            return this.entry ? this.entry.getResource() : _super.prototype.getResource.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.getEntry = function () {
            return this.entry;
        };
        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.setHidden = function (hidden) {
            this.entry ? this.entry.setHidden(hidden) : _super.prototype.setHidden.call(this, hidden);
        };
        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 = (function () {
        function NoActionProvider() {
        }
        NoActionProvider.prototype.hasActions = function (tree, element) {
            return false;
        };
        NoActionProvider.prototype.getActions = function (tree, element) {
            return winjs_base_1.TPromise.as(null);
        };
        NoActionProvider.prototype.hasSecondaryActions = function (tree, element) {
            return false;
        };
        NoActionProvider.prototype.getSecondaryActions = function (tree, element) {
            return winjs_base_1.TPromise.as(null);
        };
        NoActionProvider.prototype.getActionItem = function (tree, element, action) {
            return null;
        };
        return NoActionProvider;
    }());
    var templateEntry = 'quickOpenEntry';
    var templateEntryGroup = 'quickOpenEntryGroup';
    var Renderer = (function () {
        function Renderer(actionProvider, actionRunner) {
            if (actionProvider === void 0) { actionProvider = new NoActionProvider(); }
            if (actionRunner === void 0) { actionRunner = null; }
            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', null, row1, row2);
            entryContainer.appendChild(entry);
            // Icon
            var icon = document.createElement('span');
            row1.appendChild(icon);
            // Label
            var label = new iconLabel_1.IconLabel(row1, { supportHighlights: true });
            // Description
            var descriptionContainer = document.createElement('span');
            row1.appendChild(descriptionContainer);
            DOM.addClass(descriptionContainer, 'quick-open-entry-description');
            var description = new highlightedLabel_1.HighlightedLabel(descriptionContainer);
            // 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);
            // 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,
                description: description,
                keybinding: keybinding,
                group: group,
                actionBar: actionBar
            };
        };
        Renderer.prototype.renderElement = function (entry, templateId, templateData, styles) {
            var data = templateData;
            // 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
            this.actionProvider.getActions(null, entry).then(function (actions) {
                // TODO@Ben this will not work anymore as soon as quick open has more actions
                // but as long as there is only one are ok
                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 = templateData;
                // Border
                if (group.showBorder()) {
                    DOM.addClass(groupData.container, 'results-group-separator');
                    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() || '';
                groupData.group.textContent = groupLabel;
                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 || [];
                data.label.setValue(entry.getLabel(), null, options);
                // Meta
                data.detail.set(entry.getDetail(), detailHighlights);
                // Description
                data.description.set(entry.getDescription(), descriptionHighlights || []);
                data.description.element.title = entry.getDescription();
                // Keybinding
                data.keybinding.set(entry.getKeybinding(), null);
            }
        };
        Renderer.prototype.disposeTemplate = function (templateId, templateData) {
            var data = templateData;
            data.actionBar.dispose();
            data.actionBar = null;
            data.container = null;
            data.entry = null;
            data.description.dispose();
            data.description = null;
            data.keybinding.dispose();
            data.keybinding = null;
            data.detail.dispose();
            data.detail = null;
            data.group = null;
            data.icon = null;
            data.label.dispose();
            data.label = null;
        };
        return Renderer;
    }());
    var QuickOpenModel = (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
        });
        /**
         * Adds entries that should show up in the quick open viewer.
         */
        QuickOpenModel.prototype.addEntries = function (entries) {
            if (types.isArray(entries)) {
                this._entries = this._entries.concat(entries);
            }
        };
        /**
         * Set the entries that should show up in the quick open viewer.
         */
        QuickOpenModel.prototype.setEntries = function (entries) {
            if (types.isArray(entries)) {
                this._entries = entries;
            }
        };
        /**
         * Get the entries that should show up in the quick open viewer.
         *
         * @visibleOnly optional parameter to only return visible entries
         */
        QuickOpenModel.prototype.getEntries = function (visibleOnly) {
            if (visibleOnly) {
                return this._entries.filter(function (e) { return !e.isHidden(); });
            }
            return this._entries;
        };
        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[297/*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); });
define(__m[298/*vs/nls!vs/base/parts/tree/browser/treeDefaults*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/parts/tree/browser/treeDefaults", data); });










define(__m[128/*vs/base/parts/tree/browser/treeDefaults*/], __M([1/*require*/,0/*exports*/,298/*vs/nls!vs/base/parts/tree/browser/treeDefaults*/,7/*vs/base/common/winjs.base*/,53/*vs/base/common/actions*/,15/*vs/base/common/platform*/,10/*vs/base/common/errors*/,4/*vs/base/browser/dom*/,40/*vs/base/common/keyCodes*/]), function (require, exports, nls, winjs_base_1, actions_1, platform, errors, dom, keyCodes_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ClickBehavior;
    (function (ClickBehavior) {
        /**
         * Handle the click when the mouse button is pressed but not released yet.
         */
        ClickBehavior[ClickBehavior["ON_MOUSE_DOWN"] = 0] = "ON_MOUSE_DOWN";
        /**
         * Handle the click when the mouse button is released.
         */
        ClickBehavior[ClickBehavior["ON_MOUSE_UP"] = 1] = "ON_MOUSE_UP";
    })(ClickBehavior = exports.ClickBehavior || (exports.ClickBehavior = {}));
    var KeybindingDispatcher = (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.equals(item.keybinding)) {
                    return item.callback;
                }
            }
            return null;
        };
        return KeybindingDispatcher;
    }());
    exports.KeybindingDispatcher = KeybindingDispatcher;
    var DefaultController = (function () {
        function DefaultController(options) {
            if (options === void 0) { options = { clickBehavior: ClickBehavior.ON_MOUSE_UP, keyboardSupport: true }; }
            var _this = this;
            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 === ClickBehavior.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, 'monaco-action-bar', 'row')) {
                        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 === ClickBehavior.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 payload = { origin: origin, originalEvent: eventish };
            if (tree.getInput() === element) {
                tree.clearFocus(payload);
                tree.clearSelection(payload);
            }
            else {
                var isMouseDown = eventish && eventish.browserEvent && eventish.browserEvent.type === 'mousedown';
                if (!isMouseDown) {
                    eventish.preventDefault(); // we cannot preventDefault onMouseDown because this would break DND otherwise
                }
                eventish.stopPropagation();
                tree.DOMFocus();
                tree.setSelection([element], payload);
                tree.setFocus(element, payload);
                if (tree.isExpanded(element)) {
                    tree.collapse(element).done(null, errors.onUnexpectedError);
                }
                else {
                    tree.expand(element).done(null, errors.onUnexpectedError);
                }
            }
            return true;
        };
        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) {
                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()).done(null, 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()).done(null, 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()).done(null, 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()).done(null, 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()).done(null, 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()).done(null, 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 = tree.getFocus();
                tree.collapse(focus).then(function (didCollapse) {
                    if (focus && !didCollapse) {
                        tree.focusParent(payload);
                        return tree.reveal(tree.getFocus());
                    }
                    return undefined;
                }).done(null, 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 = tree.getFocus();
                tree.expand(focus).then(function (didExpand) {
                    if (focus && !didExpand) {
                        tree.focusFirstChild(payload);
                        return tree.reveal(tree.getFocus());
                    }
                    return undefined;
                }).done(null, 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 = (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 = (function () {
        function DefaultFilter() {
        }
        DefaultFilter.prototype.isVisible = function (tree, element) {
            return true;
        };
        return DefaultFilter;
    }());
    exports.DefaultFilter = DefaultFilter;
    var DefaultSorter = (function () {
        function DefaultSorter() {
        }
        DefaultSorter.prototype.compare = function (tree, element, otherElement) {
            return 0;
        };
        return DefaultSorter;
    }());
    exports.DefaultSorter = DefaultSorter;
    var DefaultAccessibilityProvider = (function () {
        function DefaultAccessibilityProvider() {
        }
        DefaultAccessibilityProvider.prototype.getAriaLabel = function (tree, element) {
            return null;
        };
        return DefaultAccessibilityProvider;
    }());
    exports.DefaultAccessibilityProvider = DefaultAccessibilityProvider;
    var CollapseAllAction = (function (_super) {
        __extends(CollapseAllAction, _super);
        function CollapseAllAction(viewer, enabled) {
            var _this = _super.call(this, 'vs.tree.collapse', nls.localize(0, null), 'monaco-tree-action collapse-all', enabled) || this;
            _this.viewer = viewer;
            return _this;
        }
        CollapseAllAction.prototype.run = function (context) {
            if (this.viewer.getHighlight()) {
                return winjs_base_1.TPromise.as(null); // Global action disabled if user is in edit mode from another action
            }
            this.viewer.collapseAll();
            this.viewer.clearSelection();
            this.viewer.clearFocus();
            this.viewer.DOMFocus();
            this.viewer.focusFirst();
            return winjs_base_1.TPromise.as(null);
        };
        return CollapseAllAction;
    }(actions_1.Action));
    exports.CollapseAllAction = CollapseAllAction;
});











define(__m[161/*vs/base/parts/tree/browser/treeImpl*/], __M([1/*require*/,0/*exports*/,128/*vs/base/parts/tree/browser/treeDefaults*/,38/*vs/base/common/eventEmitter*/,466/*vs/base/parts/tree/browser/treeModel*/,238/*vs/base/parts/tree/browser/treeView*/,107/*vs/base/common/iterator*/,11/*vs/base/common/event*/,3/*vs/base/common/lifecycle*/,32/*vs/base/common/color*/,26/*vs/base/common/objects*/,261/*vs/css!vs/base/parts/tree/browser/tree*/]), function (require, exports, TreeDefaults, Events, Model, View, iterator_1, event_1, Lifecycle, color_1, objects_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var TreeContext = (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: TreeDefaults.ClickBehavior.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 || null;
            this.accessibilityProvider = configuration.accessibilityProvider || new TreeDefaults.DefaultAccessibilityProvider();
        }
        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 = (function (_super) {
        __extends(Tree, _super);
        function Tree(container, configuration, options) {
            if (options === void 0) { options = {}; }
            var _this = _super.call(this) || this;
            _this.toDispose = [];
            _this._onDispose = new event_1.Emitter();
            _this._onHighlightChange = new event_1.Emitter();
            _this.toDispose.push(_this._onDispose, _this._onHighlightChange);
            _this.container = container;
            _this.configuration = configuration;
            _this.options = options;
            objects_1.mixin(_this.options, defaultStyles, false);
            _this.options.twistiePixels = typeof _this.options.twistiePixels === 'number' ? _this.options.twistiePixels : 32;
            _this.options.showTwistie = _this.options.showTwistie === false ? false : true;
            _this.options.indentPixels = typeof _this.options.indentPixels === 'number' ? _this.options.indentPixels : 12;
            _this.options.alwaysFocused = _this.options.alwaysFocused === true ? true : false;
            _this.options.useShadows = _this.options.useShadows === false ? false : true;
            _this.options.paddingOnRow = _this.options.paddingOnRow === 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.addEmitter(_this.model);
            _this.addEmitter(_this.view);
            _this.toDispose.push(_this.model.addListener('highlight', function () { return _this._onHighlightChange.fire(); }));
            return _this;
        }
        Tree.prototype.style = function (styles) {
            this.view.applyStyles(styles);
        };
        Object.defineProperty(Tree.prototype, "onDOMFocus", {
            get: function () {
                return this.view && this.view.onDOMFocus;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Tree.prototype, "onDOMBlur", {
            get: function () {
                return this.view && this.view.onDOMBlur;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Tree.prototype, "onHighlightChange", {
            get: function () {
                return this._onHighlightChange && this._onHighlightChange.event;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Tree.prototype, "onDispose", {
            get: function () {
                return this._onDispose && this._onDispose.event;
            },
            enumerable: true,
            configurable: true
        });
        Tree.prototype.getHTMLElement = function () {
            return this.view.getHTMLElement();
        };
        Tree.prototype.layout = function (height) {
            this.view.layout(height);
        };
        Tree.prototype.DOMFocus = function () {
            this.view.focus();
        };
        Tree.prototype.isDOMFocused = function () {
            return this.view.isFocused();
        };
        Tree.prototype.DOMBlur = function () {
            this.view.blur();
        };
        Tree.prototype.onVisible = function () {
            this.view.onVisible();
        };
        Tree.prototype.onHidden = function () {
            this.view.onHidden();
        };
        Tree.prototype.setInput = function (element) {
            return this.model.setInput(element);
        };
        Tree.prototype.getInput = function () {
            return this.model.getInput();
        };
        Tree.prototype.refresh = function (element, recursive) {
            if (element === void 0) { element = null; }
            if (recursive === void 0) { recursive = true; }
            return this.model.refresh(element, recursive);
        };
        Tree.prototype.expand = function (element) {
            return this.model.expand(element);
        };
        Tree.prototype.expandAll = function (elements) {
            return this.model.expandAll(elements);
        };
        Tree.prototype.collapse = function (element, recursive) {
            if (recursive === void 0) { recursive = false; }
            return this.model.collapse(element, recursive);
        };
        Tree.prototype.collapseAll = function (elements, recursive) {
            if (elements === void 0) { elements = null; }
            if (recursive === void 0) { recursive = false; }
            return this.model.collapseAll(elements, recursive);
        };
        Tree.prototype.toggleExpansion = function (element) {
            return this.model.toggleExpansion(element);
        };
        Tree.prototype.toggleExpansionAll = function (elements) {
            return this.model.toggleExpansionAll(elements);
        };
        Tree.prototype.isExpanded = function (element) {
            return this.model.isExpanded(element);
        };
        Tree.prototype.getExpandedElements = function () {
            return this.model.getExpandedElements();
        };
        Tree.prototype.reveal = function (element, relativeTop) {
            if (relativeTop === void 0) { relativeTop = null; }
            return this.model.reveal(element, relativeTop);
        };
        Tree.prototype.getRelativeTop = function (element) {
            var item = this.model.getItem(element);
            return this.view.getRelativeTop(item);
        };
        Tree.prototype.getScrollPosition = function () {
            return this.view.getScrollPosition();
        };
        Tree.prototype.setScrollPosition = function (pos) {
            this.view.setScrollPosition(pos);
        };
        Tree.prototype.getContentHeight = function () {
            return this.view.getTotalHeight();
        };
        Tree.prototype.setHighlight = function (element, eventPayload) {
            this.model.setHighlight(element, eventPayload);
        };
        Tree.prototype.getHighlight = function () {
            return this.model.getHighlight();
        };
        Tree.prototype.isHighlighted = function (element) {
            return this.model.isFocused(element);
        };
        Tree.prototype.clearHighlight = function (eventPayload) {
            this.model.setHighlight(null, eventPayload);
        };
        Tree.prototype.select = function (element, eventPayload) {
            this.model.select(element, eventPayload);
        };
        Tree.prototype.selectRange = function (fromElement, toElement, eventPayload) {
            this.model.selectRange(fromElement, toElement, eventPayload);
        };
        Tree.prototype.deselectRange = function (fromElement, toElement, eventPayload) {
            this.model.deselectRange(fromElement, toElement, eventPayload);
        };
        Tree.prototype.selectAll = function (elements, eventPayload) {
            this.model.selectAll(elements, eventPayload);
        };
        Tree.prototype.deselect = function (element, eventPayload) {
            this.model.deselect(element, eventPayload);
        };
        Tree.prototype.deselectAll = function (elements, eventPayload) {
            this.model.deselectAll(elements, eventPayload);
        };
        Tree.prototype.setSelection = function (elements, eventPayload) {
            this.model.setSelection(elements, eventPayload);
        };
        Tree.prototype.toggleSelection = function (element, eventPayload) {
            this.model.toggleSelection(element, eventPayload);
        };
        Tree.prototype.isSelected = function (element) {
            return this.model.isSelected(element);
        };
        Tree.prototype.getSelection = function () {
            return this.model.getSelection();
        };
        Tree.prototype.clearSelection = function (eventPayload) {
            this.model.setSelection([], eventPayload);
        };
        Tree.prototype.selectNext = function (count, clearSelection, eventPayload) {
            this.model.selectNext(count, clearSelection, eventPayload);
        };
        Tree.prototype.selectPrevious = function (count, clearSelection, eventPayload) {
            this.model.selectPrevious(count, clearSelection, eventPayload);
        };
        Tree.prototype.selectParent = function (clearSelection, eventPayload) {
            this.model.selectParent(clearSelection, eventPayload);
        };
        Tree.prototype.setFocus = function (element, eventPayload) {
            this.model.setFocus(element, eventPayload);
        };
        Tree.prototype.isFocused = function (element) {
            return this.model.isFocused(element);
        };
        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.addTraits = function (trait, elements) {
            this.model.addTraits(trait, elements);
        };
        Tree.prototype.removeTraits = function (trait, elements) {
            this.model.removeTraits(trait, elements);
        };
        Tree.prototype.toggleTrait = function (trait, element) {
            this.model.hasTrait(trait, element) ? this.model.removeTraits(trait, [element])
                : this.model.addTraits(trait, [element]);
        };
        Tree.prototype.hasTrait = function (trait, element) {
            return this.model.hasTrait(trait, element);
        };
        Tree.prototype.getNavigator = function (fromElement, subTreeOnly) {
            return new iterator_1.MappedNavigator(this.model.getNavigator(fromElement, subTreeOnly), function (i) { return i && i.getElement(); });
        };
        Tree.prototype.dispose = function () {
            this._onDispose.fire();
            if (this.model !== null) {
                this.model.dispose();
                this.model = null;
            }
            if (this.view !== null) {
                this.view.dispose();
                this.view = null;
            }
            this.toDispose = Lifecycle.dispose(this.toDispose);
            _super.prototype.dispose.call(this);
        };
        return Tree;
    }(Events.EventEmitter));
    exports.Tree = Tree;
});











define(__m[301/*vs/base/parts/quickopen/browser/quickOpenWidget*/], __M([1/*require*/,0/*exports*/,297/*vs/nls!vs/base/parts/quickopen/browser/quickOpenWidget*/,7/*vs/base/common/winjs.base*/,15/*vs/base/common/platform*/,79/*vs/base/common/events*/,29/*vs/base/common/types*/,10/*vs/base/common/errors*/,100/*vs/base/parts/quickopen/common/quickOpen*/,445/*vs/base/parts/quickopen/browser/quickOpenViewer*/,52/*vs/base/browser/builder*/,115/*vs/base/browser/ui/inputbox/inputBox*/,36/*vs/base/common/severity*/,161/*vs/base/parts/tree/browser/treeImpl*/,220/*vs/base/browser/ui/progressbar/progressbar*/,65/*vs/base/browser/keyboardEvent*/,128/*vs/base/parts/tree/browser/treeDefaults*/,4/*vs/base/browser/dom*/,3/*vs/base/common/lifecycle*/,48/*vs/base/common/scrollable*/,32/*vs/base/common/color*/,26/*vs/base/common/objects*/,260/*vs/css!vs/base/parts/quickopen/browser/quickopen*/]), function (require, exports, nls, winjs_base_1, platform, events_1, types, errors, quickOpen_1, quickOpenViewer_1, builder_1, inputBox_1, severity_1, treeImpl_1, progressbar_1, keyboardEvent_1, treeDefaults_1, DOM, lifecycle_1, scrollable_1, color_1, objects_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var QuickOpenController = (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 HideReason;
    (function (HideReason) {
        HideReason[HideReason["ELEMENT_SELECTED"] = 0] = "ELEMENT_SELECTED";
        HideReason[HideReason["FOCUS_LOST"] = 1] = "FOCUS_LOST";
        HideReason[HideReason["CANCELED"] = 2] = "CANCELED";
    })(HideReason = exports.HideReason || (exports.HideReason = {}));
    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 = (function () {
        function QuickOpenWidget(container, callbacks, options, usageLogger) {
            this.isDisposed = false;
            this.toUnbind = [];
            this.container = container;
            this.callbacks = callbacks;
            this.options = options;
            this.styles = options || Object.create(null);
            objects_1.mixin(this.styles, defaultStyles, false);
            this.usageLogger = usageLogger;
            this.model = null;
        }
        QuickOpenWidget.prototype.getElement = function () {
            return builder_1.$(this.builder);
        };
        QuickOpenWidget.prototype.getModel = function () {
            return this.model;
        };
        QuickOpenWidget.prototype.setCallbacks = function (callbacks) {
            this.callbacks = callbacks;
        };
        QuickOpenWidget.prototype.create = function () {
            var _this = this;
            this.builder = builder_1.$().div(function (div) {
                // Eventing
                div.on(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(HideReason.CANCELED);
                    }
                })
                    .on(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
                    .on(DOM.EventType.FOCUS, function (e) { return _this.gainingFocus(); }, null, true)
                    .on(DOM.EventType.BLUR, function (e) { return _this.loosingFocus(e); }, null, true);
                // Progress Bar
                _this.progressBar = new progressbar_1.ProgressBar(div.clone(), { progressBarBackground: _this.styles.progressBarBackground });
                _this.progressBar.getContainer().hide();
                // Input Field
                div.div({ 'class': 'quick-open-input' }, function (inputContainer) {
                    _this.inputContainer = inputContainer;
                    _this.inputBox = new inputBox_1.InputBox(inputContainer.getHTMLElement(), null, {
                        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,
                        inputValidationInfoBorder: _this.styles.inputValidationInfoBorder,
                        inputValidationWarningBackground: _this.styles.inputValidationWarningBackground,
                        inputValidationWarningBorder: _this.styles.inputValidationWarningBorder,
                        inputValidationErrorBackground: _this.styles.inputValidationErrorBackground,
                        inputValidationErrorBorder: _this.styles.inputValidationErrorBorder
                    });
                    // ARIA
                    _this.inputElement = _this.inputBox.inputElement;
                    _this.inputElement.setAttribute('role', 'combobox');
                    _this.inputElement.setAttribute('aria-haspopup', 'false');
                    _this.inputElement.setAttribute('aria-autocomplete', 'list');
                    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;
                        }
                        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;
                            }
                        }
                        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 ? quickOpen_1.Mode.OPEN_IN_BACKGROUND : quickOpen_1.Mode.OPEN);
                            }
                        }
                    });
                    DOM.addDisposableListener(_this.inputBox.inputElement, DOM.EventType.INPUT, function (e) {
                        _this.onType();
                    });
                });
                // Tree
                _this.treeContainer = div.div({
                    'class': 'quick-open-tree'
                }, function (div) {
                    _this.tree = new treeImpl_1.Tree(div.getHTMLElement(), {
                        dataSource: new quickOpenViewer_1.DataSource(_this),
                        controller: new QuickOpenController({ clickBehavior: treeDefaults_1.ClickBehavior.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: scrollable_1.ScrollbarVisibility.Visible,
                        ariaLabel: nls.localize(1, null),
                        keyboardSupport: _this.options.keyboardSupport
                    });
                    _this.treeElement = _this.tree.getHTMLElement();
                    // Handle Focus and Selection event
                    _this.toUnbind.push(_this.tree.addListener(events_1.EventType.FOCUS, function (event) {
                        _this.elementFocused(event.focus, event);
                    }));
                    _this.toUnbind.push(_this.tree.addListener(events_1.EventType.SELECTION, function (event) {
                        if (event.selection && event.selection.length > 0) {
                            _this.elementSelected(event.selection[0], event);
                        }
                    }));
                }).
                    on(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);
                    }
                }).
                    on(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);
                        }
                    }
                }).
                    clone();
            })
                .addClass('quick-open-widget')
                .build(this.container);
            // Support layout
            if (this.layoutDimensions) {
                this.layout(this.layoutDimensions);
            }
            this.applyStyles();
            return this.builder.getHTMLElement();
        };
        QuickOpenWidget.prototype.style = function (styles) {
            this.styles = styles;
            this.applyStyles();
        };
        QuickOpenWidget.prototype.applyStyles = function () {
            if (this.builder) {
                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.builder.style('color', foreground);
                this.builder.style('background-color', background);
                this.builder.style('border-color', borderColor);
                this.builder.style('border-width', borderColor ? '1px' : null);
                this.builder.style('border-style', borderColor ? 'solid' : null);
                this.builder.style('box-shadow', 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,
                    inputValidationInfoBorder: this.styles.inputValidationInfoBorder,
                    inputValidationWarningBackground: this.styles.inputValidationWarningBackground,
                    inputValidationWarningBorder: this.styles.inputValidationWarningBorder,
                    inputValidationErrorBackground: this.styles.inputValidationErrorBackground,
                    inputValidationErrorBorder: this.styles.inputValidationErrorBorder
                });
            }
            if (this.tree) {
                this.tree.style(this.styles);
            }
            if (this.renderer) {
                this.renderer.updateStyles(this.styles);
            }
        };
        QuickOpenWidget.prototype.shouldOpenInBackground = function (e) {
            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 if not prevent
            // opening in the background such as the selection can be changed
            return this.inputBox.inputElement.selectionEnd === this.inputBox.value.length;
        };
        QuickOpenWidget.prototype.onType = function () {
            var value = this.inputBox.value;
            // Adjust help text as needed if present
            if (this.helpText) {
                if (value) {
                    this.helpText.hide();
                }
                else {
                    this.helpText.show();
                }
            }
            // Send to callbacks
            this.callbacks.onType(value);
        };
        QuickOpenWidget.prototype.navigate = function (next, quickNavigate) {
            if (this.isVisible()) {
                // Transition into quick navigate mode if not yet done
                if (!this.quickNavigateConfiguration && quickNavigate) {
                    this.quickNavigateConfiguration = quickNavigate;
                    this.tree.DOMFocus();
                }
                // Navigate
                this.navigateInTree(next ? 18 /* DownArrow */ : 16 /* UpArrow */);
            }
        };
        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();
                }
                else if (keyCode === 18 /* DownArrow */ || keyCode === 2 /* Tab */ && !isShift) {
                    this.tree.focusFirst();
                }
            }
            // Reveal
            newFocus = this.tree.getFocus();
            if (newFocus) {
                this.tree.reveal(newFocus).done(null, errors.onUnexpectedError);
            }
        };
        QuickOpenWidget.prototype.elementFocused = function (value, event) {
            if (!value || !this.isVisible()) {
                return;
            }
            // ARIA
            this.inputElement.setAttribute('aria-activedescendant', this.treeElement.getAttribute('aria-activedescendant'));
            var context = { event: event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration };
            this.model.runner.run(value, quickOpen_1.Mode.PREVIEW, context);
        };
        QuickOpenWidget.prototype.elementSelected = function (value, event, preferredMode) {
            var hide = true;
            // Trigger open of element on selection
            if (this.isVisible()) {
                var mode = preferredMode || quickOpen_1.Mode.OPEN;
                var context_1 = { event: event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration };
                hide = this.model.runner.run(value, mode, context_1);
            }
            // add telemetry when an item is accepted, logging the index of the item in the list and the length of the list
            // to measure the rate of the success and the relevance of the order
            if (this.usageLogger) {
                var indexOfAcceptedElement = this.model.entries.indexOf(value);
                var entriesCount = this.model.entries.length;
                this.usageLogger.publicLog('quickOpenWidgetItemAccepted', { index: indexOfAcceptedElement, count: entriesCount, isQuickNavigate: this.quickNavigateConfiguration ? true : false });
            }
            // Hide if command was run successfully
            if (hide) {
                this.hide(HideReason.ELEMENT_SELECTED);
            }
        };
        QuickOpenWidget.prototype.extractKeyMods = function (event) {
            var isCtrlCmd = event && (event.ctrlKey || event.metaKey || (event.payload && event.payload.originalEvent && (event.payload.originalEvent.ctrlKey || event.payload.originalEvent.metaKey)));
            return isCtrlCmd ? [2048 /* CtrlCmd */] : [];
        };
        QuickOpenWidget.prototype.show = function (param, options) {
            this.visible = true;
            this.isLoosingFocus = false;
            this.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : void 0;
            // Adjust UI for quick navigate mode
            if (this.quickNavigateConfiguration) {
                this.inputContainer.hide();
                this.builder.show();
                this.tree.DOMFocus();
            }
            else {
                this.inputContainer.show();
                this.builder.show();
                this.inputBox.focus();
            }
            // Adjust Help text for IE
            if (this.helpText) {
                if (this.quickNavigateConfiguration || types.isString(param)) {
                    this.helpText.hide();
                }
                else {
                    this.helpText.show();
                }
            }
            // Show based on param
            if (types.isString(param)) {
                this.doShowWithPrefix(param);
            }
            else {
                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.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);
            }).done(function () {
                // Indicate entries to tree
                _this.tree.layout();
                // Handle auto focus
                if (input && input.entries.some(function (e) { return _this.isElementVisible(input, e); })) {
                    _this.autoFocus(input, autoFocus);
                }
            }, errors.onUnexpectedError);
        };
        QuickOpenWidget.prototype.isElementVisible = function (input, e) {
            if (!input.filter) {
                return true;
            }
            return input.filter.isVisible(e);
        };
        QuickOpenWidget.prototype.autoFocus = function (input, autoFocus) {
            var _this = this;
            if (autoFocus === void 0) { autoFocus = {}; }
            var entries = input.entries.filter(function (e) { return _this.isElementVisible(input, e); });
            // 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; i < entries.length; i++) {
                    var entry = entries[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).done(null, errors.onUnexpectedError);
                    return;
                }
            }
            // Second check for auto focus of first entry
            if (autoFocus.autoFocusFirstEntry) {
                this.tree.focusFirst();
                this.tree.reveal(this.tree.getFocus()).done(null, errors.onUnexpectedError);
            }
            else if (typeof autoFocus.autoFocusIndex === 'number') {
                if (entries.length > autoFocus.autoFocusIndex) {
                    this.tree.focusNth(autoFocus.autoFocusIndex);
                    this.tree.reveal(this.tree.getFocus()).done(null, errors.onUnexpectedError);
                }
            }
            else if (autoFocus.autoFocusSecondEntry) {
                if (entries.length > 1) {
                    this.tree.focusNth(1);
                }
            }
            else if (autoFocus.autoFocusLastEntry) {
                if (entries.length > 1) {
                    this.tree.focusLast();
                }
            }
        };
        QuickOpenWidget.prototype.refresh = function (input, autoFocus) {
            var _this = this;
            if (!this.isVisible()) {
                return;
            }
            if (!input) {
                input = this.tree.getInput();
            }
            if (!input) {
                return;
            }
            // Apply height & Refresh
            this.treeContainer.style({ height: this.getHeight(input) + "px" });
            this.tree.refresh().done(function () {
                // Indicate entries to tree
                _this.tree.layout();
                // Handle auto focus
                if (autoFocus) {
                    var doAutoFocus = autoFocus && input && input.entries.some(function (e) { return _this.isElementVisible(input, e); });
                    if (doAutoFocus) {
                        _this.autoFocus(input, autoFocus);
                    }
                }
            }, errors.onUnexpectedError);
        };
        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.40 /* 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.hide = function (reason) {
            var _this = this;
            if (!this.isVisible()) {
                return;
            }
            this.visible = false;
            this.builder.hide();
            this.builder.domBlur();
            // report failure cases
            if (reason === HideReason.CANCELED) {
                if (this.model) {
                    var entriesCount = this.model.entries.filter(function (e) { return _this.isElementVisible(_this.model, e); }).length;
                    if (this.usageLogger) {
                        this.usageLogger.publicLog('quickOpenWidgetCancelled', { count: entriesCount, isQuickNavigate: this.quickNavigateConfiguration ? true : false });
                    }
                }
            }
            // 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().getContainer().hide();
            // Clear Focus
            if (this.tree.isDOMFocused()) {
                this.tree.DOMBlur();
            }
            else if (this.inputBox.hasFocus()) {
                this.inputBox.blur();
            }
            // Callbacks
            if (reason === HideReason.ELEMENT_SELECTED) {
                this.callbacks.onOk();
            }
            else {
                this.callbacks.onCancel();
            }
            if (this.callbacks.onHide) {
                this.callbacks.onHide(reason);
            }
        };
        QuickOpenWidget.prototype.getQuickNavigateConfiguration = function () {
            return this.quickNavigateConfiguration;
        };
        QuickOpenWidget.prototype.setPlaceHolder = function (placeHolder) {
            if (this.inputBox) {
                this.inputBox.setPlaceHolder(placeHolder);
            }
        };
        QuickOpenWidget.prototype.setValue = function (value, selection) {
            if (this.inputBox) {
                this.inputBox.value = value;
                if (Array.isArray(selection)) {
                    var start = selection[0], end = selection[1];
                    this.inputBox.select({ start: start, end: end });
                }
                else {
                    this.inputBox.select();
                }
            }
        };
        QuickOpenWidget.prototype.setPassword = function (isPassword) {
            if (this.inputBox) {
                this.inputBox.inputElement.type = isPassword ? 'password' : 'text';
            }
        };
        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
            this.builder.addClass('content-changing');
            this.inputChangingTimeoutHandle = setTimeout(function () {
                _this.builder.removeClass('content-changing');
            }, 500);
        };
        QuickOpenWidget.prototype.getInput = function () {
            return this.tree.getInput();
        };
        QuickOpenWidget.prototype.getTree = function () {
            return this.tree;
        };
        QuickOpenWidget.prototype.showInputDecoration = function (decoration) {
            if (this.inputBox) {
                this.inputBox.showMessage({ type: decoration === severity_1.default.Info ? inputBox_1.MessageType.INFO : decoration === severity_1.default.Warning ? inputBox_1.MessageType.WARNING : inputBox_1.MessageType.ERROR, content: '' });
            }
        };
        QuickOpenWidget.prototype.clearInputDecoration = function () {
            if (this.inputBox) {
                this.inputBox.hideMessage();
            }
        };
        QuickOpenWidget.prototype.focus = function () {
            if (this.isVisible() && this.inputBox) {
                this.inputBox.focus();
            }
        };
        QuickOpenWidget.prototype.accept = function () {
            if (this.isVisible()) {
                var focus_3 = this.tree.getFocus();
                if (focus_3) {
                    this.elementSelected(focus_3);
                }
            }
        };
        QuickOpenWidget.prototype.getProgressBar = function () {
            return this.progressBar;
        };
        QuickOpenWidget.prototype.getInputBox = function () {
            return this.inputBox;
        };
        QuickOpenWidget.prototype.setExtraClass = function (clazz) {
            var previousClass = this.builder.getProperty('extra-class');
            if (previousClass) {
                this.builder.removeClass(previousClass);
            }
            if (clazz) {
                this.builder.addClass(clazz);
                this.builder.setProperty('extra-class', clazz);
            }
            else if (previousClass) {
                this.builder.removeProperty('extra-class');
            }
        };
        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.builder) {
                // quick open
                this.builder.style({
                    width: quickOpenWidth + 'px',
                    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.builder.getHTMLElement())) {
                return; // user clicked somewhere into quick open widget, do not close thereby
            }
            this.isLoosingFocus = true;
            winjs_base_1.TPromise.timeout(0).then(function () {
                if (!_this.isLoosingFocus) {
                    return;
                }
                if (_this.isDisposed) {
                    return;
                }
                var veto = _this.callbacks.onFocusLost && _this.callbacks.onFocusLost();
                if (!veto) {
                    _this.hide(HideReason.FOCUS_LOST);
                }
            });
        };
        QuickOpenWidget.prototype.dispose = function () {
            this.isDisposed = true;
            this.toUnbind = lifecycle_1.dispose(this.toUnbind);
            this.progressBar.dispose();
            this.inputBox.dispose();
            this.tree.dispose();
        };
        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;
    }());
    exports.QuickOpenWidget = QuickOpenWidget;
});

define(__m[302/*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[303/*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[304/*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[305/*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); });








define(__m[49/*vs/editor/common/config/editorOptions*/], __M([1/*require*/,0/*exports*/,305/*vs/nls!vs/editor/common/config/editorOptions*/,15/*vs/base/common/platform*/,48/*vs/base/common/scrollable*/,95/*vs/editor/common/model/wordHelper*/]), function (require, exports, nls, platform, scrollable_1, wordHelper_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var 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 as the parent.
         */
        WrappingIndent[WrappingIndent["Indent"] = 2] = "Indent";
    })(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 = {}));
    /**
     * @internal
     */
    function blinkingStyleToString(blinkingStyle) {
        if (blinkingStyle === TextEditorCursorBlinkingStyle.Blink) {
            return 'blink';
        }
        else if (blinkingStyle === TextEditorCursorBlinkingStyle.Expand) {
            return 'expand';
        }
        else if (blinkingStyle === TextEditorCursorBlinkingStyle.Phase) {
            return 'phase';
        }
        else if (blinkingStyle === TextEditorCursorBlinkingStyle.Smooth) {
            return 'smooth';
        }
        else if (blinkingStyle === TextEditorCursorBlinkingStyle.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 = (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.wordSeparators = source.wordSeparators;
            this.autoClosingBrackets = source.autoClosingBrackets;
            this.autoIndent = source.autoIndent;
            this.useTabStops = source.useTabStops;
            this.tabFocusMode = source.tabFocusMode;
            this.dragAndDrop = source.dragAndDrop;
            this.emptySelectionClipboard = source.emptySelectionClipboard;
            this.layoutInfo = source.layoutInfo;
            this.fontInfo = source.fontInfo;
            this.viewInfo = source.viewInfo;
            this.wrappingInfo = source.wrappingInfo;
            this.contribInfo = source.contribInfo;
        }
        /**
         * @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.wordSeparators === other.wordSeparators
                && this.autoClosingBrackets === other.autoClosingBrackets
                && this.autoIndent === other.autoIndent
                && this.useTabStops === other.useTabStops
                && this.tabFocusMode === other.tabFocusMode
                && this.dragAndDrop === other.dragAndDrop
                && this.emptySelectionClipboard === other.emptySelectionClipboard
                && 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),
                wordSeparators: (this.wordSeparators !== newOpts.wordSeparators),
                autoClosingBrackets: (this.autoClosingBrackets !== newOpts.autoClosingBrackets),
                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),
                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.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
                && this._equalsNumberArrays(a.rulers, b.rulers)
                && a.ariaLabel === b.ariaLabel
                && a.renderLineNumbers === b.renderLineNumbers
                && a.renderCustomLineNumbers === b.renderCustomLineNumbers
                && a.renderRelativeLineNumbers === b.renderRelativeLineNumbers
                && 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.cursorStyle === b.cursorStyle
                && a.hideCursorInOverviewRuler === b.hideCursorInOverviewRuler
                && a.scrollBeyondLastLine === b.scrollBeyondLastLine
                && a.stopRenderingLineAfter === b.stopRenderingLineAfter
                && a.renderWhitespace === b.renderWhitespace
                && a.renderControlCharacters === b.renderControlCharacters
                && a.fontLigatures === b.fontLigatures
                && a.renderIndentGuides === b.renderIndentGuides
                && 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);
        };
        /**
         * @internal
         */
        InternalEditorOptions._equalsMinimapOptions = function (a, b) {
            return (a.enabled === b.enabled
                && a.showSlider === b.showSlider
                && a.renderCharacters === b.renderCharacters
                && a.maxColumn === b.maxColumn);
        };
        InternalEditorOptions._equalsNumberArrays = 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;
        };
        /**
         * @internal
         */
        InternalEditorOptions._equalFindOptions = function (a, b) {
            return (a.seedSearchStringFromSelection === b.seedSearchStringFromSelection
                && a.autoFindInSelection === b.autoFindInSelection);
        };
        /**
         * @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
                && a.hover === b.hover
                && a.links === b.links
                && a.contextmenu === b.contextmenu
                && InternalEditorOptions._equalsQuickSuggestions(a.quickSuggestions, b.quickSuggestions)
                && a.quickSuggestionsDelay === b.quickSuggestionsDelay
                && a.parameterHints === b.parameterHints
                && a.iconsInSuggestions === b.iconsInSuggestions
                && a.formatOnType === b.formatOnType
                && a.formatOnPaste === b.formatOnPaste
                && a.suggestOnTriggerCharacters === b.suggestOnTriggerCharacters
                && a.acceptSuggestionOnEnter === b.acceptSuggestionOnEnter
                && a.acceptSuggestionOnCommitCharacter === b.acceptSuggestionOnCommitCharacter
                && a.snippetSuggestions === b.snippetSuggestions
                && a.wordBasedSuggestions === b.wordBasedSuggestions
                && a.suggestFontSize === b.suggestFontSize
                && a.suggestLineHeight === b.suggestLineHeight
                && a.selectionHighlight === b.selectionHighlight
                && a.occurrencesHighlight === b.occurrencesHighlight
                && a.codeLens === b.codeLens
                && a.folding === b.folding
                && a.showFoldingControls === b.showFoldingControls
                && a.matchBrackets === b.matchBrackets
                && this._equalFindOptions(a.find, b.find));
        };
        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 _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 === 'indent') {
            return WrappingIndent.Indent;
        }
        else if (wrappingIndent === 'same') {
            return WrappingIndent.Same;
        }
        else {
            return WrappingIndent.None;
        }
    }
    function _cursorBlinkingStyleFromString(cursorBlinkingStyle, defaultValue) {
        if (typeof cursorBlinkingStyle !== 'string') {
            return defaultValue;
        }
        switch (cursorBlinkingStyle) {
            case 'blink':
                return TextEditorCursorBlinkingStyle.Blink;
            case 'smooth':
                return TextEditorCursorBlinkingStyle.Smooth;
            case 'phase':
                return TextEditorCursorBlinkingStyle.Phase;
            case 'expand':
                return TextEditorCursorBlinkingStyle.Expand;
            case 'visible': // maintain compatibility
            case 'solid':
                return TextEditorCursorBlinkingStyle.Solid;
        }
        return TextEditorCursorBlinkingStyle.Blink;
    }
    function _scrollbarVisibilityFromString(visibility, defaultValue) {
        if (typeof visibility !== 'string') {
            return defaultValue;
        }
        switch (visibility) {
            case 'hidden':
                return scrollable_1.ScrollbarVisibility.Hidden;
            case 'visible':
                return scrollable_1.ScrollbarVisibility.Visible;
            default:
                return scrollable_1.ScrollbarVisibility.Auto;
        }
    }
    /**
     * @internal
     */
    var EditorOptionsValidator = (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;
            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']);
            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: _boolean(opts.autoClosingBrackets, defaults.autoClosingBrackets),
                autoIndent: _boolean(opts.autoIndent, defaults.autoIndent),
                dragAndDrop: _boolean(opts.dragAndDrop, defaults.dragAndDrop),
                emptySelectionClipboard: _boolean(opts.emptySelectionClipboard, defaults.emptySelectionClipboard),
                useTabStops: _boolean(opts.useTabStops, defaults.useTabStops),
                multiCursorModifier: multiCursorModifier,
                accessibilitySupport: _stringSet(opts.accessibilitySupport, defaults.accessibilitySupport, ['auto', 'on', 'off']),
                viewInfo: viewInfo,
                contribInfo: contribInfo,
            };
        };
        EditorOptionsValidator._sanitizeScrollbarOpts = function (opts, defaults, mouseWheelScrollSensitivity) {
            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
            };
        };
        EditorOptionsValidator._sanitizeMinimapOpts = function (opts, defaults) {
            if (typeof opts !== 'object') {
                return defaults;
            }
            return {
                enabled: _boolean(opts.enabled, defaults.enabled),
                showSlider: _stringSet(opts.showSlider, defaults.showSlider, ['always', 'mouseover']),
                renderCharacters: _boolean(opts.renderCharacters, defaults.renderCharacters),
                maxColumn: _clampedInt(opts.maxColumn, defaults.maxColumn, 1, 10000),
            };
        };
        EditorOptionsValidator._santizeFindOpts = function (opts, defaults) {
            if (typeof opts !== 'object') {
                return defaults;
            }
            return {
                seedSearchStringFromSelection: _boolean(opts.seedSearchStringFromSelection, defaults.seedSearchStringFromSelection),
                autoFindInSelection: _boolean(opts.autoFindInSelection, defaults.autoFindInSelection)
            };
        };
        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;
            var renderRelativeLineNumbers = defaults.renderRelativeLineNumbers;
            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 = true;
                    renderCustomLineNumbers = lineNumbers;
                    renderRelativeLineNumbers = false;
                }
                else if (lineNumbers === 'relative') {
                    renderLineNumbers = true;
                    renderCustomLineNumbers = null;
                    renderRelativeLineNumbers = true;
                }
                else if (lineNumbers === 'on') {
                    renderLineNumbers = true;
                    renderCustomLineNumbers = null;
                    renderRelativeLineNumbers = false;
                }
                else {
                    renderLineNumbers = false;
                    renderCustomLineNumbers = null;
                    renderRelativeLineNumbers = false;
                }
            }
            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(opts.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(opts.renderLineHighlight, defaults.renderLineHighlight, ['none', 'gutter', 'line', 'all']);
            }
            var mouseWheelScrollSensitivity = _float(opts.mouseWheelScrollSensitivity, defaults.scrollbar.mouseWheelScrollSensitivity);
            var scrollbar = this._sanitizeScrollbarOpts(opts.scrollbar, defaults.scrollbar, mouseWheelScrollSensitivity);
            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,
                renderRelativeLineNumbers: renderRelativeLineNumbers,
                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),
                cursorStyle: _cursorStyleFromString(opts.cursorStyle, defaults.cursorStyle),
                hideCursorInOverviewRuler: _boolean(opts.hideCursorInOverviewRuler, defaults.hideCursorInOverviewRuler),
                scrollBeyondLastLine: _boolean(opts.scrollBeyondLastLine, defaults.scrollBeyondLastLine),
                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),
                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);
            }
            var find = this._santizeFindOpts(opts.find, defaults.find);
            return {
                selectionClipboard: _boolean(opts.selectionClipboard, defaults.selectionClipboard),
                hover: _boolean(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: _boolean(opts.parameterHints, defaults.parameterHints),
                iconsInSuggestions: _boolean(opts.iconsInSuggestions, defaults.iconsInSuggestions),
                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),
                snippetSuggestions: _stringSet(opts.snippetSuggestions, defaults.snippetSuggestions, ['top', 'bottom', 'inline', 'none']),
                wordBasedSuggestions: _boolean(opts.wordBasedSuggestions, defaults.wordBasedSuggestions),
                suggestFontSize: _clampedInt(opts.suggestFontSize, defaults.suggestFontSize, 0, 1000),
                suggestLineHeight: _clampedInt(opts.suggestLineHeight, defaults.suggestLineHeight, 0, 1000),
                selectionHighlight: _boolean(opts.selectionHighlight, defaults.selectionHighlight),
                occurrencesHighlight: _boolean(opts.occurrencesHighlight, defaults.occurrencesHighlight),
                codeLens: _boolean(opts.codeLens, defaults.codeLens) && _boolean(opts.referenceInfos, true),
                folding: _boolean(opts.folding, defaults.folding),
                showFoldingControls: _stringSet(opts.showFoldingControls, defaults.showFoldingControls, ['always', 'mouseover']),
                matchBrackets: _boolean(opts.matchBrackets, defaults.matchBrackets),
                find: find
            };
        };
        return EditorOptionsValidator;
    }());
    exports.EditorOptionsValidator = EditorOptionsValidator;
    /**
     * @internal
     */
    var InternalEditorOptionsFactory = (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,
                autoIndent: opts.autoIndent,
                dragAndDrop: opts.dragAndDrop,
                emptySelectionClipboard: opts.emptySelectionClipboard,
                useTabStops: opts.useTabStops,
                multiCursorModifier: opts.multiCursorModifier,
                accessibilitySupport: opts.accessibilitySupport,
                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,
                    renderRelativeLineNumbers: opts.viewInfo.renderRelativeLineNumbers,
                    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,
                    cursorStyle: opts.viewInfo.cursorStyle,
                    hideCursorInOverviewRuler: opts.viewInfo.hideCursorInOverviewRuler,
                    scrollBeyondLastLine: opts.viewInfo.scrollBeyondLastLine,
                    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),
                    renderLineHighlight: (accessibilityIsOn ? 'none' : opts.viewInfo.renderLineHighlight),
                    scrollbar: opts.viewInfo.scrollbar,
                    minimap: {
                        enabled: (accessibilityIsOn ? false : opts.viewInfo.minimap.enabled),
                        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,
                    iconsInSuggestions: opts.contribInfo.iconsInSuggestions,
                    formatOnType: opts.contribInfo.formatOnType,
                    formatOnPaste: opts.contribInfo.formatOnPaste,
                    suggestOnTriggerCharacters: opts.contribInfo.suggestOnTriggerCharacters,
                    acceptSuggestionOnEnter: opts.contribInfo.acceptSuggestionOnEnter,
                    acceptSuggestionOnCommitCharacter: opts.contribInfo.acceptSuggestionOnCommitCharacter,
                    snippetSuggestions: opts.contribInfo.snippetSuggestions,
                    wordBasedSuggestions: opts.contribInfo.wordBasedSuggestions,
                    suggestFontSize: opts.contribInfo.suggestFontSize,
                    suggestLineHeight: opts.contribInfo.suggestLineHeight,
                    selectionHighlight: (accessibilityIsOn ? false : opts.contribInfo.selectionHighlight),
                    occurrencesHighlight: (accessibilityIsOn ? false : opts.contribInfo.occurrencesHighlight),
                    codeLens: (accessibilityIsOn ? false : opts.contribInfo.codeLens),
                    folding: (accessibilityIsOn ? false : opts.contribInfo.folding),
                    showFoldingControls: opts.contribInfo.showFoldingControls,
                    matchBrackets: (accessibilityIsOn ? false : opts.contribInfo.matchBrackets),
                    find: opts.contribInfo.find
                }
            };
        };
        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,
                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,
                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,
                wordSeparators: opts.wordSeparators,
                autoClosingBrackets: opts.autoClosingBrackets,
                autoIndent: opts.autoIndent,
                useTabStops: opts.useTabStops,
                tabFocusMode: opts.readOnly ? true : env.tabFocusMode,
                dragAndDrop: opts.dragAndDrop,
                emptySelectionClipboard: opts.emptySelectionClipboard && env.emptySelectionClipboard,
                layoutInfo: layoutInfo,
                fontInfo: env.fontInfo,
                viewInfo: opts.viewInfo,
                wrappingInfo: wrappingInfo,
                contribInfo: opts.contribInfo
            });
        };
        return InternalEditorOptionsFactory;
    }());
    exports.InternalEditorOptionsFactory = InternalEditorOptionsFactory;
    /**
     * @internal
     */
    var EditorLayoutProvider = (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 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 minimapWidth;
            var contentWidth;
            if (!minimap) {
                minimapWidth = 0;
                renderMinimap = RenderMinimap.None;
                contentWidth = remainingWidth;
            }
            else {
                var minimapCharWidth = void 0;
                if (pixelRatio >= 2) {
                    renderMinimap = minimapRenderCharacters ? RenderMinimap.Large : RenderMinimap.LargeBlocks;
                    minimapCharWidth = 2 / pixelRatio;
                }
                else {
                    renderMinimap = minimapRenderCharacters ? RenderMinimap.Small : RenderMinimap.SmallBlocks;
                    minimapCharWidth = 1 / pixelRatio;
                }
                // Given:
                // viewportColumn = (contentWidth - verticalScrollbarWidth) / typicalHalfwidthCharacterWidth
                // minimapWidth = viewportColumn * minimapCharWidth
                // contentWidth = remainingWidth - minimapWidth
                // What are good values for contentWidth and minimapWidth ?
                // minimapWidth = ((contentWidth - verticalScrollbarWidth) / typicalHalfwidthCharacterWidth) * minimapCharWidth
                // typicalHalfwidthCharacterWidth * minimapWidth = (contentWidth - verticalScrollbarWidth) * minimapCharWidth
                // typicalHalfwidthCharacterWidth * minimapWidth = (remainingWidth - minimapWidth - verticalScrollbarWidth) * minimapCharWidth
                // (typicalHalfwidthCharacterWidth + minimapCharWidth) * minimapWidth = (remainingWidth - verticalScrollbarWidth) * minimapCharWidth
                // minimapWidth = ((remainingWidth - verticalScrollbarWidth) * minimapCharWidth) / (typicalHalfwidthCharacterWidth + minimapCharWidth)
                minimapWidth = Math.max(0, Math.floor(((remainingWidth - verticalScrollbarWidth) * minimapCharWidth) / (typicalHalfwidthCharacterWidth + minimapCharWidth)));
                var minimapColumns = minimapWidth / minimapCharWidth;
                if (minimapColumns > minimapMaxColumn) {
                    minimapWidth = Math.floor(minimapMaxColumn * minimapCharWidth);
                }
                contentWidth = remainingWidth - minimapWidth;
            }
            var viewportColumn = Math.max(1, Math.floor((contentWidth - verticalScrollbarWidth) / 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,
                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\', \'Courier New\', 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,
        insertSpaces: true,
        detectIndentation: true,
        trimAutoWhitespace: 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: WrappingIndent.Same,
        wordWrapBreakBeforeCharacters: '([{‘“〈《「『【〔（［｛｢£¥＄￡￥+＋',
        wordWrapBreakAfterCharacters: ' \t})]?|&,;¢°′″‰℃、。｡､￠，．：；？！％・･ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ｧｨｩｪｫｬｭｮｯｰ”〉》」』】〕）］｝｣',
        wordWrapBreakObtrusiveCharacters: '.',
        autoClosingBrackets: true,
        autoIndent: true,
        dragAndDrop: true,
        emptySelectionClipboard: true,
        useTabStops: true,
        multiCursorModifier: 'altKey',
        accessibilitySupport: 'auto',
        viewInfo: {
            extraEditorClassName: '',
            disableMonospaceOptimizations: false,
            rulers: [],
            ariaLabel: nls.localize(1, null),
            renderLineNumbers: true,
            renderCustomLineNumbers: null,
            renderRelativeLineNumbers: false,
            selectOnLineNumbers: true,
            glyphMargin: true,
            revealHorizontalRightPadding: 30,
            roundedSelection: true,
            overviewRulerLanes: 2,
            overviewRulerBorder: true,
            cursorBlinking: TextEditorCursorBlinkingStyle.Blink,
            mouseWheelZoom: false,
            cursorStyle: TextEditorCursorStyle.Line,
            hideCursorInOverviewRuler: false,
            scrollBeyondLastLine: true,
            stopRenderingLineAfter: 10000,
            renderWhitespace: 'none',
            renderControlCharacters: false,
            fontLigatures: false,
            renderIndentGuides: true,
            renderLineHighlight: 'line',
            scrollbar: {
                vertical: scrollable_1.ScrollbarVisibility.Auto,
                horizontal: scrollable_1.ScrollbarVisibility.Auto,
                arrowSize: 11,
                useShadows: true,
                verticalHasArrows: false,
                horizontalHasArrows: false,
                horizontalScrollbarSize: 10,
                horizontalSliderSize: 10,
                verticalScrollbarSize: 14,
                verticalSliderSize: 14,
                handleMouseWheel: true,
                mouseWheelScrollSensitivity: 1,
            },
            minimap: {
                enabled: true,
                showSlider: 'mouseover',
                renderCharacters: true,
                maxColumn: 120
            },
            fixedOverflowWidgets: false,
        },
        contribInfo: {
            selectionClipboard: true,
            hover: true,
            links: true,
            contextmenu: true,
            quickSuggestions: { other: true, comments: false, strings: false },
            quickSuggestionsDelay: 10,
            parameterHints: true,
            iconsInSuggestions: true,
            formatOnType: false,
            formatOnPaste: false,
            suggestOnTriggerCharacters: true,
            acceptSuggestionOnEnter: 'on',
            acceptSuggestionOnCommitCharacter: true,
            snippetSuggestions: 'inline',
            wordBasedSuggestions: true,
            suggestFontSize: 0,
            suggestLineHeight: 0,
            selectionHighlight: true,
            occurrencesHighlight: true,
            codeLens: true,
            folding: true,
            showFoldingControls: 'mouseover',
            matchBrackets: true,
            find: {
                seedSearchStringFromSelection: true,
                autoFindInSelection: false
            }
        },
    };
});











define(__m[132/*vs/editor/common/config/fontInfo*/], __M([1/*require*/,0/*exports*/,15/*vs/base/common/platform*/,135/*vs/editor/common/config/editorZoom*/,49/*vs/editor/common/config/editorOptions*/]), function (require, exports, platform, editorZoom_1, editorOptions_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * Determined from empirical observations.
     * @internal
     */
    var GOLDEN_LINE_HEIGHT_RATIO = platform.isMacintosh ? 1.5 : 1.35;
    function safeParseFloat(n, defaultValue) {
        if (typeof n === 'number') {
            return n;
        }
        var r = parseFloat(n);
        if (isNaN(r)) {
            return defaultValue;
        }
        return r;
    }
    function safeParseInt(n, defaultValue) {
        if (typeof n === 'number') {
            return Math.round(n);
        }
        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 = (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) {
            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, 100);
            if (fontSize === 0) {
                fontSize = editorOptions_1.EDITOR_FONT_DEFAULTS.fontSize;
            }
            else if (fontSize < 8) {
                fontSize = 8;
            }
            var lineHeight = safeParseInt(opts.lineHeight, 0);
            lineHeight = clamp(lineHeight, 0, 150);
            if (lineHeight === 0) {
                lineHeight = Math.round(GOLDEN_LINE_HEIGHT_RATIO * fontSize);
            }
            else if (lineHeight < 8) {
                lineHeight = 8;
            }
            var letterSpacing = safeParseFloat(opts.letterSpacing, 0);
            letterSpacing = clamp(letterSpacing, -20, 20);
            var editorZoomLevelMultiplier = 1 + (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;
        };
        return BareFontInfo;
    }());
    exports.BareFontInfo = BareFontInfo;
    var FontInfo = (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.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.spaceWidth === other.spaceWidth
                && this.maxDigitWidth === other.maxDigitWidth);
        };
        return FontInfo;
    }(BareFontInfo));
    exports.FontInfo = FontInfo;
});

define(__m[93/*vs/editor/common/model/textModel*/], __M([1/*require*/,0/*exports*/,38/*vs/base/common/eventEmitter*/,9/*vs/base/common/strings*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,118/*vs/editor/common/model/modelLine*/,482/*vs/editor/common/model/indentationGuesser*/,49/*vs/editor/common/config/editorOptions*/,104/*vs/editor/common/viewModel/prefixSumComputer*/,481/*vs/editor/common/model/indentRanges*/,158/*vs/editor/common/model/textModelSearch*/,101/*vs/editor/common/model/textSource*/,55/*vs/editor/common/model/textModelEvents*/]), function (require, exports, eventEmitter_1, strings, position_1, range_1, editorCommon, modelLine_1, indentationGuesser_1, editorOptions_1, prefixSumComputer_1, indentRanges_1, textModelSearch_1, textSource_1, textModelEvents) {
    /*---------------------------------------------------------------------------------------------
     *  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 USE_MIMINAL_MODEL_LINE = true;
    var LIMIT_FIND_COUNT = 999;
    exports.LONG_LINE_BOUNDARY = 10000;
    var TextModel = (function () {
        function TextModel(rawTextSource, creationOptions) {
            this._eventEmitter = new eventEmitter_1.OrderGuaranteeEventEmitter();
            var textModelData = TextModel.resolveCreationData(rawTextSource, creationOptions);
            // !!! 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.
            this._isTooLargeForTokenization = ((textModelData.text.length > TextModel.MODEL_TOKENIZATION_LIMIT)
                || (textModelData.text.lines.length > TextModel.MANY_MANY_LINES));
            this._shouldSimplifyMode = (this._isTooLargeForTokenization
                || (textModelData.text.length > TextModel.MODEL_SYNC_LIMIT));
            this._options = new editorCommon.TextModelResolvedOptions(textModelData.options);
            this._constructLines(textModelData.text);
            this._setVersionId(1);
            this._isDisposed = false;
            this._isDisposing = false;
        }
        TextModel.createFromString = function (text, options) {
            if (options === void 0) { options = TextModel.DEFAULT_CREATION_OPTIONS; }
            return new TextModel(textSource_1.RawTextSource.fromString(text), options);
        };
        TextModel.resolveCreationData = function (rawTextSource, options) {
            var textSource = textSource_1.TextSource.fromRawTextSource(rawTextSource, options.defaultEOL);
            var resolvedOpts;
            if (options.detectIndentation) {
                var guessedIndentation = indentationGuesser_1.guessIndentation(textSource.lines, options.tabSize, options.insertSpaces);
                resolvedOpts = new editorCommon.TextModelResolvedOptions({
                    tabSize: guessedIndentation.tabSize,
                    insertSpaces: guessedIndentation.insertSpaces,
                    trimAutoWhitespace: options.trimAutoWhitespace,
                    defaultEOL: options.defaultEOL
                });
            }
            else {
                resolvedOpts = new editorCommon.TextModelResolvedOptions({
                    tabSize: options.tabSize,
                    insertSpaces: options.insertSpaces,
                    trimAutoWhitespace: options.trimAutoWhitespace,
                    defaultEOL: options.defaultEOL
                });
            }
            return {
                text: textSource,
                options: resolvedOpts
            };
        };
        TextModel.prototype.addBulkListener = function (listener) {
            return this._eventEmitter.addBulkListener(listener);
        };
        TextModel.prototype._createModelLine = function (text, tabSize) {
            if (USE_MIMINAL_MODEL_LINE && this._isTooLargeForTokenization) {
                return new modelLine_1.MinimalModelLine(text, tabSize);
            }
            return new modelLine_1.ModelLine(text, tabSize);
        };
        TextModel.prototype._assertNotDisposed = function () {
            if (this._isDisposed) {
                throw new Error('Model is disposed!');
            }
        };
        TextModel.prototype.isTooLargeForHavingARichMode = function () {
            return this._shouldSimplifyMode;
        };
        TextModel.prototype.isTooLargeForTokenization = function () {
            return this._isTooLargeForTokenization;
        };
        TextModel.prototype.getOptions = function () {
            this._assertNotDisposed();
            return this._options;
        };
        TextModel.prototype.updateOptions = function (_newOpts) {
            this._assertNotDisposed();
            var tabSize = (typeof _newOpts.tabSize !== 'undefined') ? _newOpts.tabSize : this._options.tabSize;
            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 editorCommon.TextModelResolvedOptions({
                tabSize: tabSize,
                insertSpaces: insertSpaces,
                defaultEOL: this._options.defaultEOL,
                trimAutoWhitespace: trimAutoWhitespace
            });
            if (this._options.equals(newOpts)) {
                return;
            }
            var e = this._options.createChangeEvent(newOpts);
            this._options = newOpts;
            if (e.tabSize) {
                var newTabSize = this._options.tabSize;
                for (var i = 0, len = this._lines.length; i < len; i++) {
                    this._lines[i].updateTabSize(newTabSize);
                }
            }
            this._eventEmitter.emit(textModelEvents.TextModelEventType.ModelOptionsChanged, e);
        };
        TextModel.prototype.detectIndentation = function (defaultInsertSpaces, defaultTabSize) {
            this._assertNotDisposed();
            var lines = this._lines.map(function (line) { return line.text; });
            var guessedIndentation = indentationGuesser_1.guessIndentation(lines, defaultTabSize, defaultInsertSpaces);
            this.updateOptions({
                insertSpaces: guessedIndentation.insertSpaces,
                tabSize: guessedIndentation.tabSize
            });
        };
        TextModel._normalizeIndentationFromWhitespace = function (str, tabSize, insertSpaces) {
            var spacesCnt = 0;
            for (var i = 0; i < str.length; i++) {
                if (str.charAt(i) === '\t') {
                    spacesCnt += tabSize;
                }
                else {
                    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;
        };
        TextModel.normalizeIndentation = function (str, tabSize, insertSpaces) {
            var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(str);
            if (firstNonWhitespaceIndex === -1) {
                firstNonWhitespaceIndex = str.length;
            }
            return TextModel._normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex), tabSize, insertSpaces) + str.substring(firstNonWhitespaceIndex);
        };
        TextModel.prototype.normalizeIndentation = function (str) {
            this._assertNotDisposed();
            return TextModel.normalizeIndentation(str, this._options.tabSize, this._options.insertSpaces);
        };
        TextModel.prototype.getOneIndent = function () {
            this._assertNotDisposed();
            var tabSize = this._options.tabSize;
            var insertSpaces = this._options.insertSpaces;
            if (insertSpaces) {
                var result = '';
                for (var i = 0; i < tabSize; i++) {
                    result += ' ';
                }
                return result;
            }
            else {
                return '\t';
            }
        };
        TextModel.prototype.getVersionId = function () {
            this._assertNotDisposed();
            return this._versionId;
        };
        TextModel.prototype.mightContainRTL = function () {
            return this._mightContainRTL;
        };
        TextModel.prototype.mightContainNonBasicASCII = function () {
            return this._mightContainNonBasicASCII;
        };
        TextModel.prototype.getAlternativeVersionId = function () {
            this._assertNotDisposed();
            return this._alternativeVersionId;
        };
        TextModel.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].text.length + eolLength;
                }
                this._lineStarts = new prefixSumComputer_1.PrefixSumComputer(lineStartValues);
            }
        };
        TextModel.prototype.getOffsetAt = function (rawPosition) {
            this._assertNotDisposed();
            var position = this._validatePosition(rawPosition.lineNumber, rawPosition.column, false);
            this._ensureLineStarts();
            return this._lineStarts.getAccumulatedValue(position.lineNumber - 2) + position.column - 1;
        };
        TextModel.prototype.getPositionAt = function (offset) {
            this._assertNotDisposed();
            offset = Math.floor(offset);
            offset = Math.max(0, offset);
            this._ensureLineStarts();
            var out = this._lineStarts.getIndexOf(offset);
            var lineLength = this._lines[out.index].text.length;
            // Ensure we return a valid position
            return new position_1.Position(out.index + 1, Math.min(out.remainder + 1, lineLength + 1));
        };
        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.isDisposed = function () {
            return this._isDisposed;
        };
        TextModel.prototype.dispose = function () {
            this._isDisposed = true;
            // Null out members, such that any use of a disposed model will throw exceptions sooner rather than later
            this._lines = null;
            this._EOL = null;
            this._BOM = null;
            this._eventEmitter.dispose();
        };
        TextModel.prototype._emitContentChanged2 = function (startLineNumber, startColumn, endLineNumber, endColumn, rangeLength, text, isUndoing, isRedoing, isFlush) {
            var e = {
                changes: [{
                        range: new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn),
                        rangeLength: rangeLength,
                        text: text,
                    }],
                eol: this._EOL,
                versionId: this.getVersionId(),
                isUndoing: isUndoing,
                isRedoing: isRedoing,
                isFlush: isFlush
            };
            if (!this._isDisposing) {
                this._eventEmitter.emit(textModelEvents.TextModelEventType.ModelContentChanged, e);
            }
        };
        TextModel.prototype._resetValue = function (newValue) {
            this._constructLines(newValue);
            this._increaseVersionId();
        };
        TextModel.prototype.equals = function (other) {
            this._assertNotDisposed();
            if (this._BOM !== other.BOM) {
                return false;
            }
            if (this._EOL !== other.EOL) {
                return false;
            }
            if (this._lines.length !== other.lines.length) {
                return false;
            }
            for (var i = 0, len = this._lines.length; i < len; i++) {
                if (this._lines[i].text !== other.lines[i]) {
                    return false;
                }
            }
            return true;
        };
        TextModel.prototype.setValue = function (value) {
            this._assertNotDisposed();
            if (value === null) {
                // There's nothing to do
                return;
            }
            var textSource = textSource_1.TextSource.fromString(value, this._options.defaultEOL);
            this.setValueFromTextSource(textSource);
        };
        TextModel.prototype.setValueFromTextSource = function (newValue) {
            this._assertNotDisposed();
            if (newValue === 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._resetValue(newValue);
            this._emitModelRawContentChangedEvent(new textModelEvents.ModelRawContentChangedEvent([
                new textModelEvents.ModelRawFlush()
            ], this._versionId, false, false));
            this._emitContentChanged2(1, 1, endLineNumber, endColumn, oldModelValueLength, this.getValue(), false, false, true);
        };
        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._BOM + 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._BOM.length + fullModelValue;
            }
            return fullModelValue;
        };
        TextModel.prototype.getValueInRange = function (rawRange, eol) {
            if (eol === void 0) { eol = editorCommon.EndOfLinePreference.TextDefined; }
            this._assertNotDisposed();
            var range = this.validateRange(rawRange);
            if (range.isEmpty()) {
                return '';
            }
            if (range.startLineNumber === range.endLineNumber) {
                return this._lines[range.startLineNumber - 1].text.substring(range.startColumn - 1, range.endColumn - 1);
            }
            var lineEnding = this._getEndOfLine(eol), startLineIndex = range.startLineNumber - 1, endLineIndex = range.endLineNumber - 1, resultLines = [];
            resultLines.push(this._lines[startLineIndex].text.substring(range.startColumn - 1));
            for (var i = startLineIndex + 1; i < endLineIndex; i++) {
                resultLines.push(this._lines[i].text);
            }
            resultLines.push(this._lines[endLineIndex].text.substring(0, range.endColumn - 1));
            return resultLines.join(lineEnding);
        };
        TextModel.prototype.getValueLengthInRange = function (rawRange, eol) {
            if (eol === void 0) { eol = editorCommon.EndOfLinePreference.TextDefined; }
            this._assertNotDisposed();
            var range = this.validateRange(rawRange);
            if (range.isEmpty()) {
                return 0;
            }
            if (range.startLineNumber === range.endLineNumber) {
                return (range.endColumn - range.startColumn);
            }
            var startOffset = this.getOffsetAt(new position_1.Position(range.startLineNumber, range.startColumn));
            var endOffset = this.getOffsetAt(new position_1.Position(range.endLineNumber, range.endColumn));
            return endOffset - startOffset;
        };
        TextModel.prototype.isDominatedByLongLines = function () {
            this._assertNotDisposed();
            var smallLineCharCount = 0, longLineCharCount = 0, i, len, lines = this._lines, lineLength;
            for (i = 0, len = this._lines.length; i < len; i++) {
                lineLength = lines[i].text.length;
                if (lineLength >= exports.LONG_LINE_BOUNDARY) {
                    longLineCharCount += lineLength;
                }
                else {
                    smallLineCharCount += lineLength;
                }
            }
            return (longLineCharCount > smallLineCharCount);
        };
        TextModel.prototype.getLineCount = function () {
            this._assertNotDisposed();
            return this._lines.length;
        };
        TextModel.prototype.getLineContent = function (lineNumber) {
            this._assertNotDisposed();
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
            }
            return this._lines[lineNumber - 1].text;
        };
        TextModel.prototype.getIndentLevel = function (lineNumber) {
            this._assertNotDisposed();
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
            }
            return this._lines[lineNumber - 1].getIndentLevel();
        };
        TextModel.prototype._resetIndentRanges = function () {
            this._indentRanges = null;
        };
        TextModel.prototype._getIndentRanges = function () {
            if (!this._indentRanges) {
                this._indentRanges = indentRanges_1.computeRanges(this);
            }
            return this._indentRanges;
        };
        TextModel.prototype.getIndentRanges = function () {
            this._assertNotDisposed();
            var indentRanges = this._getIndentRanges();
            return indentRanges_1.IndentRange.deepCloneArr(indentRanges);
        };
        TextModel.prototype._toValidLineIndentGuide = function (lineNumber, indentGuide) {
            var lineIndentLevel = this._lines[lineNumber - 1].getIndentLevel();
            if (lineIndentLevel === -1) {
                return indentGuide;
            }
            var maxIndentGuide = Math.ceil(lineIndentLevel / this._options.tabSize);
            return Math.min(maxIndentGuide, indentGuide);
        };
        TextModel.prototype.getLineIndentGuide = function (lineNumber) {
            this._assertNotDisposed();
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
            }
            var indentRanges = this._getIndentRanges();
            for (var i = indentRanges.length - 1; i >= 0; i--) {
                var rng = indentRanges[i];
                if (rng.startLineNumber === lineNumber) {
                    return this._toValidLineIndentGuide(lineNumber, Math.ceil(rng.indent / this._options.tabSize));
                }
                if (rng.startLineNumber < lineNumber && lineNumber <= rng.endLineNumber) {
                    return this._toValidLineIndentGuide(lineNumber, 1 + Math.floor(rng.indent / this._options.tabSize));
                }
                if (rng.endLineNumber + 1 === lineNumber) {
                    var bestIndent = rng.indent;
                    while (i > 0) {
                        i--;
                        rng = indentRanges[i];
                        if (rng.endLineNumber + 1 === lineNumber) {
                            bestIndent = rng.indent;
                        }
                    }
                    return this._toValidLineIndentGuide(lineNumber, Math.ceil(bestIndent / this._options.tabSize));
                }
            }
            return 0;
        };
        TextModel.prototype.getLinesContent = function () {
            this._assertNotDisposed();
            var r = [];
            for (var i = 0, len = this._lines.length; i < len; i++) {
                r[i] = this._lines[i].text;
            }
            return r;
        };
        TextModel.prototype.getEOL = function () {
            this._assertNotDisposed();
            return this._EOL;
        };
        TextModel.prototype.setEOL = function (eol) {
            this._assertNotDisposed();
            var newEOL = (eol === editorCommon.EndOfLineSequence.CRLF ? '\r\n' : '\n');
            if (this._EOL === newEOL) {
                // Nothing to do
                return;
            }
            var oldFullModelRange = this.getFullModelRange();
            var oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
            var endLineNumber = this.getLineCount();
            var endColumn = this.getLineMaxColumn(endLineNumber);
            this._EOL = newEOL;
            this._lineStarts = null;
            this._increaseVersionId();
            this._emitModelRawContentChangedEvent(new textModelEvents.ModelRawContentChangedEvent([
                new textModelEvents.ModelRawEOLChanged()
            ], this._versionId, false, false));
            this._emitContentChanged2(1, 1, endLineNumber, endColumn, oldModelValueLength, this.getValue(), false, false, false);
        };
        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 ' + lineNumber + ' for `lineNumber`');
            }
            return this._lines[lineNumber - 1].text.length + 1;
        };
        TextModel.prototype.getLineFirstNonWhitespaceColumn = function (lineNumber) {
            this._assertNotDisposed();
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
            }
            var result = strings.firstNonWhitespaceIndex(this._lines[lineNumber - 1].text);
            if (result === -1) {
                return 0;
            }
            return result + 1;
        };
        TextModel.prototype.getLineLastNonWhitespaceColumn = function (lineNumber) {
            this._assertNotDisposed();
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
            }
            var result = strings.lastNonWhitespaceIndex(this._lines[lineNumber - 1].text);
            if (result === -1) {
                return 0;
            }
            return result + 2;
        };
        TextModel.prototype.validateLineNumber = function (lineNumber) {
            this._assertNotDisposed();
            if (lineNumber < 1) {
                lineNumber = 1;
            }
            if (lineNumber > this._lines.length) {
                lineNumber = this._lines.length;
            }
            return lineNumber;
        };
        /**
         * @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' ? _lineNumber : 1);
            var column = Math.floor(typeof _column === 'number' ? _column : 1);
            if (lineNumber < 1) {
                return new position_1.Position(1, 1);
            }
            if (lineNumber > this._lines.length) {
                return new position_1.Position(this._lines.length, this.getLineMaxColumn(this._lines.length));
            }
            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._lines[lineNumber - 1].text.charCodeAt(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();
            return this._validatePosition(position.lineNumber, position.column, true);
        };
        TextModel.prototype.validateRange = function (_range) {
            this._assertNotDisposed();
            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 startLineText = this._lines[startLineNumber - 1].text;
            var endLineText = this._lines[endLineNumber - 1].text;
            var charCodeBeforeStart = (startColumn > 1 ? startLineText.charCodeAt(startColumn - 2) : 0);
            var charCodeBeforeEnd = (endColumn > 1 && endColumn <= endLineText.length ? endLineText.charCodeAt(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();
            return this.getPositionAt(this.getOffsetAt(rawPosition) + offset);
        };
        TextModel.prototype.getFullModelRange = function () {
            this._assertNotDisposed();
            var lineCount = this.getLineCount();
            return new range_1.Range(1, 1, lineCount, this.getLineMaxColumn(lineCount));
        };
        TextModel.prototype._emitModelRawContentChangedEvent = function (e) {
            if (this._isDisposing) {
                // Do not confuse listeners by emitting any event after disposing
                return;
            }
            this._eventEmitter.emit(textModelEvents.TextModelEventType.ModelRawContentChanged2, e);
        };
        TextModel.prototype._constructLines = function (textSource) {
            var tabSize = this._options.tabSize;
            var rawLines = textSource.lines;
            var modelLines = new Array(rawLines.length);
            for (var i = 0, len = rawLines.length; i < len; i++) {
                modelLines[i] = this._createModelLine(rawLines[i], tabSize);
            }
            this._BOM = textSource.BOM;
            this._mightContainRTL = textSource.containsRTL;
            this._mightContainNonBasicASCII = !textSource.isBasicASCII;
            this._EOL = textSource.EOL;
            this._lines = modelLines;
            this._lineStarts = null;
            this._resetIndentRanges();
        };
        TextModel.prototype._getEndOfLine = function (eol) {
            switch (eol) {
                case editorCommon.EndOfLinePreference.LF:
                    return '\n';
                case editorCommon.EndOfLinePreference.CRLF:
                    return '\r\n';
                case editorCommon.EndOfLinePreference.TextDefined:
                    return this.getEOL();
            }
            throw new Error('Unknown EOL preference');
        };
        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();
            }
            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);
            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);
        };
        TextModel.MODEL_SYNC_LIMIT = 5 * 1024 * 1024; // 5 MB
        TextModel.MODEL_TOKENIZATION_LIMIT = 20 * 1024 * 1024; // 20 MB
        TextModel.MANY_MANY_LINES = 300 * 1000; // 300K lines
        TextModel.DEFAULT_CREATION_OPTIONS = {
            tabSize: editorOptions_1.EDITOR_MODEL_DEFAULTS.tabSize,
            insertSpaces: editorOptions_1.EDITOR_MODEL_DEFAULTS.insertSpaces,
            detectIndentation: false,
            defaultEOL: editorCommon.DefaultEndOfLine.LF,
            trimAutoWhitespace: editorOptions_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
        };
        return TextModel;
    }());
    exports.TextModel = TextModel;
});

define(__m[39/*vs/editor/common/controller/cursorCommon*/], __M([1/*require*/,0/*exports*/,12/*vs/editor/common/core/position*/,9/*vs/base/common/strings*/,93/*vs/editor/common/model/textModel*/,22/*vs/editor/common/core/selection*/,2/*vs/editor/common/core/range*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/,10/*vs/base/common/errors*/]), function (require, exports, position_1, strings, textModel_1, selection_1, range_1, languageConfigurationRegistry_1, errors_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var RevealTarget;
    (function (RevealTarget) {
        RevealTarget[RevealTarget["Primary"] = 0] = "Primary";
        RevealTarget[RevealTarget["TopMost"] = 1] = "TopMost";
        RevealTarget[RevealTarget["BottomMost"] = 2] = "BottomMost";
    })(RevealTarget = exports.RevealTarget || (exports.RevealTarget = {}));
    var CursorConfiguration = (function () {
        function CursorConfiguration(languageIdentifier, oneIndent, modelOptions, configuration) {
            var c = configuration.editor;
            this.readOnly = c.readOnly;
            this.tabSize = modelOptions.tabSize;
            this.insertSpaces = modelOptions.insertSpaces;
            this.oneIndent = oneIndent;
            this.pageSize = 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.autoClosingBrackets = c.autoClosingBrackets;
            this.autoIndent = c.autoIndent;
            this.autoClosingPairsOpen = {};
            this.autoClosingPairsClose = {};
            this.surroundingPairs = {};
            this.electricChars = {};
            var electricChars = CursorConfiguration._getElectricCharacters(languageIdentifier);
            if (electricChars) {
                for (var i = 0; i < electricChars.length; i++) {
                    this.electricChars[electricChars[i]] = true;
                }
            }
            var autoClosingPairs = CursorConfiguration._getAutoClosingPairs(languageIdentifier);
            if (autoClosingPairs) {
                for (var i = 0; i < autoClosingPairs.length; i++) {
                    this.autoClosingPairsOpen[autoClosingPairs[i].open] = autoClosingPairs[i].close;
                    this.autoClosingPairsClose[autoClosingPairs[i].close] = autoClosingPairs[i].open;
                }
            }
            var surroundingPairs = CursorConfiguration._getSurroundingPairs(languageIdentifier);
            if (surroundingPairs) {
                for (var i = 0; i < surroundingPairs.length; i++) {
                    this.surroundingPairs[surroundingPairs[i].open] = surroundingPairs[i].close;
                }
            }
        }
        CursorConfiguration.shouldRecreate = function (e) {
            return (e.layoutInfo
                || e.wordSeparators
                || e.emptySelectionClipboard
                || e.autoClosingBrackets
                || e.useTabStops
                || e.lineHeight
                || e.readOnly);
        };
        CursorConfiguration.prototype.normalizeIndentation = function (str) {
            return textModel_1.TextModel.normalizeIndentation(str, this.tabSize, 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._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 = (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 = (function () {
        function CursorContext(configuration, model, viewModel) {
            this.model = model;
            this.viewModel = viewModel;
            this.config = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOneIndent(), 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.getScrollTop = function () {
            return this.viewModel.viewLayout.getScrollTop();
        };
        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.getCompletelyVisibleModelRangeAtScrollTop = function (scrollTop) {
            var viewRange = this.viewModel.getCompletelyVisibleViewRangeAtScrollTop(scrollTop);
            return this.viewModel.coordinatesConverter.convertViewRangeToModelRange(viewRange);
        };
        CursorContext.prototype.getVerticalOffsetForViewLine = function (viewLineNumber) {
            return this.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewLineNumber);
        };
        return CursorContext;
    }());
    exports.CursorContext = CursorContext;
    var CursorState = (function () {
        function CursorState(modelState, viewState) {
            this.modelState = modelState;
            this.viewState = viewState;
        }
        CursorState.fromModelState = function (modelState) {
            return new CursorState(modelState, null);
        };
        CursorState.fromViewState = function (viewState) {
            return new CursorState(null, 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.ensureInEditableRange = function (context, states) {
            var model = context.model;
            if (!model.hasEditableRange()) {
                return states;
            }
            var modelEditableRange = model.getEditableRange();
            var viewEditableRange = context.convertModelRangeToViewRange(modelEditableRange);
            var result = [];
            for (var i = 0, len = states.length; i < len; i++) {
                var state = states[i];
                if (state.modelState) {
                    var newModelState = CursorState._ensureInEditableRange(state.modelState, modelEditableRange);
                    result[i] = newModelState ? CursorState.fromModelState(newModelState) : state;
                }
                else {
                    var newViewState = CursorState._ensureInEditableRange(state.viewState, viewEditableRange);
                    result[i] = newViewState ? CursorState.fromViewState(newViewState) : state;
                }
            }
            return result;
        };
        CursorState._ensureInEditableRange = function (state, editableRange) {
            var position = state.position;
            if (position.lineNumber < editableRange.startLineNumber || (position.lineNumber === editableRange.startLineNumber && position.column < editableRange.startColumn)) {
                return new SingleCursorState(state.selectionStart, state.selectionStartLeftoverVisibleColumns, new position_1.Position(editableRange.startLineNumber, editableRange.startColumn), 0);
            }
            if (position.lineNumber > editableRange.endLineNumber || (position.lineNumber === editableRange.endLineNumber && position.column > editableRange.endColumn)) {
                return new SingleCursorState(state.selectionStart, state.selectionStartLeftoverVisibleColumns, new position_1.Position(editableRange.endLineNumber, editableRange.endColumn), 0);
            }
            return null;
        };
        CursorState.prototype.equals = function (other) {
            return (this.viewState.equals(other.viewState) && this.modelState.equals(other.viewState));
        };
        return CursorState;
    }());
    exports.CursorState = CursorState;
    var EditOperationResult = (function () {
        function EditOperationResult(commands, opts) {
            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 = (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.nextTabStop(result, tabSize);
                }
                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.nextTabStop(beforeVisibleColumn, tabSize);
                }
                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.nextTabStop = function (visibleColumn, tabSize) {
            return visibleColumn + tabSize - visibleColumn % tabSize;
        };
        /**
         * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)
         */
        CursorColumns.prevTabStop = function (column, tabSize) {
            return column - 1 - (column - 1) % tabSize;
        };
        return CursorColumns;
    }());
    exports.CursorColumns = CursorColumns;
});

define(__m[167/*vs/editor/common/commands/shiftCommand*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,39/*vs/editor/common/controller/cursorCommon*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, strings, cursorCommon_1, range_1, selection_1, languageConfigurationRegistry_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ShiftCommand = (function () {
        function ShiftCommand(range, opts) {
            this._opts = opts;
            this._selection = range;
            this._useLastEditRangeForCursorEndPosition = false;
            this._selectionStartColumnStaysPut = false;
        }
        ShiftCommand.unshiftIndentCount = function (line, column, tabSize) {
            // Determine the visible column where the content starts
            var contentStartVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize);
            var desiredTabStop = cursorCommon_1.CursorColumns.prevTabStop(contentStartVisibleColumn, tabSize);
            // The `desiredTabStop` is a multiple of `tabSize` => determine the number of indents
            return desiredTabStop / tabSize;
        };
        ShiftCommand.shiftIndentCount = function (line, column, tabSize) {
            // Determine the visible column where the content starts
            var contentStartVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize);
            var desiredTabStop = cursorCommon_1.CursorColumns.nextTabStop(contentStartVisibleColumn, tabSize);
            // The `desiredTabStop` is a multiple of `tabSize` => determine the number of indents
            return desiredTabStop / tabSize;
        };
        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 tabSize = this._opts.tabSize;
            var oneIndent = this._opts.oneIndent;
            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) {
                // indents[i] represents i * oneIndent
                var indents = ['', oneIndent];
                // 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 % tabSize !== 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
                            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 < tabSize; 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 desiredIndentCount = void 0;
                    if (this._opts.isUnshift) {
                        desiredIndentCount = ShiftCommand.unshiftIndentCount(lineText, indentationEndIndex + 1, tabSize);
                    }
                    else {
                        desiredIndentCount = ShiftCommand.shiftIndentCount(lineText, indentationEndIndex + 1, tabSize);
                    }
                    // Fill `indents`, as needed
                    for (var j = indents.length; j <= desiredIndentCount; j++) {
                        indents[j] = indents[j - 1] + oneIndent;
                    }
                    this._addEditOperation(builder, new range_1.Range(lineNumber, 1, lineNumber, indentationEndIndex + 1), indents[desiredIndentCount]);
                    if (lineNumber === startLine) {
                        // Force the startColumn to stay put because we're inserting after it
                        this._selectionStartColumnStaysPut = (this._selection.startColumn <= indentationEndIndex + 1);
                    }
                }
            }
            else {
                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, tabSize);
                        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() === selection_1.SelectionDirection.LTR) {
                    return new selection_1.Selection(result.startLineNumber, initialStartColumn, result.endLineNumber, result.endColumn);
                }
                return new selection_1.Selection(result.endLineNumber, result.endColumn, result.startLineNumber, initialStartColumn);
            }
            return result;
        };
        return ShiftCommand;
    }());
    exports.ShiftCommand = ShiftCommand;
});

define(__m[311/*vs/editor/common/controller/cursorColumnSelection*/], __M([1/*require*/,0/*exports*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,39/*vs/editor/common/controller/cursorCommon*/]), function (require, exports, position_1, range_1, cursorCommon_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ColumnSelection = (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;
});

define(__m[169/*vs/editor/common/controller/cursorMoveOperations*/], __M([1/*require*/,0/*exports*/,39/*vs/editor/common/controller/cursorCommon*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/]), function (require, exports, cursorCommon_1, position_1, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CursorPosition = (function () {
        function CursorPosition(lineNumber, column, leftoverVisibleColumns) {
            this.lineNumber = lineNumber;
            this.column = column;
            this.leftoverVisibleColumns = leftoverVisibleColumns;
        }
        return CursorPosition;
    }());
    exports.CursorPosition = CursorPosition;
    var MoveOperations = (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;
});

define(__m[170/*vs/editor/common/controller/cursorDeleteOperations*/], __M([1/*require*/,0/*exports*/,73/*vs/editor/common/commands/replaceCommand*/,39/*vs/editor/common/controller/cursorCommon*/,2/*vs/editor/common/core/range*/,169/*vs/editor/common/controller/cursorMoveOperations*/,9/*vs/base/common/strings*/]), function (require, exports, replaceCommand_1, cursorCommon_1, range_1, cursorMoveOperations_1, strings) {
    /*---------------------------------------------------------------------------------------------
     *  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 DeleteOperations = (function () {
        function DeleteOperations() {
        }
        DeleteOperations.deleteRight = function (config, model, selections) {
            var commands = [];
            var shouldPushStackElementBefore = false;
            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) {
                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;
                }
                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 (config, model, selections) {
            if (this._isAutoClosingPairDelete(config, model, selections)) {
                return this._runAutoClosingPairDelete(config, model, selections);
            }
            var commands = [];
            var shouldPushStackElementBefore = false;
            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
                            ? lineContent.length + 1
                            : firstNonWhitespaceIndex + 1);
                        if (position.column <= lastIndentationColumn) {
                            var fromVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, position);
                            var toVisibleColumn = cursorCommon_1.CursorColumns.prevTabStop(fromVisibleColumn, config.tabSize);
                            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(commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: true
            });
        };
        return DeleteOperations;
    }());
    exports.DeleteOperations = DeleteOperations;
});

define(__m[119/*vs/editor/common/controller/cursorTypeOperations*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,73/*vs/editor/common/commands/replaceCommand*/,39/*vs/editor/common/controller/cursorCommon*/,2/*vs/editor/common/core/range*/,9/*vs/base/common/strings*/,167/*vs/editor/common/commands/shiftCommand*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/,60/*vs/editor/common/modes/languageConfiguration*/,441/*vs/editor/common/commands/surroundSelectionCommand*/,94/*vs/editor/common/controller/wordCharacterClassifier*/]), function (require, exports, errors_1, replaceCommand_1, cursorCommon_1, range_1, strings, shiftCommand_1, languageConfigurationRegistry_1, languageConfiguration_1, surroundSelectionCommand_1, wordCharacterClassifier_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var TypeOperations = (function () {
        function TypeOperations() {
        }
        TypeOperations.indent = 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: false,
                    tabSize: config.tabSize,
                    oneIndent: config.oneIndent,
                    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,
                    oneIndent: config.oneIndent,
                    useTabStops: config.useTabStops
                });
            }
            return commands;
        };
        TypeOperations.shiftIndent = function (config, indentation, count) {
            count = count || 1;
            var desiredIndentCount = shiftCommand_1.ShiftCommand.shiftIndentCount(indentation, indentation.length + count, config.tabSize);
            var newIndentation = '';
            for (var i = 0; i < desiredIndentCount; i++) {
                newIndentation += '\t';
            }
            return newIndentation;
        };
        TypeOperations.unshiftIndent = function (config, indentation, count) {
            count = count || 1;
            var desiredIndentCount = shiftCommand_1.ShiftCommand.unshiftIndentCount(indentation, indentation.length + count, config.tabSize);
            var newIndentation = '';
            for (var i = 0; i < desiredIndentCount; i++) {
                newIndentation += '\t';
            }
            return newIndentation;
        };
        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(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(commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: true
            });
        };
        TypeOperations._distributePasteToCursors = function (selections, pasteOnNewLine, text) {
            if (pasteOnNewLine) {
                return null;
            }
            if (selections.length === 1) {
                return null;
            }
            for (var i = 0; i < selections.length; i++) {
                if (selections[i].startLineNumber !== selections[i].endLineNumber) {
                    return null;
                }
            }
            var pastePieces = text.split(/\r\n|\r|\n/);
            if (pastePieces.length !== selections.length) {
                return null;
            }
            return pastePieces;
        };
        TypeOperations.paste = function (config, model, selections, pasteOnNewLine, text) {
            var distributedPaste = this._distributePasteToCursors(selections, pasteOnNewLine, text);
            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;
            var indentation;
            var expectedIndentAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getInheritIndentForLine(model, lineNumber, false);
            if (expectedIndentAction) {
                action = expectedIndentAction.action;
                indentation = expectedIndentAction.indentation;
            }
            else if (lineNumber > 1) {
                var lastLineNumber = lineNumber - 1;
                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 tabSize = config.tabSize;
                var spacesCnt = tabSize - (visibleColumnFromColumn % tabSize);
                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)) {
                        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,
                        oneIndent: config.oneIndent,
                        useTabStops: config.useTabStops
                    });
                }
            }
            return commands;
        };
        TypeOperations.replacePreviousChar = function (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(commands, {
                shouldPushStackElementBefore: false,
                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) {
            var r = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(model, range);
            if (r) {
                var enterAction = r.enterAction;
                var indentation_1 = r.indentation;
                if (enterAction.indentAction === languageConfiguration_1.IndentAction.None) {
                    // Nothing special
                    return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation_1 + enterAction.appendText), keepPosition);
                }
                else if (enterAction.indentAction === languageConfiguration_1.IndentAction.Indent) {
                    // Indent once
                    return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation_1 + enterAction.appendText), keepPosition);
                }
                else if (enterAction.indentAction === languageConfiguration_1.IndentAction.IndentOutdent) {
                    // Ultra special
                    var normalIndent = config.normalizeIndentation(indentation_1);
                    var increasedIndent = config.normalizeIndentation(indentation_1 + 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_1);
                    return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(actualIndentation + enterAction.appendText), keepPosition);
                }
            }
            // no enter rules applied, we should check indentation rules then.
            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.tabSize);
                        }
                        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._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) {
            if (!config.autoClosingBrackets || !config.autoClosingPairsClose.hasOwnProperty(ch)) {
                return false;
            }
            for (var i = 0, len = selections.length; i < len; i++) {
                var selection = selections[i];
                if (!selection.isEmpty()) {
                    return false;
                }
                var position = selection.getPosition();
                var lineText = model.getLineContent(position.lineNumber);
                var afterCharacter = lineText.charAt(position.column - 1);
                if (afterCharacter !== ch) {
                    return false;
                }
            }
            return true;
        };
        TypeOperations._runAutoClosingCloseCharType = function (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(commands, {
                shouldPushStackElementBefore: false,
                shouldPushStackElementAfter: false
            });
        };
        TypeOperations._isAutoClosingOpenCharType = function (config, model, selections, ch) {
            if (!config.autoClosingBrackets || !config.autoClosingPairsOpen.hasOwnProperty(ch)) {
                return false;
            }
            for (var i = 0, len = selections.length; i < len; i++) {
                var selection = selections[i];
                if (!selection.isEmpty()) {
                    return false;
                }
                var position = selection.getPosition();
                var lineText = model.getLineContent(position.lineNumber);
                // Do not auto-close ' or " after a word character
                if ((ch === '\'' || ch === '"') && position.column > 1) {
                    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 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;
                        }
                    }
                    if (!isBeforeCloseBrace && !/\s/.test(characterAfter)) {
                        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 (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(commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: false
            });
        };
        TypeOperations._isSurroundSelectionType = function (config, model, selections, ch) {
            if (!config.autoClosingBrackets || !config.surroundingPairs.hasOwnProperty(ch)) {
                return false;
            }
            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;
                }
            }
            return true;
        };
        TypeOperations._runSurroundSelectionType = function (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(commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: true
            });
        };
        TypeOperations._typeInterceptorElectricChar = function (config, model, selections, ch) {
            if (!config.electricChars.hasOwnProperty(ch) || !selections.isEmpty()) {
                return null;
            }
            var position = selections.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);
            }
            if (!electricAction) {
                return null;
            }
            if (electricAction.appendText) {
                var command = new replaceCommand_1.ReplaceCommandWithOffsetCursorState(selections, ch + electricAction.appendText, 0, -electricAction.appendText.length);
                return new cursorCommon_1.EditOperationResult([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([command], {
                        shouldPushStackElementBefore: false,
                        shouldPushStackElementAfter: true
                    });
                }
            }
            return null;
        };
        TypeOperations.typeWithInterceptors = function (config, model, selections, ch) {
            if (ch === '\n') {
                var commands = [];
                for (var i = 0, len = selections.length; i < len; i++) {
                    commands[i] = TypeOperations._enter(config, model, false, selections[i]);
                }
                return new cursorCommon_1.EditOperationResult(commands, {
                    shouldPushStackElementBefore: true,
                    shouldPushStackElementAfter: false,
                });
            }
            if (config.autoIndent) {
                var indentCommand = this._runAutoIndentType(config, model, selections[0], ch);
                if (indentCommand) {
                    return new cursorCommon_1.EditOperationResult([indentCommand], {
                        shouldPushStackElementBefore: true,
                        shouldPushStackElementAfter: false,
                    });
                }
            }
            if (this._isAutoClosingCloseCharType(config, model, selections, ch)) {
                return this._runAutoClosingCloseCharType(config, model, selections, ch);
            }
            if (this._isAutoClosingOpenCharType(config, model, selections, ch)) {
                return this._runAutoClosingOpenCharType(config, model, selections, ch);
            }
            if (this._isSurroundSelectionType(config, model, selections, ch)) {
                return this._runSurroundSelectionType(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 (selections.length === 1) {
                var r = this._typeInterceptorElectricChar(config, model, selections[0], ch);
                if (r) {
                    return r;
                }
            }
            return this.typeWithoutInterceptors(config, model, selections, ch);
        };
        TypeOperations.typeWithoutInterceptors = function (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(commands, {
                shouldPushStackElementBefore: false,
                shouldPushStackElementAfter: false
            });
        };
        TypeOperations.lineInsertBefore = function (config, model, selections) {
            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) {
            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;
});

define(__m[172/*vs/editor/common/controller/cursorWordOperations*/], __M([1/*require*/,0/*exports*/,39/*vs/editor/common/controller/cursorCommon*/,12/*vs/editor/common/core/position*/,94/*vs/editor/common/controller/wordCharacterClassifier*/,9/*vs/base/common/strings*/,2/*vs/editor/common/core/range*/]), function (require, exports, cursorCommon_1, position_1, wordCharacterClassifier_1, strings, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var WordType;
    (function (WordType) {
        WordType[WordType["None"] = 0] = "None";
        WordType[WordType["Regular"] = 1] = "Regular";
        WordType[WordType["Separator"] = 2] = "Separator";
    })(WordType || (WordType = {}));
    var WordNavigationType;
    (function (WordNavigationType) {
        WordNavigationType[WordNavigationType["WordStart"] = 0] = "WordStart";
        WordNavigationType[WordNavigationType["WordEnd"] = 1] = "WordEnd";
    })(WordNavigationType = exports.WordNavigationType || (exports.WordNavigationType = {}));
    var WordOperations = (function () {
        function WordOperations() {
        }
        WordOperations._createWord = function (lineContent, wordType, start, end) {
            // console.log('WORD ==> ' + start + ' => ' + end + ':::: <<<' + lineContent.substring(start, end) + '>>>');
            return { start: start, end: end, wordType: wordType };
        };
        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, 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, 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, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
                    }
                }
            }
            if (wordType !== 0 /* None */) {
                return this._createWord(lineContent, wordType, 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, 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, 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, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
                    }
                }
            }
            if (wordType !== 0 /* None */) {
                return this._createWord(lineContent, wordType, 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;
            if (column === 1) {
                if (lineNumber > 1) {
                    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) {
                    column = prevWordOnLine.start + 1;
                }
                else {
                    column = 1;
                }
            }
            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 {
                    column = 1;
                }
            }
            return new position_1.Position(lineNumber, column);
        };
        WordOperations.moveWordRight = function (wordSeparators, model, position, wordNavigationType) {
            var lineNumber = position.lineNumber;
            var column = position.column;
            if (column === model.getLineMaxColumn(lineNumber)) {
                if (lineNumber < model.getLineCount()) {
                    lineNumber = lineNumber + 1;
                    column = 1;
                }
            }
            var nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, column));
            if (wordNavigationType === 1 /* WordEnd */) {
                if (nextWordOnLine) {
                    column = nextWordOnLine.end + 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 {
                    column = model.getLineMaxColumn(lineNumber);
                }
            }
            return new position_1.Position(lineNumber, column);
        };
        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._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 === 1 /* 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.word = function (config, model, cursor, inSelectionMode, position) {
            var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(config.wordSeparators);
            var prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
            var isInPrevWord = (prevWord && prevWord.wordType === 1 /* Regular */ && prevWord.start < position.column - 1 && position.column - 1 <= prevWord.end);
            var nextWord = WordOperations._findNextWordOnLine(wordSeparators, model, position);
            var isInNextWord = (nextWord && nextWord.wordType === 1 /* Regular */ && nextWord.start < position.column - 1 && position.column - 1 <= nextWord.end);
            if (!inSelectionMode || !cursor.hasSelection()) {
                // Entering word selection for the first time
                var startColumn_1;
                var endColumn_1;
                if (isInPrevWord) {
                    startColumn_1 = prevWord.start + 1;
                    endColumn_1 = prevWord.end + 1;
                }
                else if (isInNextWord) {
                    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 (isInPrevWord) {
                startColumn = prevWord.start + 1;
                endColumn = prevWord.end + 1;
            }
            else if (isInNextWord) {
                startColumn = nextWord.start + 1;
                endColumn = nextWord.end + 1;
            }
            else {
                startColumn = position.column;
                endColumn = position.column;
            }
            var lineNumber = position.lineNumber;
            var column;
            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(cursor.hasSelection(), lineNumber, column, 0);
        };
        return WordOperations;
    }());
    exports.WordOperations = WordOperations;
});

define(__m[173/*vs/editor/common/controller/cursorMoveCommands*/], __M([1/*require*/,0/*exports*/,39/*vs/editor/common/controller/cursorCommon*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,169/*vs/editor/common/controller/cursorMoveOperations*/,172/*vs/editor/common/controller/cursorWordOperations*/,29/*vs/base/common/types*/]), function (require, exports, cursorCommon_1, position_1, range_1, cursorMoveOperations_1, cursorWordOperations_1, types) {
    /*---------------------------------------------------------------------------------------------
     *  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 CursorMoveCommands = (function () {
        function CursorMoveCommands() {
        }
        CursorMoveCommands.addCursorDown = function (context, cursors) {
            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);
                result[resultLen++] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.translateDown(context.config, context.viewModel, cursor.viewState));
            }
            return result;
        };
        CursorMoveCommands.addCursorUp = function (context, cursors) {
            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);
                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) {
            if (context.model.hasEditableRange()) {
                // Toggle between selecting editable range and selecting the entire buffer
                var editableRange = context.model.getEditableRange();
                var selection = cursor.modelState.selection;
                if (!selection.equalsRange(editableRange)) {
                    // Selection is not editable range => select editable range
                    return cursorCommon_1.CursorState.fromModelState(new cursorCommon_1.SingleCursorState(new range_1.Range(editableRange.startLineNumber, editableRange.startColumn, editableRange.startLineNumber, editableRange.startColumn), 0, new position_1.Position(editableRange.endLineNumber, editableRange.endColumn), 0));
                }
            }
            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];
                result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveLeft(context.config, context.viewModel, cursor.viewState, inSelectionMode, noOfColumns));
            }
            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];
                result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveRight(context.config, context.viewModel, cursor.viewState, inSelectionMode, noOfColumns));
            }
            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
                }
            ]
        };
        /**
         * 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;
        ;
        var Direction;
        (function (Direction) {
            Direction[Direction["Left"] = 0] = "Left";
            Direction[Direction["Right"] = 1] = "Right";
            Direction[Direction["Up"] = 2] = "Up";
            Direction[Direction["Down"] = 3] = "Down";
            Direction[Direction["WrappedLineStart"] = 4] = "WrappedLineStart";
            Direction[Direction["WrappedLineFirstNonWhitespaceCharacter"] = 5] = "WrappedLineFirstNonWhitespaceCharacter";
            Direction[Direction["WrappedLineColumnCenter"] = 6] = "WrappedLineColumnCenter";
            Direction[Direction["WrappedLineEnd"] = 7] = "WrappedLineEnd";
            Direction[Direction["WrappedLineLastNonWhitespaceCharacter"] = 8] = "WrappedLineLastNonWhitespaceCharacter";
            Direction[Direction["ViewPortTop"] = 9] = "ViewPortTop";
            Direction[Direction["ViewPortCenter"] = 10] = "ViewPortCenter";
            Direction[Direction["ViewPortBottom"] = 11] = "ViewPortBottom";
            Direction[Direction["ViewPortIfOutside"] = 12] = "ViewPortIfOutside";
        })(Direction = CursorMove.Direction || (CursorMove.Direction = {}));
        ;
        var Unit;
        (function (Unit) {
            Unit[Unit["None"] = 0] = "None";
            Unit[Unit["Line"] = 1] = "Line";
            Unit[Unit["WrappedLine"] = 2] = "WrappedLine";
            Unit[Unit["Character"] = 3] = "Character";
            Unit[Unit["HalfLine"] = 4] = "HalfLine";
        })(Unit = CursorMove.Unit || (CursorMove.Unit = {}));
        ;
    })(CursorMove = exports.CursorMove || (exports.CursorMove = {}));
});

define(__m[317/*vs/editor/common/controller/oneCursor*/], __M([1/*require*/,0/*exports*/,39/*vs/editor/common/controller/cursorCommon*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/]), function (require, exports, cursorCommon_1, position_1, range_1, selection_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var OneCursor = (function () {
        function OneCursor(context) {
            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) {
            context.model._removeMarker(this._selStartMarker);
            context.model._removeMarker(this._selEndMarker);
        };
        OneCursor.prototype.asCursorState = function () {
            return new cursorCommon_1.CursorState(this.modelState, this.viewState);
        };
        OneCursor.prototype.readSelectionFromMarkers = function (context) {
            var start = context.model._getMarker(this._selStartMarker);
            var end = context.model._getMarker(this._selEndMarker);
            if (this.modelState.selection.getDirection() === selection_1.SelectionDirection.LTR) {
                return new selection_1.Selection(start.lineNumber, start.column, end.lineNumber, end.column);
            }
            return new selection_1.Selection(end.lineNumber, end.column, start.lineNumber, start.column);
        };
        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) {
                // 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);
            }
            if (this.modelState && this.viewState && this.modelState.equals(modelState) && this.viewState.equals(viewState)) {
                // No-op, early return
                return;
            }
            this.modelState = modelState;
            this.viewState = viewState;
            this._selStartMarker = this._ensureMarker(context, this._selStartMarker, this.modelState.selection.startLineNumber, this.modelState.selection.startColumn, true);
            this._selEndMarker = this._ensureMarker(context, this._selEndMarker, this.modelState.selection.endLineNumber, this.modelState.selection.endColumn, false);
        };
        OneCursor.prototype._ensureMarker = function (context, markerId, lineNumber, column, stickToPreviousCharacter) {
            if (!markerId) {
                return context.model._addMarker(0, lineNumber, column, stickToPreviousCharacter);
            }
            else {
                context.model._changeMarker(markerId, lineNumber, column);
                context.model._changeMarkerStickiness(markerId, stickToPreviousCharacter);
                return markerId;
            }
        };
        return OneCursor;
    }());
    exports.OneCursor = OneCursor;
});

define(__m[318/*vs/editor/common/controller/cursorCollection*/], __M([1/*require*/,0/*exports*/,317/*vs/editor/common/controller/oneCursor*/,22/*vs/editor/common/core/selection*/,39/*vs/editor/common/controller/cursorCommon*/]), function (require, exports, oneCursor_1, selection_1, cursorCommon_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CursorCollection = (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.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,
                    viewSelection: cursors[i].viewState.selection
                });
            }
            sortedCursors.sort(function (a, b) {
                if (a.viewSelection.startLineNumber === b.viewSelection.startLineNumber) {
                    return a.viewSelection.startColumn - b.viewSelection.startColumn;
                }
                return a.viewSelection.startLineNumber - b.viewSelection.startLineNumber;
            });
            for (var sortedCursorIndex = 0; sortedCursorIndex < sortedCursors.length - 1; sortedCursorIndex++) {
                var current = sortedCursors[sortedCursorIndex];
                var next = sortedCursors[sortedCursorIndex + 1];
                var currentViewSelection = current.viewSelection;
                var nextViewSelection = next.viewSelection;
                var shouldMergeCursors = void 0;
                if (nextViewSelection.isEmpty() || currentViewSelection.isEmpty()) {
                    // Merge touching cursors if one of them is collapsed
                    shouldMergeCursors = nextViewSelection.getStartPosition().isBeforeOrEqual(currentViewSelection.getEndPosition());
                }
                else {
                    // Merge only overlapping cursors (i.e. allow touching ranges)
                    shouldMergeCursors = nextViewSelection.getStartPosition().isBefore(currentViewSelection.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 j = 0; j < sortedCursors.length; j++) {
                        if (sortedCursors[j].index > looserIndex) {
                            sortedCursors[j].index--;
                        }
                    }
                    cursors.splice(looserIndex, 1);
                    sortedCursors.splice(looserSortedCursorIndex, 1);
                    this._removeSecondaryCursor(looserIndex - 1);
                    sortedCursorIndex--;
                }
            }
        };
        return CursorCollection;
    }());
    exports.CursorCollection = CursorCollection;
});

define(__m[319/*vs/editor/contrib/linesOperations/common/moveLinesCommand*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/,167/*vs/editor/common/commands/shiftCommand*/,263/*vs/editor/contrib/indentation/common/indentUtils*/,60/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, strings, range_1, selection_1, languageConfigurationRegistry_1, shiftCommand_1, IndentUtil, languageConfiguration_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MoveLinesCommand = (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 tabSize = model.getOptions().tabSize;
            var insertSpaces = model.getOptions().insertSpaces;
            var indentConverter = this.buildIndentConverter(tabSize);
            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, movingLineText;
                if (this._isMovingDown) {
                    movingLineNumber = s.endLineNumber + 1;
                    movingLineText = model.getLineContent(movingLineNumber);
                    // Delete line that needs to be moved
                    builder.addEditOperation(new range_1.Range(movingLineNumber - 1, model.getLineMaxColumn(movingLineNumber - 1), movingLineNumber, model.getLineMaxColumn(movingLineNumber)), null);
                    var insertingText_1 = movingLineText;
                    if (this.isAutoIndent(model, s)) {
                        var movingLineMatchResult = this.matchEnterRule(model, indentConverter, tabSize, movingLineNumber, s.startLineNumber - 1);
                        // if s.startLineNumber - 1 matches onEnter rule, we still honor that.
                        if (movingLineMatchResult !== null) {
                            var oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber));
                            var newSpaceCnt = movingLineMatchResult + IndentUtil.getSpaceCnt(oldIndentation, tabSize);
                            var newIndentation = IndentUtil.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);
                                }
                                else {
                                    return model.getLineContent(lineNumber);
                                }
                            };
                            var indentOfMovingLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber, indentConverter);
                            if (indentOfMovingLine !== null) {
                                var oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber));
                                var newSpaceCnt = IndentUtil.getSpaceCnt(indentOfMovingLine, tabSize);
                                var oldSpaceCnt = IndentUtil.getSpaceCnt(oldIndentation, tabSize);
                                if (newSpaceCnt !== oldSpaceCnt) {
                                    var newIndentation = IndentUtil.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), s.startLineNumber + 1, indentConverter);
                            if (newIndentatOfMovingBlock !== null) {
                                var oldIndentation = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber));
                                var newSpaceCnt = IndentUtil.getSpaceCnt(newIndentatOfMovingBlock, tabSize);
                                var oldSpaceCnt = IndentUtil.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 = s.startLineNumber - 1;
                    movingLineText = model.getLineContent(movingLineNumber);
                    // Delete line that needs to be moved
                    builder.addEditOperation(new range_1.Range(movingLineNumber, 1, movingLineNumber + 1, 1), null);
                    // Insert line that needs to be moved after
                    builder.addEditOperation(new range_1.Range(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), '\n' + movingLineText);
                    if (this.isAutoIndent(model, s)) {
                        virtualModel.getLineContent = function (lineNumber) {
                            if (lineNumber === movingLineNumber) {
                                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, indentConverter);
                            if (indentOfFirstLine !== null) {
                                // adjust the indentation of the moving block
                                var oldIndent = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber));
                                var newSpaceCnt = IndentUtil.getSpaceCnt(indentOfFirstLine, tabSize);
                                var oldSpaceCnt = IndentUtil.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) {
            return {
                shiftIndent: function (indentation) {
                    var desiredIndentCount = shiftCommand_1.ShiftCommand.shiftIndentCount(indentation, indentation.length + 1, tabSize);
                    var newIndentation = '';
                    for (var i = 0; i < desiredIndentCount; i++) {
                        newIndentation += '\t';
                    }
                    return newIndentation;
                },
                unshiftIndent: function (indentation) {
                    var desiredIndentCount = shiftCommand_1.ShiftCommand.unshiftIndentCount(indentation, indentation.length + 1, tabSize);
                    var newIndentation = '';
                    for (var i = 0; i < desiredIndentCount; i++) {
                        newIndentation += '\t';
                    }
                    return newIndentation;
                }
            };
        };
        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 & 2 /* DECREASE_MASK */) {
                        newIndentation = indentConverter.unshiftIndent(newIndentation);
                    }
                    var newSpaceCnt = IndentUtil.getSpaceCnt(newIndentation, tabSize);
                    var oldSpaceCnt = IndentUtil.getSpaceCnt(oldIndentation, tabSize);
                    return newSpaceCnt - oldSpaceCnt;
                }
            }
            return null;
        };
        MoveLinesCommand.prototype.trimLeft = function (str) {
            return str.replace(/^\s+/, '');
        };
        MoveLinesCommand.prototype.isAutoIndent = function (model, selection) {
            if (!this._autoIndent) {
                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 = IndentUtil.getSpaceCnt(originalIndent, tabSize);
                var newSpacesCnt = originalSpacesCnt + offset;
                var newIndent = IndentUtil.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;
});

define(__m[320/*vs/nls!vs/editor/common/controller/cursor*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/controller/cursor", data); });










define(__m[321/*vs/editor/common/controller/cursor*/], __M([1/*require*/,0/*exports*/,320/*vs/nls!vs/editor/common/controller/cursor*/,9/*vs/base/common/strings*/,10/*vs/base/common/errors*/,318/*vs/editor/common/controller/cursorCollection*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,20/*vs/editor/common/editorCommon*/,39/*vs/editor/common/controller/cursorCommon*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/,170/*vs/editor/common/controller/cursorDeleteOperations*/,119/*vs/editor/common/controller/cursorTypeOperations*/,55/*vs/editor/common/model/textModelEvents*/,54/*vs/editor/common/controller/cursorEvents*/,57/*vs/editor/common/view/viewEvents*/,11/*vs/base/common/event*/]), function (require, exports, nls, strings, errors_1, cursorCollection_1, range_1, selection_1, editorCommon, cursorCommon_1, languageConfigurationRegistry_1, cursorDeleteOperations_1, cursorTypeOperations_1, textModelEvents_1, cursorEvents_1, viewEvents, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    // import { ScreenReaderMessageGenerator } from "vs/editor/common/controller/accGenerator";
    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 = (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 = (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 = (function (_super) {
        __extends(Cursor, _super);
        function Cursor(configuration, model, viewModel) {
            var _this = _super.call(this) || this;
            _this._onDidChange = _this._register(new event_1.Emitter());
            _this.onDidChange = _this._onDidChange.event;
            _this._configuration = configuration;
            _this._model = model;
            _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._register(_this._model.addBulkListener(function (events) {
                if (_this._isHandling) {
                    return;
                }
                var hadContentChange = false;
                var hadFlushEvent = false;
                for (var i = 0, len = events.length; i < len; i++) {
                    var event_2 = events[i];
                    var eventType = event_2.type;
                    if (eventType === textModelEvents_1.TextModelEventType.ModelRawContentChanged2) {
                        hadContentChange = true;
                        var rawChangeEvent = event_2.data;
                        hadFlushEvent = hadFlushEvent || rawChangeEvent.containsEvent(1 /* Flush */);
                    }
                }
                if (!hadContentChange) {
                    return;
                }
                _this._onModelContentChanged(hadFlushEvent);
            }));
            _this._register(viewModel.addEventListener(function (events) {
                if (!containsLineMappingChanged(events)) {
                    return;
                }
                // Ensure valid state
                _this.setStates('viewModel', cursorEvents_1.CursorChangeReason.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(languageConfigurationRegistry_1.LanguageConfigurationRegistry.onDidChange(function () {
                // TODO@Alex: react only if certain supports changed? (and if my model's mode changed)
                updateCursorContext();
            }));
            _this._register(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) {
            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) {
            this._revealRange(target, 0 /* Simple */, horizontal);
        };
        Cursor.prototype.revealRange = function (revealHorizontal, viewRange, verticalType) {
            this.emitCursorRevealRange(viewRange, verticalType, revealHorizontal);
        };
        Cursor.prototype.scrollTo = function (desiredScrollTop) {
            this._viewModel.viewLayout.setScrollPosition({
                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', cursorEvents_1.CursorChangeReason.NotSet, cursorCommon_1.CursorState.fromModelSelections(desiredSelections));
            this.reveal(true, 0 /* Primary */);
        };
        Cursor.prototype._onModelContentChanged = function (hadFlushEvent) {
            if (hadFlushEvent) {
                // a model.setValue() was called
                this._cursors.dispose();
                this._cursors = new cursorCollection_1.CursorCollection(this.context);
                this._emitStateChangedIfNecessary('model', cursorEvents_1.CursorChangeReason.ContentFlush, null);
            }
            else {
                var selectionsFromMarkers = this._cursors.readSelectionFromMarkers();
                this.setStates('modelChange', cursorEvents_1.CursorChangeReason.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, cursorEvents_1.CursorChangeReason.NotSet, cursorCommon_1.CursorState.fromModelSelections(selections));
        };
        // ------ auxiliary handling logic
        Cursor.prototype._executeEditOperation = function (opResult) {
            if (!opResult) {
                // Nothing to execute
                return;
            }
            if (this._configuration.editor.readOnly) {
                // Cannot execute when read only
                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);
            }
            if (opResult.shouldPushStackElementAfter) {
                this._model.pushStackElement();
            }
        };
        Cursor.prototype._interpretCommandResult = function (cursorState) {
            if (!cursorState || cursorState.length === 0) {
                return;
            }
            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 isInEditableRange = true;
            if (this._model.hasEditableRange()) {
                var editableRange = this._model.getEditableRange();
                if (!editableRange.containsPosition(newState.cursorState[0].modelState.position)) {
                    isInEditableRange = false;
                }
            }
            var selections = this._cursors.getSelections();
            var viewSelections = this._cursors.getViewSelections();
            var screenReaderMessage = null;
            // if (oldState) {
            // 	screenReaderMessage = ScreenReaderMessageGenerator.generateMessage(
            // 		source,
            // 		this._model,
            // 		oldState.modelVersionId,
            // 		oldState.cursorState[0].modelState.selection,
            // 		newState.modelVersionId,
            // 		newState.cursorState[0].modelState.selection
            // 	);
            // }
            // Let the view get the event first.
            this._emit([new viewEvents.ViewCursorStateChangedEvent(viewSelections, isInEditableRange, screenReaderMessage)]);
            // Only after the view has been notified, let the rest of the world know...
            this._onDidChange.fire(new CursorStateChangedEvent(selections, source || 'keyboard', reason));
            return true;
        };
        Cursor.prototype._revealRange = function (revealTarget, verticalType, revealHorizontal) {
            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);
        };
        Cursor.prototype.emitCursorRevealRange = function (viewRange, verticalType, revealHorizontal) {
            this._emit([new viewEvents.ViewRevealRangeRequestEvent(viewRange, verticalType, revealHorizontal)]);
        };
        // -----------------------------------------------------------------------------------------------------------
        // ----- 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;
                return;
            }
            var oldState = new CursorModelState(this._model, this);
            var cursorChangeReason = cursorEvents_1.CursorChangeReason.NotSet;
            // 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 = cursorEvents_1.CursorChangeReason.Paste;
                        this._paste(payload.text, payload.pasteOnNewLine);
                        break;
                    case H.Cut:
                        this._cut();
                        break;
                    case H.Undo:
                        cursorChangeReason = cursorEvents_1.CursorChangeReason.Undo;
                        this._interpretCommandResult(this._model.undo());
                        break;
                    case H.Redo:
                        cursorChangeReason = cursorEvents_1.CursorChangeReason.Redo;
                        this._interpretCommandResult(this._model.redo());
                        break;
                    case H.ExecuteCommand:
                        this._externalExecuteCommand(payload);
                        break;
                    case H.ExecuteCommands:
                        this._externalExecuteCommands(payload);
                        break;
                }
            }
            catch (err) {
                errors_1.onUnexpectedError(err);
            }
            this._isHandling = false;
            if (this._emitStateChangedIfNecessary(source, cursorChangeReason, oldState)) {
                this._revealRange(0 /* Primary */, 0 /* Simple */, true);
            }
        };
        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.context.config, this.context.model, this.getSelections(), chr));
                }
            }
            else {
                this._executeEditOperation(cursorTypeOperations_1.TypeOperations.typeWithoutInterceptors(this.context.config, this.context.model, this.getSelections(), text));
            }
        };
        Cursor.prototype._replacePreviousChar = function (text, replaceCharCnt) {
            this._executeEditOperation(cursorTypeOperations_1.TypeOperations.replacePreviousChar(this.context.config, this.context.model, this.getSelections(), text, replaceCharCnt));
        };
        Cursor.prototype._paste = function (text, pasteOnNewLine) {
            this._executeEditOperation(cursorTypeOperations_1.TypeOperations.paste(this.context.config, this.context.model, this.getSelections(), pasteOnNewLine, text));
        };
        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([command], {
                shouldPushStackElementBefore: false,
                shouldPushStackElementAfter: false
            }));
        };
        Cursor.prototype._externalExecuteCommands = function (commands) {
            this._executeEditOperation(new cursorCommon_1.EditOperationResult(commands, {
                shouldPushStackElementBefore: false,
                shouldPushStackElementAfter: false
            }));
        };
        return Cursor;
    }(viewEvents.ViewEventEmitter));
    exports.Cursor = Cursor;
    var CommandExecutor = (function () {
        function CommandExecutor() {
        }
        CommandExecutor.executeCommands = function (model, selectionsBefore, commands) {
            var ctx = {
                model: model,
                selectionsBefore: selectionsBefore,
                selectionStartMarkers: [],
                positionMarkers: []
            };
            var result = this._innerExecuteCommands(ctx, commands);
            for (var i = 0; i < ctx.selectionStartMarkers.length; i++) {
                ctx.model._removeMarker(ctx.selectionStartMarkers[i]);
                ctx.model._removeMarker(ctx.positionMarkers[i]);
            }
            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 editableRange = ctx.model.getEditableRange();
            var editableRangeStart = editableRange.getStartPosition();
            var editableRangeEnd = editableRange.getEndPosition();
            for (var i = 0, len = rawOperations.length; i < len; i++) {
                var operationRange = rawOperations[i].range;
                if (!editableRangeStart.isBeforeOrEqual(operationRange.getStartPosition()) || !operationRange.getEndPosition().isBeforeOrEqual(editableRangeEnd)) {
                    // These commands are outside of the editable range
                    return null;
                }
            }
            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; i < inverseEditOperations.length; i++) {
                    var op = inverseEditOperations[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 selectionStartMarker = ctx.model._getMarker(ctx.selectionStartMarkers[idx]);
                                var positionMarker = ctx.model._getMarker(ctx.positionMarkers[idx]);
                                return new selection_1.Selection(selectionStartMarker.lineNumber, selectionStartMarker.column, positionMarker.lineNumber, positionMarker.column);
                            }
                        });
                    }
                    else {
                        cursorSelections[i] = ctx.selectionsBefore[i];
                    }
                };
                for (var i = 0; i < ctx.selectionsBefore.length; i++) {
                    _loop_1(i);
                }
                return cursorSelections;
            });
            // 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; i < losingCursors.length; i++) {
                selectionsAfter.splice(losingCursors[i], 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++) {
                if (commands[i]) {
                    var r = this._getEditOperationsFromCommand(ctx, i, commands[i]);
                    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 selectionMarkerStickToPreviousCharacter;
                var positionMarkerStickToPreviousCharacter;
                if (selection.isEmpty()) {
                    // Try to lock it with surrounding text
                    if (typeof trackPreviousOnEmpty === 'boolean') {
                        selectionMarkerStickToPreviousCharacter = trackPreviousOnEmpty;
                        positionMarkerStickToPreviousCharacter = trackPreviousOnEmpty;
                    }
                    else {
                        var maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber);
                        if (selection.startColumn === maxLineColumn) {
                            selectionMarkerStickToPreviousCharacter = true;
                            positionMarkerStickToPreviousCharacter = true;
                        }
                        else {
                            selectionMarkerStickToPreviousCharacter = false;
                            positionMarkerStickToPreviousCharacter = false;
                        }
                    }
                }
                else {
                    if (selection.getDirection() === selection_1.SelectionDirection.LTR) {
                        selectionMarkerStickToPreviousCharacter = false;
                        positionMarkerStickToPreviousCharacter = true;
                    }
                    else {
                        selectionMarkerStickToPreviousCharacter = true;
                        positionMarkerStickToPreviousCharacter = false;
                    }
                }
                var l = ctx.selectionStartMarkers.length;
                ctx.selectionStartMarkers[l] = ctx.model._addMarker(0, selection.selectionStartLineNumber, selection.selectionStartColumn, selectionMarkerStickToPreviousCharacter);
                ctx.positionMarkers[l] = ctx.model._addMarker(0, selection.positionLineNumber, selection.positionColumn, positionMarkerStickToPreviousCharacter);
                return l.toString();
            };
            var editOperationBuilder = {
                addEditOperation: addEditOperation,
                addTrackedEditOperation: addTrackedEditOperation,
                trackSelection: trackSelection
            };
            try {
                command.getEditOperations(ctx.model, editOperationBuilder);
            }
            catch (e) {
                e.friendlyMessage = nls.localize(0, null);
                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;
    }());
});

define(__m[322/*vs/nls!vs/editor/common/model/textModelWithTokens*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/model/textModelWithTokens", data); });










define(__m[323/*vs/editor/common/model/textModelWithTokens*/], __M([1/*require*/,0/*exports*/,322/*vs/nls!vs/editor/common/model/textModelWithTokens*/,10/*vs/base/common/errors*/,426/*vs/base/common/stopwatch*/,93/*vs/editor/common/model/textModel*/,17/*vs/editor/common/modes*/,68/*vs/editor/common/modes/nullMode*/,91/*vs/editor/common/modes/supports*/,98/*vs/editor/common/modes/supports/richEditBrackets*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/,95/*vs/editor/common/model/wordHelper*/,55/*vs/editor/common/model/textModelEvents*/]), function (require, exports, nls, errors_1, stopwatch_1, textModel_1, modes_1, nullMode_1, supports_1, richEditBrackets_1, languageConfigurationRegistry_1, wordHelper_1, textModelEvents) {
    /*---------------------------------------------------------------------------------------------
     *  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 ModelTokensChangedEventBuilder = (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 {
                ranges: this._ranges
            };
        };
        return ModelTokensChangedEventBuilder;
    }());
    var TextModelWithTokens = (function (_super) {
        __extends(TextModelWithTokens, _super);
        function TextModelWithTokens(rawTextSource, creationOptions, languageIdentifier) {
            var _this = _super.call(this, rawTextSource, creationOptions) || this;
            _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({
                    ranges: [{
                            fromLineNumber: 1,
                            toLineNumber: _this.getLineCount()
                        }]
                });
            });
            _this._revalidateTokensTimeout = -1;
            _this._resetTokenizationState();
            return _this;
        }
        TextModelWithTokens.prototype.dispose = function () {
            this._tokenizationListener.dispose();
            this._clearTimers();
            this._lastState = null;
            _super.prototype.dispose.call(this);
        };
        TextModelWithTokens.prototype._shouldAutoTokenize = function () {
            return false;
        };
        TextModelWithTokens.prototype._resetValue = function (newValue) {
            _super.prototype._resetValue.call(this, newValue);
            // Cancel tokenization, clear all tokens and begin tokenizing
            this._resetTokenizationState();
        };
        TextModelWithTokens.prototype._resetTokenizationState = function () {
            this._clearTimers();
            for (var i = 0; i < this._lines.length; i++) {
                this._lines[i].resetTokenizationState();
            }
            this._tokenizationSupport = null;
            if (!this._isTooLargeForTokenization) {
                this._tokenizationSupport = modes_1.TokenizationRegistry.get(this._languageIdentifier.language);
            }
            if (this._tokenizationSupport) {
                var initialState = null;
                try {
                    initialState = this._tokenizationSupport.getInitialState();
                }
                catch (e) {
                    e.friendlyMessage = TextModelWithTokens.MODE_TOKENIZATION_FAILED_MSG;
                    errors_1.onUnexpectedError(e);
                    this._tokenizationSupport = null;
                }
                if (initialState) {
                    this._lines[0].setState(initialState);
                }
            }
            this._lastState = null;
            this._invalidLineStartIndex = 0;
            this._beginBackgroundTokenization();
        };
        TextModelWithTokens.prototype._clearTimers = function () {
            if (this._revalidateTokensTimeout !== -1) {
                clearTimeout(this._revalidateTokensTimeout);
                this._revalidateTokensTimeout = -1;
            }
        };
        TextModelWithTokens.prototype._withModelTokensChangedEventBuilder = function (callback) {
            var eventBuilder = new ModelTokensChangedEventBuilder();
            var result = callback(eventBuilder);
            if (!this._isDisposing) {
                var e = eventBuilder.build();
                if (e) {
                    this._eventEmitter.emit(textModelEvents.TextModelEventType.ModelTokensChanged, e);
                }
            }
            return result;
        };
        TextModelWithTokens.prototype.forceTokenization = function (lineNumber) {
            var _this = this;
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
            }
            this._withModelTokensChangedEventBuilder(function (eventBuilder) {
                _this._updateTokensUntilLine(eventBuilder, lineNumber);
            });
        };
        TextModelWithTokens.prototype.getLineTokens = function (lineNumber) {
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
            }
            return this._getLineTokens(lineNumber);
        };
        TextModelWithTokens.prototype._getLineTokens = function (lineNumber) {
            return this._lines[lineNumber - 1].getTokens(this._languageIdentifier.id);
        };
        TextModelWithTokens.prototype.getLanguageIdentifier = function () {
            return this._languageIdentifier;
        };
        TextModelWithTokens.prototype.getModeId = function () {
            return this._languageIdentifier.language;
        };
        TextModelWithTokens.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({
                ranges: [{
                        fromLineNumber: 1,
                        toLineNumber: this.getLineCount()
                    }]
            });
            this._emitModelModeChangedEvent(e);
        };
        TextModelWithTokens.prototype.getLanguageIdAtPosition = function (_lineNumber, _column) {
            if (!this._tokenizationSupport) {
                return this._languageIdentifier.id;
            }
            var _a = this.validatePosition({ lineNumber: _lineNumber, column: _column }), lineNumber = _a.lineNumber, column = _a.column;
            var lineTokens = this._getLineTokens(lineNumber);
            var token = lineTokens.findTokenAtOffset(column - 1);
            return token.languageId;
        };
        TextModelWithTokens.prototype._invalidateLine = function (lineIndex) {
            this._lines[lineIndex].setIsInvalid(true);
            if (lineIndex < this._invalidLineStartIndex) {
                if (this._invalidLineStartIndex < this._lines.length) {
                    this._lines[this._invalidLineStartIndex].setIsInvalid(true);
                }
                this._invalidLineStartIndex = lineIndex;
                this._beginBackgroundTokenization();
            }
        };
        TextModelWithTokens.prototype._beginBackgroundTokenization = function () {
            var _this = this;
            if (this._shouldAutoTokenize() && this._revalidateTokensTimeout === -1) {
                this._revalidateTokensTimeout = setTimeout(function () {
                    _this._revalidateTokensTimeout = -1;
                    _this._revalidateTokensNow();
                }, 0);
            }
        };
        TextModelWithTokens.prototype._warmUpTokens = function () {
            // Warm up first 100 lines (if it takes less than 50ms)
            var maxLineNumber = Math.min(100, this.getLineCount());
            var toLineNumber = maxLineNumber;
            for (var lineNumber = 1; lineNumber <= maxLineNumber; lineNumber++) {
                var text = this._lines[lineNumber - 1].text;
                if (text.length >= 200) {
                    // This line is over 200 chars long, so warm up without it
                    toLineNumber = lineNumber - 1;
                    break;
                }
            }
            this._revalidateTokensNow(toLineNumber);
            if (this._invalidLineStartIndex < this._lines.length) {
                this._beginBackgroundTokenization();
            }
        };
        TextModelWithTokens.prototype._revalidateTokensNow = function (toLineNumber) {
            var _this = this;
            if (toLineNumber === void 0) { toLineNumber = this._invalidLineStartIndex + 1000000; }
            this._withModelTokensChangedEventBuilder(function (eventBuilder) {
                toLineNumber = Math.min(_this._lines.length, toLineNumber);
                var MAX_ALLOWED_TIME = 20, fromLineNumber = _this._invalidLineStartIndex + 1, tokenizedChars = 0, currentCharsToTokenize = 0, currentEstimatedTimeToTokenize = 0, sw = stopwatch_1.StopWatch.create(false), elapsedTime;
                // Tokenize at most 1000 lines. Estimate the tokenization speed per character and stop when:
                // - MAX_ALLOWED_TIME is reached
                // - tokenizing the next line would go above MAX_ALLOWED_TIME
                for (var lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
                    elapsedTime = sw.elapsed();
                    if (elapsedTime > MAX_ALLOWED_TIME) {
                        // Stop if MAX_ALLOWED_TIME is reached
                        toLineNumber = lineNumber - 1;
                        break;
                    }
                    // Compute how many characters will be tokenized for this line
                    currentCharsToTokenize = _this._lines[lineNumber - 1].text.length;
                    if (tokenizedChars > 0) {
                        // If we have enough history, estimate how long tokenizing this line would take
                        currentEstimatedTimeToTokenize = (elapsedTime / tokenizedChars) * currentCharsToTokenize;
                        if (elapsedTime + currentEstimatedTimeToTokenize > MAX_ALLOWED_TIME) {
                            // Tokenizing this line will go above MAX_ALLOWED_TIME
                            toLineNumber = lineNumber - 1;
                            break;
                        }
                    }
                    _this._updateTokensUntilLine(eventBuilder, lineNumber);
                    tokenizedChars += currentCharsToTokenize;
                    // Skip the lines that got tokenized
                    lineNumber = Math.max(lineNumber, _this._invalidLineStartIndex + 1);
                }
                elapsedTime = sw.elapsed();
                if (_this._invalidLineStartIndex < _this._lines.length) {
                    _this._beginBackgroundTokenization();
                }
            });
        };
        TextModelWithTokens.prototype._updateTokensUntilLine = function (eventBuilder, lineNumber) {
            if (!this._tokenizationSupport) {
                this._invalidLineStartIndex = this._lines.length;
                return;
            }
            var linesLength = this._lines.length;
            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 r = null;
                var text = this._lines[lineIndex].text;
                try {
                    // Tokenize only the first X characters
                    var freshState = this._lines[lineIndex].getState().clone();
                    r = this._tokenizationSupport.tokenize2(this._lines[lineIndex].text, freshState, 0);
                }
                catch (e) {
                    e.friendlyMessage = TextModelWithTokens.MODE_TOKENIZATION_FAILED_MSG;
                    errors_1.onUnexpectedError(e);
                }
                if (!r) {
                    r = nullMode_1.nullTokenize2(this._languageIdentifier.id, text, this._lines[lineIndex].getState(), 0);
                }
                this._lines[lineIndex].setTokens(this._languageIdentifier.id, r.tokens);
                eventBuilder.registerChangedTokens(lineIndex + 1);
                this._lines[lineIndex].setIsInvalid(false);
                if (endStateIndex < linesLength) {
                    if (this._lines[endStateIndex].getState() !== null && r.endState.equals(this._lines[endStateIndex].getState())) {
                        // The end state of this line remains the same
                        var nextInvalidLineIndex = lineIndex + 1;
                        while (nextInvalidLineIndex < linesLength) {
                            if (this._lines[nextInvalidLineIndex].isInvalid()) {
                                break;
                            }
                            if (nextInvalidLineIndex + 1 < linesLength) {
                                if (this._lines[nextInvalidLineIndex + 1].getState() === 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._lines[endStateIndex].setState(r.endState);
                    }
                }
                else {
                    this._lastState = r.endState;
                }
            }
            this._invalidLineStartIndex = Math.max(this._invalidLineStartIndex, endLineIndex + 1);
        };
        TextModelWithTokens.prototype.emitModelTokensChangedEvent = function (e) {
            if (!this._isDisposing) {
                this._eventEmitter.emit(textModelEvents.TextModelEventType.ModelTokensChanged, e);
            }
        };
        TextModelWithTokens.prototype._emitModelModeChangedEvent = function (e) {
            if (!this._isDisposing) {
                this._eventEmitter.emit(textModelEvents.TextModelEventType.ModelLanguageChanged, e);
            }
        };
        // Having tokens allows implementing additional helper methods
        TextModelWithTokens.prototype.getWordAtPosition = function (_position) {
            this._assertNotDisposed();
            var position = this.validatePosition(_position);
            var lineContent = this.getLineContent(position.lineNumber);
            if (this._invalidLineStartIndex <= position.lineNumber) {
                // this line is not tokenized
                return wordHelper_1.getWordAtText(position.column, languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(this._languageIdentifier.id), lineContent, 0);
            }
            var lineTokens = this._getLineTokens(position.lineNumber);
            var offset = position.column - 1;
            var token = lineTokens.findTokenAtOffset(offset);
            var result = wordHelper_1.getWordAtText(position.column, languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(token.languageId), lineContent.substring(token.startOffset, token.endOffset), token.startOffset);
            if (!result && token.hasPrev && token.startOffset === offset) {
                // The position is right at the beginning of `modeIndex`, so try looking at `modeIndex` - 1 too
                var prevToken = token.prev();
                result = wordHelper_1.getWordAtText(position.column, languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(prevToken.languageId), lineContent.substring(prevToken.startOffset, prevToken.endOffset), prevToken.startOffset);
            }
            return result;
        };
        TextModelWithTokens.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
            };
        };
        TextModelWithTokens.prototype.findMatchingBracketUp = function (_bracket, _position) {
            var bracket = _bracket.toLowerCase();
            var position = this.validatePosition(_position);
            var lineTokens = this._getLineTokens(position.lineNumber);
            var token = lineTokens.findTokenAtOffset(position.column - 1);
            var bracketsSupport = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(token.languageId);
            if (!bracketsSupport) {
                return null;
            }
            var data = bracketsSupport.textIsBracket[bracket];
            if (!data) {
                return null;
            }
            return this._findMatchingBracketUp(data, position);
        };
        TextModelWithTokens.prototype.matchBracket = function (position) {
            return this._matchBracket(this.validatePosition(position));
        };
        TextModelWithTokens.prototype._matchBracket = function (position) {
            var lineNumber = position.lineNumber;
            var lineTokens = this._getLineTokens(lineNumber);
            var lineText = this._lines[lineNumber - 1].text;
            var currentToken = lineTokens.findTokenAtOffset(position.column - 1);
            if (!currentToken) {
                return null;
            }
            var currentModeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(currentToken.languageId);
            // check that the token is not to be ignored
            if (currentModeBrackets && !supports_1.ignoreBracketsInToken(currentToken.tokenType)) {
                // limit search to not go before `maxBracketLength`
                var searchStartOffset = Math.max(currentToken.startOffset, position.column - 1 - currentModeBrackets.maxBracketLength);
                // limit search to not go after `maxBracketLength`
                var searchEndOffset = Math.min(currentToken.endOffset, position.column - 1 + currentModeBrackets.maxBracketLength);
                // first, check if there is a bracket to the right of `position`
                var foundBracket = richEditBrackets_1.BracketsUtils.findNextBracketInToken(currentModeBrackets.forwardRegex, lineNumber, lineText, position.column - 1, searchEndOffset);
                if (foundBracket && foundBracket.startColumn === position.column) {
                    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) {
                        return r;
                    }
                }
                // it might still be the case that [currentTokenStart -> currentTokenEnd] contains multiple brackets
                while (true) {
                    var foundBracket_1 = richEditBrackets_1.BracketsUtils.findNextBracketInToken(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                    if (!foundBracket_1) {
                        // there are no brackets in this text
                        break;
                    }
                    // check that we didn't hit a bracket too far away from position
                    if (foundBracket_1.startColumn <= position.column && position.column <= foundBracket_1.endColumn) {
                        var foundBracketText = lineText.substring(foundBracket_1.startColumn - 1, foundBracket_1.endColumn - 1);
                        foundBracketText = foundBracketText.toLowerCase();
                        var r = this._matchFoundBracket(foundBracket_1, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText]);
                        // check that we can actually match this bracket
                        if (r) {
                            return r;
                        }
                    }
                    searchStartOffset = foundBracket_1.endColumn - 1;
                }
            }
            // If position is in between two tokens, try also looking in the previous token
            if (currentToken.hasPrev && currentToken.startOffset === position.column - 1) {
                var prevToken = currentToken.prev();
                var prevModeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(prevToken.languageId);
                // check that previous token is not to be ignored
                if (prevModeBrackets && !supports_1.ignoreBracketsInToken(prevToken.tokenType)) {
                    // limit search in case previous token is very large, there's no need to go beyond `maxBracketLength`
                    var searchStartOffset = Math.max(prevToken.startOffset, position.column - 1 - prevModeBrackets.maxBracketLength);
                    var searchEndOffset = currentToken.startOffset;
                    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;
        };
        TextModelWithTokens.prototype._matchFoundBracket = function (foundBracket, data, isOpen) {
            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;
        };
        TextModelWithTokens.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 lineText = this._lines[lineNumber - 1].text;
                var currentToken = void 0;
                var searchStopOffset = void 0;
                if (lineNumber === position.lineNumber) {
                    currentToken = lineTokens.findTokenAtOffset(position.column - 1);
                    searchStopOffset = position.column - 1;
                }
                else {
                    currentToken = lineTokens.lastToken();
                    if (currentToken) {
                        searchStopOffset = currentToken.endOffset;
                    }
                }
                while (currentToken) {
                    if (currentToken.languageId === languageId && !supports_1.ignoreBracketsInToken(currentToken.tokenType)) {
                        while (true) {
                            var r = richEditBrackets_1.BracketsUtils.findPrevBracketInToken(reversedBracketRegex, lineNumber, lineText, currentToken.startOffset, 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;
                        }
                    }
                    currentToken = currentToken.prev();
                    if (currentToken) {
                        searchStopOffset = currentToken.endOffset;
                    }
                }
            }
            return null;
        };
        TextModelWithTokens.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 lineText = this._lines[lineNumber - 1].text;
                var currentToken = void 0;
                var searchStartOffset = void 0;
                if (lineNumber === position.lineNumber) {
                    currentToken = lineTokens.findTokenAtOffset(position.column - 1);
                    searchStartOffset = position.column - 1;
                }
                else {
                    currentToken = lineTokens.firstToken();
                    if (currentToken) {
                        searchStartOffset = currentToken.startOffset;
                    }
                }
                while (currentToken) {
                    if (currentToken.languageId === languageId && !supports_1.ignoreBracketsInToken(currentToken.tokenType)) {
                        while (true) {
                            var r = richEditBrackets_1.BracketsUtils.findNextBracketInToken(bracketRegex, lineNumber, lineText, searchStartOffset, currentToken.endOffset);
                            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;
                        }
                    }
                    currentToken = currentToken.next();
                    if (currentToken) {
                        searchStartOffset = currentToken.startOffset;
                    }
                }
            }
            return null;
        };
        TextModelWithTokens.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 lineText = this._lines[lineNumber - 1].text;
                var currentToken = void 0;
                var searchStopOffset = void 0;
                if (lineNumber === position.lineNumber) {
                    currentToken = lineTokens.findTokenAtOffset(position.column - 1);
                    searchStopOffset = position.column - 1;
                }
                else {
                    currentToken = lineTokens.lastToken();
                    if (currentToken) {
                        searchStopOffset = currentToken.endOffset;
                    }
                }
                while (currentToken) {
                    if (languageId !== currentToken.languageId) {
                        languageId = currentToken.languageId;
                        modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
                    }
                    if (modeBrackets && !supports_1.ignoreBracketsInToken(currentToken.tokenType)) {
                        var r = richEditBrackets_1.BracketsUtils.findPrevBracketInToken(modeBrackets.reversedRegex, lineNumber, lineText, currentToken.startOffset, searchStopOffset);
                        if (r) {
                            return this._toFoundBracket(modeBrackets, r);
                        }
                    }
                    currentToken = currentToken.prev();
                    if (currentToken) {
                        searchStopOffset = currentToken.endOffset;
                    }
                }
            }
            return null;
        };
        TextModelWithTokens.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 lineText = this._lines[lineNumber - 1].text;
                var currentToken = void 0;
                var searchStartOffset = void 0;
                if (lineNumber === position.lineNumber) {
                    currentToken = lineTokens.findTokenAtOffset(position.column - 1);
                    searchStartOffset = position.column - 1;
                }
                else {
                    currentToken = lineTokens.firstToken();
                    if (currentToken) {
                        searchStartOffset = currentToken.startOffset;
                    }
                }
                while (currentToken) {
                    if (languageId !== currentToken.languageId) {
                        languageId = currentToken.languageId;
                        modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
                    }
                    if (modeBrackets && !supports_1.ignoreBracketsInToken(currentToken.tokenType)) {
                        var r = richEditBrackets_1.BracketsUtils.findNextBracketInToken(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, currentToken.endOffset);
                        if (r) {
                            return this._toFoundBracket(modeBrackets, r);
                        }
                    }
                    currentToken = currentToken.next();
                    if (currentToken) {
                        searchStartOffset = currentToken.startOffset;
                    }
                }
            }
            return null;
        };
        TextModelWithTokens.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]
            };
        };
        TextModelWithTokens.MODE_TOKENIZATION_FAILED_MSG = nls.localize(0, null);
        return TextModelWithTokens;
    }(textModel_1.TextModel));
    exports.TextModelWithTokens = TextModelWithTokens;
});











define(__m[324/*vs/editor/common/model/textModelWithMarkers*/], __M([1/*require*/,0/*exports*/,108/*vs/base/common/idGenerator*/,12/*vs/editor/common/core/position*/,118/*vs/editor/common/model/modelLine*/,323/*vs/editor/common/model/textModelWithTokens*/]), function (require, exports, idGenerator_1, position_1, modelLine_1, textModelWithTokens_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var _INSTANCE_COUNT = 0;
    var TextModelWithMarkers = (function (_super) {
        __extends(TextModelWithMarkers, _super);
        function TextModelWithMarkers(rawTextSource, creationOptions, languageIdentifier) {
            var _this = _super.call(this, rawTextSource, creationOptions, languageIdentifier) || this;
            _this._markerIdGenerator = new idGenerator_1.IdGenerator((++_INSTANCE_COUNT) + ';');
            _this._markerIdToMarker = Object.create(null);
            return _this;
        }
        TextModelWithMarkers.prototype.dispose = function () {
            this._markerIdToMarker = null;
            _super.prototype.dispose.call(this);
        };
        TextModelWithMarkers.prototype._resetValue = function (newValue) {
            _super.prototype._resetValue.call(this, newValue);
            // Destroy all my markers
            this._markerIdToMarker = Object.create(null);
        };
        TextModelWithMarkers.prototype._addMarker = function (internalDecorationId, lineNumber, column, stickToPreviousCharacter) {
            var pos = this.validatePosition(new position_1.Position(lineNumber, column));
            var marker = new modelLine_1.LineMarker(this._markerIdGenerator.nextId(), internalDecorationId, pos, stickToPreviousCharacter);
            this._markerIdToMarker[marker.id] = marker;
            this._lines[pos.lineNumber - 1].addMarker(marker);
            return marker.id;
        };
        TextModelWithMarkers.prototype._addMarkers = function (newMarkers) {
            if (newMarkers.length === 0) {
                return [];
            }
            var markers = [];
            for (var i = 0, len = newMarkers.length; i < len; i++) {
                var newMarker = newMarkers[i];
                var marker = new modelLine_1.LineMarker(this._markerIdGenerator.nextId(), newMarker.internalDecorationId, newMarker.position, newMarker.stickToPreviousCharacter);
                this._markerIdToMarker[marker.id] = marker;
                markers[i] = marker;
            }
            var sortedMarkers = markers.slice(0);
            sortedMarkers.sort(function (a, b) {
                return a.position.lineNumber - b.position.lineNumber;
            });
            var currentLineNumber = 0;
            var currentMarkers = [], currentMarkersLen = 0;
            for (var i = 0, len = sortedMarkers.length; i < len; i++) {
                var marker = sortedMarkers[i];
                if (marker.position.lineNumber !== currentLineNumber) {
                    if (currentLineNumber !== 0) {
                        this._lines[currentLineNumber - 1].addMarkers(currentMarkers);
                    }
                    currentLineNumber = marker.position.lineNumber;
                    currentMarkers.length = 0;
                    currentMarkersLen = 0;
                }
                currentMarkers[currentMarkersLen++] = marker;
            }
            this._lines[currentLineNumber - 1].addMarkers(currentMarkers);
            return markers;
        };
        TextModelWithMarkers.prototype._changeMarker = function (id, lineNumber, column) {
            var marker = this._markerIdToMarker[id];
            if (!marker) {
                return;
            }
            var newPos = this.validatePosition(new position_1.Position(lineNumber, column));
            if (newPos.lineNumber !== marker.position.lineNumber) {
                // Move marker between lines
                this._lines[marker.position.lineNumber - 1].removeMarker(marker);
                this._lines[newPos.lineNumber - 1].addMarker(marker);
            }
            marker.setPosition(newPos);
        };
        TextModelWithMarkers.prototype._changeMarkerStickiness = function (id, newStickToPreviousCharacter) {
            var marker = this._markerIdToMarker[id];
            if (!marker) {
                return;
            }
            marker.stickToPreviousCharacter = newStickToPreviousCharacter;
        };
        TextModelWithMarkers.prototype._getMarker = function (id) {
            var marker = this._markerIdToMarker[id];
            if (!marker) {
                return null;
            }
            return marker.position;
        };
        TextModelWithMarkers.prototype._getMarkersCount = function () {
            return Object.keys(this._markerIdToMarker).length;
        };
        TextModelWithMarkers.prototype._removeMarker = function (id) {
            var marker = this._markerIdToMarker[id];
            if (!marker) {
                return;
            }
            this._lines[marker.position.lineNumber - 1].removeMarker(marker);
            delete this._markerIdToMarker[id];
        };
        TextModelWithMarkers.prototype._removeMarkers = function (markers) {
            markers.sort(function (a, b) {
                return a.position.lineNumber - b.position.lineNumber;
            });
            var currentLineNumber = 0;
            var currentMarkers = null;
            for (var i = 0, len = markers.length; i < len; i++) {
                var marker = markers[i];
                delete this._markerIdToMarker[marker.id];
                if (marker.position.lineNumber !== currentLineNumber) {
                    if (currentLineNumber !== 0) {
                        this._lines[currentLineNumber - 1].removeMarkers(currentMarkers);
                    }
                    currentLineNumber = marker.position.lineNumber;
                    currentMarkers = Object.create(null);
                }
                currentMarkers[marker.id] = true;
            }
            this._lines[currentLineNumber - 1].removeMarkers(currentMarkers);
        };
        return TextModelWithMarkers;
    }(textModelWithTokens_1.TextModelWithTokens));
    exports.TextModelWithMarkers = TextModelWithMarkers;
});











define(__m[34/*vs/editor/common/model/textModelWithDecorations*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,133/*vs/base/common/htmlContent*/,9/*vs/base/common/strings*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,118/*vs/editor/common/model/modelLine*/,12/*vs/editor/common/core/position*/,324/*vs/editor/common/model/textModelWithMarkers*/,55/*vs/editor/common/model/textModelEvents*/]), function (require, exports, errors_1, htmlContent_1, strings, range_1, editorCommon, modelLine_1, position_1, textModelWithMarkers_1, textModelEvents) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassName = {
        EditorWarningDecoration: 'greensquiggly',
        EditorErrorDecoration: 'redsquiggly'
    };
    var DecorationsTracker = (function () {
        function DecorationsTracker() {
            this.addedDecorations = [];
            this.addedDecorationsLen = 0;
            this.changedDecorations = [];
            this.changedDecorationsLen = 0;
            this.removedDecorations = [];
            this.removedDecorationsLen = 0;
        }
        // --- Build decoration events
        DecorationsTracker.prototype.addNewDecoration = function (id) {
            this.addedDecorations[this.addedDecorationsLen++] = id;
        };
        DecorationsTracker.prototype.addRemovedDecoration = function (id) {
            this.removedDecorations[this.removedDecorationsLen++] = id;
        };
        DecorationsTracker.prototype.addMovedDecoration = function (id) {
            this.changedDecorations[this.changedDecorationsLen++] = id;
        };
        DecorationsTracker.prototype.addUpdatedDecoration = function (id) {
            this.changedDecorations[this.changedDecorationsLen++] = id;
        };
        return DecorationsTracker;
    }());
    var InternalDecoration = (function () {
        function InternalDecoration(id, internalId, ownerId, range, startMarker, endMarker, options) {
            this.id = id;
            this.internalId = internalId;
            this.ownerId = ownerId;
            this.range = range;
            this.startMarker = startMarker;
            this.endMarker = endMarker;
            this.setOptions(options);
        }
        InternalDecoration.prototype.setOptions = function (options) {
            this.options = options;
            this.isForValidation = (this.options.className === exports.ClassName.EditorErrorDecoration
                || this.options.className === exports.ClassName.EditorWarningDecoration);
        };
        InternalDecoration.prototype.setRange = function (multiLineDecorationsMap, range) {
            if (this.range.equalsRange(range)) {
                return;
            }
            var rangeWasMultiLine = (this.range.startLineNumber !== this.range.endLineNumber);
            this.range = range;
            var rangeIsMultiline = (this.range.startLineNumber !== this.range.endLineNumber);
            if (rangeWasMultiLine === rangeIsMultiline) {
                return;
            }
            if (rangeIsMultiline) {
                multiLineDecorationsMap[this.id] = this;
            }
            else {
                delete multiLineDecorationsMap[this.id];
            }
        };
        return InternalDecoration;
    }());
    exports.InternalDecoration = InternalDecoration;
    var _INSTANCE_COUNT = 0;
    /**
     * Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc.
     */
    function nextInstanceId() {
        var LETTERS_CNT = (90 /* Z */ - 65 /* A */ + 1);
        var result = _INSTANCE_COUNT++;
        result = result % (2 * LETTERS_CNT);
        if (result < LETTERS_CNT) {
            return String.fromCharCode(97 /* a */ + result);
        }
        return String.fromCharCode(65 /* A */ + result - LETTERS_CNT);
    }
    var TextModelWithDecorations = (function (_super) {
        __extends(TextModelWithDecorations, _super);
        function TextModelWithDecorations(rawTextSource, creationOptions, languageIdentifier) {
            var _this = _super.call(this, rawTextSource, creationOptions, languageIdentifier) || this;
            _this._instanceId = nextInstanceId();
            _this._lastDecorationId = 0;
            // Initialize decorations
            _this._currentDecorationsTracker = null;
            _this._currentDecorationsTrackerCnt = 0;
            _this._currentMarkersTracker = null;
            _this._currentMarkersTrackerCnt = 0;
            _this._decorations = Object.create(null);
            _this._internalDecorations = Object.create(null);
            _this._multiLineDecorationsMap = Object.create(null);
            return _this;
        }
        TextModelWithDecorations.prototype.dispose = function () {
            this._decorations = null;
            this._internalDecorations = null;
            this._multiLineDecorationsMap = null;
            _super.prototype.dispose.call(this);
        };
        TextModelWithDecorations.prototype._resetValue = function (newValue) {
            _super.prototype._resetValue.call(this, newValue);
            // Destroy all my decorations
            this._decorations = Object.create(null);
            this._internalDecorations = Object.create(null);
            this._multiLineDecorationsMap = Object.create(null);
        };
        TextModelWithDecorations._shouldStartMarkerSticksToPreviousCharacter = function (stickiness) {
            if (stickiness === editorCommon.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges || stickiness === editorCommon.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore) {
                return true;
            }
            return false;
        };
        TextModelWithDecorations._shouldEndMarkerSticksToPreviousCharacter = function (stickiness) {
            if (stickiness === editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges || stickiness === editorCommon.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore) {
                return true;
            }
            return false;
        };
        TextModelWithDecorations.prototype._getTrackedRangesCount = function () {
            return Object.keys(this._decorations).length;
        };
        // --- END TrackedRanges
        TextModelWithDecorations.prototype.changeDecorations = function (callback, ownerId) {
            if (ownerId === void 0) { ownerId = 0; }
            this._assertNotDisposed();
            try {
                this._eventEmitter.beginDeferredEmit();
                var decorationsTracker = this._acquireDecorationsTracker();
                return this._changeDecorations(decorationsTracker, ownerId, callback);
            }
            finally {
                this._releaseDecorationsTracker();
                this._eventEmitter.endDeferredEmit();
            }
        };
        TextModelWithDecorations.prototype._changeDecorations = function (decorationsTracker, ownerId, callback) {
            var _this = this;
            var changeAccessor = {
                addDecoration: function (range, options) {
                    return _this._addDecorationImpl(decorationsTracker, ownerId, _this.validateRange(range), _normalizeOptions(options));
                },
                changeDecoration: function (id, newRange) {
                    _this._changeDecorationImpl(decorationsTracker, id, _this.validateRange(newRange));
                },
                changeDecorationOptions: function (id, options) {
                    _this._changeDecorationOptionsImpl(decorationsTracker, id, _normalizeOptions(options));
                },
                removeDecoration: function (id) {
                    _this._removeDecorationImpl(decorationsTracker, id);
                },
                deltaDecorations: function (oldDecorations, newDecorations) {
                    return _this._deltaDecorationsImpl(decorationsTracker, ownerId, oldDecorations, _this._normalizeDeltaDecorations(newDecorations));
                }
            };
            var result = null;
            try {
                result = callback(changeAccessor);
            }
            catch (e) {
                errors_1.onUnexpectedError(e);
            }
            // Invalidate change accessor
            changeAccessor.addDecoration = null;
            changeAccessor.changeDecoration = null;
            changeAccessor.removeDecoration = null;
            changeAccessor.deltaDecorations = null;
            return result;
        };
        TextModelWithDecorations.prototype.deltaDecorations = function (oldDecorations, newDecorations, ownerId) {
            if (ownerId === void 0) { ownerId = 0; }
            this._assertNotDisposed();
            if (!oldDecorations) {
                oldDecorations = [];
            }
            return this.changeDecorations(function (changeAccessor) {
                return changeAccessor.deltaDecorations(oldDecorations, newDecorations);
            }, ownerId);
        };
        TextModelWithDecorations.prototype.removeAllDecorationsWithOwnerId = function (ownerId) {
            var toRemove = [];
            for (var decorationId in this._decorations) {
                // No `hasOwnProperty` call due to using Object.create(null)
                var decoration = this._decorations[decorationId];
                if (decoration.ownerId === ownerId) {
                    toRemove.push(decoration.id);
                }
            }
            this._removeDecorationsImpl(null, toRemove);
        };
        TextModelWithDecorations.prototype.getDecorationOptions = function (decorationId) {
            var decoration = this._decorations[decorationId];
            if (!decoration) {
                return null;
            }
            return decoration.options;
        };
        TextModelWithDecorations.prototype.getDecorationRange = function (decorationId) {
            var decoration = this._decorations[decorationId];
            if (!decoration) {
                return null;
            }
            return decoration.range;
        };
        TextModelWithDecorations.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);
        };
        /**
         * Fetch only multi-line decorations that intersect with the given line number range
         */
        TextModelWithDecorations.prototype._getMultiLineDecorations = function (filterRange, filterOwnerId, filterOutValidation) {
            var filterStartLineNumber = filterRange.startLineNumber;
            var filterStartColumn = filterRange.startColumn;
            var filterEndLineNumber = filterRange.endLineNumber;
            var filterEndColumn = filterRange.endColumn;
            var result = [];
            for (var decorationId in this._multiLineDecorationsMap) {
                // No `hasOwnProperty` call due to using Object.create(null)
                var decoration = this._multiLineDecorationsMap[decorationId];
                if (filterOwnerId && decoration.ownerId && decoration.ownerId !== filterOwnerId) {
                    continue;
                }
                if (filterOutValidation && decoration.isForValidation) {
                    continue;
                }
                var range = decoration.range;
                if (range.startLineNumber > filterEndLineNumber) {
                    continue;
                }
                if (range.startLineNumber === filterEndLineNumber && range.startColumn > filterEndColumn) {
                    continue;
                }
                if (range.endLineNumber < filterStartLineNumber) {
                    continue;
                }
                if (range.endLineNumber === filterStartLineNumber && range.endColumn < filterStartColumn) {
                    continue;
                }
                result.push(decoration);
            }
            return result;
        };
        TextModelWithDecorations.prototype._getDecorationsInRange = function (filterRange, filterOwnerId, filterOutValidation) {
            var filterStartLineNumber = filterRange.startLineNumber;
            var filterStartColumn = filterRange.startColumn;
            var filterEndLineNumber = filterRange.endLineNumber;
            var filterEndColumn = filterRange.endColumn;
            var result = this._getMultiLineDecorations(filterRange, filterOwnerId, filterOutValidation);
            var resultMap = {};
            for (var i = 0, len = result.length; i < len; i++) {
                resultMap[result[i].id] = true;
            }
            for (var lineNumber = filterStartLineNumber; lineNumber <= filterEndLineNumber; lineNumber++) {
                var lineMarkers = this._lines[lineNumber - 1].getMarkers();
                if (lineMarkers === null) {
                    continue;
                }
                for (var i = 0, len = lineMarkers.length; i < len; i++) {
                    var lineMarker = lineMarkers[i];
                    var internalDecorationId = lineMarker.internalDecorationId;
                    if (internalDecorationId === 0) {
                        // marker does not belong to any decoration
                        continue;
                    }
                    var decoration = this._internalDecorations[internalDecorationId];
                    if (resultMap.hasOwnProperty(decoration.id)) {
                        // decoration already in result
                        continue;
                    }
                    if (filterOwnerId && decoration.ownerId && decoration.ownerId !== filterOwnerId) {
                        continue;
                    }
                    if (filterOutValidation && decoration.isForValidation) {
                        continue;
                    }
                    var range = decoration.range;
                    if (range.startLineNumber > filterEndLineNumber) {
                        continue;
                    }
                    if (range.startLineNumber === filterEndLineNumber && range.startColumn > filterEndColumn) {
                        continue;
                    }
                    if (range.endLineNumber < filterStartLineNumber) {
                        continue;
                    }
                    if (range.endLineNumber === filterStartLineNumber && range.endColumn < filterStartColumn) {
                        continue;
                    }
                    result.push(decoration);
                    resultMap[decoration.id] = true;
                }
            }
            return result;
        };
        TextModelWithDecorations.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);
        };
        TextModelWithDecorations.prototype.getDecorationsInRange = function (range, ownerId, filterOutValidation) {
            var validatedRange = this.validateRange(range);
            return this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation);
        };
        TextModelWithDecorations.prototype.getAllDecorations = function (ownerId, filterOutValidation) {
            if (ownerId === void 0) { ownerId = 0; }
            if (filterOutValidation === void 0) { filterOutValidation = false; }
            var result = [];
            for (var decorationId in this._decorations) {
                // No `hasOwnProperty` call due to using Object.create(null)
                var decoration = this._decorations[decorationId];
                if (ownerId && decoration.ownerId && decoration.ownerId !== ownerId) {
                    continue;
                }
                if (filterOutValidation && decoration.isForValidation) {
                    continue;
                }
                result.push(decoration);
            }
            return result;
        };
        TextModelWithDecorations.prototype._acquireMarkersTracker = function () {
            if (this._currentMarkersTrackerCnt === 0) {
                this._currentMarkersTracker = new modelLine_1.MarkersTracker();
            }
            this._currentMarkersTrackerCnt++;
            return this._currentMarkersTracker;
        };
        TextModelWithDecorations.prototype._releaseMarkersTracker = function () {
            this._currentMarkersTrackerCnt--;
            if (this._currentMarkersTrackerCnt === 0) {
                var markersTracker = this._currentMarkersTracker;
                this._currentMarkersTracker = null;
                this._handleTrackedMarkers(markersTracker);
            }
        };
        /**
         * Handle changed markers (i.e. update decorations ranges and return the changed decorations, unique and sorted by id)
         */
        TextModelWithDecorations.prototype._handleTrackedMarkers = function (markersTracker) {
            var changedInternalDecorationIds = markersTracker.getDecorationIds();
            if (changedInternalDecorationIds.length === 0) {
                return;
            }
            changedInternalDecorationIds.sort();
            var uniqueChangedDecorations = [], uniqueChangedDecorationsLen = 0;
            var previousInternalDecorationId = 0;
            for (var i = 0, len = changedInternalDecorationIds.length; i < len; i++) {
                var internalDecorationId = changedInternalDecorationIds[i];
                if (internalDecorationId === previousInternalDecorationId) {
                    continue;
                }
                previousInternalDecorationId = internalDecorationId;
                var decoration = this._internalDecorations[internalDecorationId];
                if (!decoration) {
                    // perhaps the decoration was removed in the meantime
                    continue;
                }
                var startMarker = decoration.startMarker.position;
                var endMarker = decoration.endMarker.position;
                var range = TextModelWithDecorations._createRangeFromMarkers(startMarker, endMarker);
                decoration.setRange(this._multiLineDecorationsMap, range);
                uniqueChangedDecorations[uniqueChangedDecorationsLen++] = decoration.id;
            }
            if (uniqueChangedDecorations.length > 0) {
                var e = {
                    addedDecorations: [],
                    changedDecorations: uniqueChangedDecorations,
                    removedDecorations: []
                };
                this.emitModelDecorationsChangedEvent(e);
            }
        };
        TextModelWithDecorations._createRangeFromMarkers = function (startPosition, endPosition) {
            if (endPosition.isBefore(startPosition)) {
                // This tracked range has turned in on itself (end marker before start marker)
                // This can happen in extreme editing conditions where lots of text is removed and lots is added
                // Treat it as a collapsed range
                return new range_1.Range(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column);
            }
            return new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
        };
        TextModelWithDecorations.prototype._acquireDecorationsTracker = function () {
            if (this._currentDecorationsTrackerCnt === 0) {
                this._currentDecorationsTracker = new DecorationsTracker();
            }
            this._currentDecorationsTrackerCnt++;
            return this._currentDecorationsTracker;
        };
        TextModelWithDecorations.prototype._releaseDecorationsTracker = function () {
            this._currentDecorationsTrackerCnt--;
            if (this._currentDecorationsTrackerCnt === 0) {
                var decorationsTracker = this._currentDecorationsTracker;
                this._currentDecorationsTracker = null;
                this._handleTrackedDecorations(decorationsTracker);
            }
        };
        TextModelWithDecorations.prototype._handleTrackedDecorations = function (decorationsTracker) {
            if (decorationsTracker.addedDecorationsLen === 0
                && decorationsTracker.changedDecorationsLen === 0
                && decorationsTracker.removedDecorationsLen === 0) {
                return;
            }
            var e = {
                addedDecorations: decorationsTracker.addedDecorations,
                changedDecorations: decorationsTracker.changedDecorations,
                removedDecorations: decorationsTracker.removedDecorations
            };
            this.emitModelDecorationsChangedEvent(e);
        };
        TextModelWithDecorations.prototype.emitModelDecorationsChangedEvent = function (e) {
            if (!this._isDisposing) {
                this._eventEmitter.emit(textModelEvents.TextModelEventType.ModelDecorationsChanged, e);
            }
        };
        TextModelWithDecorations.prototype._normalizeDeltaDecorations = function (deltaDecorations) {
            var result = [];
            for (var i = 0, len = deltaDecorations.length; i < len; i++) {
                var deltaDecoration = deltaDecorations[i];
                result.push(new ModelDeltaDecoration(i, this.validateRange(deltaDecoration.range), _normalizeOptions(deltaDecoration.options)));
            }
            return result;
        };
        TextModelWithDecorations.prototype._externalDecorationId = function (internalId) {
            return this._instanceId + ";" + internalId;
        };
        TextModelWithDecorations.prototype._addDecorationImpl = function (decorationsTracker, ownerId, _range, options) {
            var range = this.validateRange(_range);
            var internalDecorationId = (++this._lastDecorationId);
            var decorationId = this._externalDecorationId(internalDecorationId);
            var markers = this._addMarkers([
                {
                    internalDecorationId: internalDecorationId,
                    position: new position_1.Position(range.startLineNumber, range.startColumn),
                    stickToPreviousCharacter: TextModelWithDecorations._shouldStartMarkerSticksToPreviousCharacter(options.stickiness)
                },
                {
                    internalDecorationId: internalDecorationId,
                    position: new position_1.Position(range.endLineNumber, range.endColumn),
                    stickToPreviousCharacter: TextModelWithDecorations._shouldEndMarkerSticksToPreviousCharacter(options.stickiness)
                }
            ]);
            var decoration = new InternalDecoration(decorationId, internalDecorationId, ownerId, range, markers[0], markers[1], options);
            this._decorations[decorationId] = decoration;
            this._internalDecorations[internalDecorationId] = decoration;
            if (range.startLineNumber !== range.endLineNumber) {
                this._multiLineDecorationsMap[decorationId] = decoration;
            }
            decorationsTracker.addNewDecoration(decorationId);
            return decorationId;
        };
        TextModelWithDecorations.prototype._addDecorationsImpl = function (decorationsTracker, ownerId, newDecorations) {
            var internalDecorationIds = [];
            var decorationIds = [];
            var newMarkers = [];
            for (var i = 0, len = newDecorations.length; i < len; i++) {
                var newDecoration = newDecorations[i];
                var range = newDecoration.range;
                var stickiness = newDecoration.options.stickiness;
                var internalDecorationId = (++this._lastDecorationId);
                var decorationId = this._externalDecorationId(internalDecorationId);
                internalDecorationIds[i] = internalDecorationId;
                decorationIds[i] = decorationId;
                newMarkers[2 * i] = {
                    internalDecorationId: internalDecorationId,
                    position: new position_1.Position(range.startLineNumber, range.startColumn),
                    stickToPreviousCharacter: TextModelWithDecorations._shouldStartMarkerSticksToPreviousCharacter(stickiness)
                };
                newMarkers[2 * i + 1] = {
                    internalDecorationId: internalDecorationId,
                    position: new position_1.Position(range.endLineNumber, range.endColumn),
                    stickToPreviousCharacter: TextModelWithDecorations._shouldEndMarkerSticksToPreviousCharacter(stickiness)
                };
            }
            var markerIds = this._addMarkers(newMarkers);
            for (var i = 0, len = newDecorations.length; i < len; i++) {
                var newDecoration = newDecorations[i];
                var range = newDecoration.range;
                var internalDecorationId = internalDecorationIds[i];
                var decorationId = decorationIds[i];
                var startMarker = markerIds[2 * i];
                var endMarker = markerIds[2 * i + 1];
                var decoration = new InternalDecoration(decorationId, internalDecorationId, ownerId, range, startMarker, endMarker, newDecoration.options);
                this._decorations[decorationId] = decoration;
                this._internalDecorations[internalDecorationId] = decoration;
                if (range.startLineNumber !== range.endLineNumber) {
                    this._multiLineDecorationsMap[decorationId] = decoration;
                }
                decorationsTracker.addNewDecoration(decorationId);
            }
            return decorationIds;
        };
        TextModelWithDecorations.prototype._changeDecorationImpl = function (decorationsTracker, decorationId, newRange) {
            var decoration = this._decorations[decorationId];
            if (!decoration) {
                return;
            }
            var startMarker = decoration.startMarker;
            if (newRange.startLineNumber !== startMarker.position.lineNumber) {
                // move marker between lines
                this._lines[startMarker.position.lineNumber - 1].removeMarker(startMarker);
                this._lines[newRange.startLineNumber - 1].addMarker(startMarker);
            }
            startMarker.setPosition(new position_1.Position(newRange.startLineNumber, newRange.startColumn));
            var endMarker = decoration.endMarker;
            if (newRange.endLineNumber !== endMarker.position.lineNumber) {
                // move marker between lines
                this._lines[endMarker.position.lineNumber - 1].removeMarker(endMarker);
                this._lines[newRange.endLineNumber - 1].addMarker(endMarker);
            }
            endMarker.setPosition(new position_1.Position(newRange.endLineNumber, newRange.endColumn));
            decoration.setRange(this._multiLineDecorationsMap, newRange);
            decorationsTracker.addMovedDecoration(decorationId);
        };
        TextModelWithDecorations.prototype._changeDecorationOptionsImpl = function (decorationsTracker, decorationId, options) {
            var decoration = this._decorations[decorationId];
            if (!decoration) {
                return;
            }
            if (decoration.options.stickiness !== options.stickiness) {
                decoration.startMarker.stickToPreviousCharacter = TextModelWithDecorations._shouldStartMarkerSticksToPreviousCharacter(options.stickiness);
                decoration.endMarker.stickToPreviousCharacter = TextModelWithDecorations._shouldEndMarkerSticksToPreviousCharacter(options.stickiness);
            }
            decoration.setOptions(options);
            decorationsTracker.addUpdatedDecoration(decorationId);
        };
        TextModelWithDecorations.prototype._removeDecorationImpl = function (decorationsTracker, decorationId) {
            var decoration = this._decorations[decorationId];
            if (!decoration) {
                return;
            }
            this._removeMarkers([decoration.startMarker, decoration.endMarker]);
            delete this._multiLineDecorationsMap[decorationId];
            delete this._decorations[decorationId];
            delete this._internalDecorations[decoration.internalId];
            if (decorationsTracker) {
                decorationsTracker.addRemovedDecoration(decorationId);
            }
        };
        TextModelWithDecorations.prototype._removeDecorationsImpl = function (decorationsTracker, decorationIds) {
            var removeMarkers = [], removeMarkersLen = 0;
            for (var i = 0, len = decorationIds.length; i < len; i++) {
                var decorationId = decorationIds[i];
                var decoration = this._decorations[decorationId];
                if (!decoration) {
                    continue;
                }
                if (decorationsTracker) {
                    decorationsTracker.addRemovedDecoration(decorationId);
                }
                removeMarkers[removeMarkersLen++] = decoration.startMarker;
                removeMarkers[removeMarkersLen++] = decoration.endMarker;
                delete this._multiLineDecorationsMap[decorationId];
                delete this._decorations[decorationId];
                delete this._internalDecorations[decoration.internalId];
            }
            if (removeMarkers.length > 0) {
                this._removeMarkers(removeMarkers);
            }
        };
        TextModelWithDecorations.prototype._resolveOldDecorations = function (oldDecorations) {
            var result = [];
            for (var i = 0, len = oldDecorations.length; i < len; i++) {
                var id = oldDecorations[i];
                var decoration = this._decorations[id];
                if (!decoration) {
                    continue;
                }
                result.push(decoration);
            }
            return result;
        };
        TextModelWithDecorations.prototype._deltaDecorationsImpl = function (decorationsTracker, ownerId, oldDecorationsIds, newDecorations) {
            if (oldDecorationsIds.length === 0) {
                // Nothing to remove
                return this._addDecorationsImpl(decorationsTracker, ownerId, newDecorations);
            }
            if (newDecorations.length === 0) {
                // Nothing to add
                this._removeDecorationsImpl(decorationsTracker, oldDecorationsIds);
                return [];
            }
            var oldDecorations = this._resolveOldDecorations(oldDecorationsIds);
            oldDecorations.sort(function (a, b) { return range_1.Range.compareRangesUsingStarts(a.range, b.range); });
            newDecorations.sort(function (a, b) { return range_1.Range.compareRangesUsingStarts(a.range, b.range); });
            var result = [], oldDecorationsIndex = 0, oldDecorationsLength = oldDecorations.length, newDecorationsIndex = 0, newDecorationsLength = newDecorations.length, decorationsToAdd = [], decorationsToRemove = [];
            while (oldDecorationsIndex < oldDecorationsLength && newDecorationsIndex < newDecorationsLength) {
                var oldDecoration = oldDecorations[oldDecorationsIndex];
                var newDecoration = newDecorations[newDecorationsIndex];
                var comparison = range_1.Range.compareRangesUsingStarts(oldDecoration.range, newDecoration.range);
                if (comparison < 0) {
                    // `oldDecoration` is before `newDecoration` => remove `oldDecoration`
                    decorationsToRemove.push(oldDecoration.id);
                    oldDecorationsIndex++;
                    continue;
                }
                if (comparison > 0) {
                    // `newDecoration` is before `oldDecoration` => add `newDecoration`
                    decorationsToAdd.push(newDecoration);
                    newDecorationsIndex++;
                    continue;
                }
                // The ranges of `oldDecoration` and `newDecoration` are equal
                if (!oldDecoration.options.equals(newDecoration.options)) {
                    // The options do not match => remove `oldDecoration`
                    decorationsToRemove.push(oldDecoration.id);
                    oldDecorationsIndex++;
                    continue;
                }
                // Bingo! We can reuse `oldDecoration` for `newDecoration`
                result[newDecoration.index] = oldDecoration.id;
                oldDecorationsIndex++;
                newDecorationsIndex++;
            }
            while (oldDecorationsIndex < oldDecorationsLength) {
                // No more new decorations => remove decoration at `oldDecorationsIndex`
                decorationsToRemove.push(oldDecorations[oldDecorationsIndex].id);
                oldDecorationsIndex++;
            }
            while (newDecorationsIndex < newDecorationsLength) {
                // No more old decorations => add decoration at `newDecorationsIndex`
                decorationsToAdd.push(newDecorations[newDecorationsIndex]);
                newDecorationsIndex++;
            }
            // Remove `decorationsToRemove`
            if (decorationsToRemove.length > 0) {
                this._removeDecorationsImpl(decorationsTracker, decorationsToRemove);
            }
            // Add `decorationsToAdd`
            if (decorationsToAdd.length > 0) {
                var newIds = this._addDecorationsImpl(decorationsTracker, ownerId, decorationsToAdd);
                for (var i = 0, len = decorationsToAdd.length; i < len; i++) {
                    result[decorationsToAdd[i].index] = newIds[i];
                }
            }
            return result;
        };
        return TextModelWithDecorations;
    }(textModelWithMarkers_1.TextModelWithMarkers));
    exports.TextModelWithDecorations = TextModelWithDecorations;
    function cleanClassName(className) {
        return className.replace(/[^a-z0-9\-]/gi, ' ');
    }
    var ModelDecorationOverviewRulerOptions = (function () {
        function ModelDecorationOverviewRulerOptions(options) {
            this.color = strings.empty;
            this.darkColor = strings.empty;
            this.hcColor = strings.empty;
            this.position = editorCommon.OverviewRulerLane.Center;
            if (options && options.color) {
                this.color = options.color;
            }
            if (options && options.darkColor) {
                this.darkColor = options.darkColor;
                this.hcColor = options.darkColor;
            }
            if (options && options.hcColor) {
                this.hcColor = options.hcColor;
            }
            if (options && options.hasOwnProperty('position')) {
                this.position = options.position;
            }
        }
        ModelDecorationOverviewRulerOptions.prototype.equals = function (other) {
            return (this.color === other.color
                && this.darkColor === other.darkColor
                && this.hcColor === other.hcColor
                && this.position === other.position);
        };
        return ModelDecorationOverviewRulerOptions;
    }());
    exports.ModelDecorationOverviewRulerOptions = ModelDecorationOverviewRulerOptions;
    var lastStaticId = 0;
    var ModelDecorationOptions = (function () {
        function ModelDecorationOptions(staticId, options) {
            this.staticId = staticId;
            this.stickiness = options.stickiness || editorCommon.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges;
            this.className = options.className ? cleanClassName(options.className) : strings.empty;
            this.hoverMessage = options.hoverMessage || [];
            this.glyphMarginHoverMessage = options.glyphMarginHoverMessage || strings.empty;
            this.isWholeLine = options.isWholeLine || false;
            this.showIfCollapsed = options.showIfCollapsed || false;
            this.overviewRuler = new ModelDecorationOverviewRulerOptions(options.overviewRuler);
            this.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : strings.empty;
            this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : strings.empty;
            this.marginClassName = options.marginClassName ? cleanClassName(options.marginClassName) : strings.empty;
            this.inlineClassName = options.inlineClassName ? cleanClassName(options.inlineClassName) : strings.empty;
            this.beforeContentClassName = options.beforeContentClassName ? cleanClassName(options.beforeContentClassName) : strings.empty;
            this.afterContentClassName = options.afterContentClassName ? cleanClassName(options.afterContentClassName) : strings.empty;
            if (options.__extraOptions) {
                this.extraOptions = options.__extraOptions;
            }
        }
        ModelDecorationOptions.register = function (options) {
            return new ModelDecorationOptions(++lastStaticId, options);
        };
        ModelDecorationOptions.createDynamic = function (options) {
            return new ModelDecorationOptions(0, options);
        };
        ModelDecorationOptions.prototype.equals = function (other) {
            if (this.staticId > 0 || other.staticId > 0) {
                return this.staticId === other.staticId;
            }
            return (this.stickiness === other.stickiness
                && this.className === other.className
                && this.isWholeLine === other.isWholeLine
                && this.showIfCollapsed === other.showIfCollapsed
                && this.glyphMarginClassName === other.glyphMarginClassName
                && this.linesDecorationsClassName === other.linesDecorationsClassName
                && this.marginClassName === other.marginClassName
                && this.inlineClassName === other.inlineClassName
                && this.beforeContentClassName === other.beforeContentClassName
                && this.afterContentClassName === other.afterContentClassName
                && htmlContent_1.markedStringsEquals(this.hoverMessage, other.hoverMessage)
                && htmlContent_1.markedStringsEquals(this.glyphMarginHoverMessage, other.glyphMarginHoverMessage)
                && this.overviewRuler.equals(other.overviewRuler)
                && this.extraOptions === other.extraOptions);
        };
        return ModelDecorationOptions;
    }());
    exports.ModelDecorationOptions = ModelDecorationOptions;
    ModelDecorationOptions.EMPTY = ModelDecorationOptions.register({});
    var ModelDeltaDecoration = (function () {
        function ModelDeltaDecoration(index, range, options) {
            this.index = index;
            this.range = range;
            this.options = options;
        }
        return ModelDeltaDecoration;
    }());
    function _normalizeOptions(options) {
        if (options instanceof ModelDecorationOptions) {
            return options;
        }
        return ModelDecorationOptions.createDynamic(options);
    }
});











define(__m[326/*vs/editor/common/model/editableTextModel*/], __M([1/*require*/,0/*exports*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,475/*vs/editor/common/model/editStack*/,34/*vs/editor/common/model/textModelWithDecorations*/,9/*vs/base/common/strings*/,33/*vs/base/common/arrays*/,12/*vs/editor/common/core/position*/,101/*vs/editor/common/model/textSource*/,93/*vs/editor/common/model/textModel*/,55/*vs/editor/common/model/textModelEvents*/]), function (require, exports, range_1, editorCommon, editStack_1, textModelWithDecorations_1, strings, arrays, position_1, textSource_1, textModel_1, textModelEvents) {
    /*---------------------------------------------------------------------------------------------
     *  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 EditableTextModel = (function (_super) {
        __extends(EditableTextModel, _super);
        function EditableTextModel(rawTextSource, creationOptions, languageIdentifier) {
            var _this = _super.call(this, rawTextSource, creationOptions, languageIdentifier) || this;
            _this._commandManager = new editStack_1.EditStack(_this);
            _this._isUndoing = false;
            _this._isRedoing = false;
            _this._hasEditableRange = false;
            _this._editableRangeId = null;
            _this._trimAutoWhitespaceLines = null;
            return _this;
        }
        EditableTextModel.createFromString = function (text, options, languageIdentifier) {
            if (options === void 0) { options = textModel_1.TextModel.DEFAULT_CREATION_OPTIONS; }
            if (languageIdentifier === void 0) { languageIdentifier = null; }
            return new EditableTextModel(textSource_1.RawTextSource.fromString(text), options, languageIdentifier);
        };
        EditableTextModel.prototype.onDidChangeRawContent = function (listener) {
            return this._eventEmitter.addListener(textModelEvents.TextModelEventType.ModelRawContentChanged2, listener);
        };
        EditableTextModel.prototype.onDidChangeContent = function (listener) {
            return this._eventEmitter.addListener(textModelEvents.TextModelEventType.ModelContentChanged, listener);
        };
        EditableTextModel.prototype.dispose = function () {
            this._commandManager = null;
            _super.prototype.dispose.call(this);
        };
        EditableTextModel.prototype._resetValue = function (newValue) {
            _super.prototype._resetValue.call(this, newValue);
            // Destroy my edit history and settings
            this._commandManager = new editStack_1.EditStack(this);
            this._hasEditableRange = false;
            this._editableRangeId = null;
            this._trimAutoWhitespaceLines = null;
        };
        EditableTextModel.prototype.pushStackElement = function () {
            this._commandManager.pushStackElement();
        };
        EditableTextModel.prototype.pushEditOperations = function (beforeCursorState, editOperations, cursorStateComputer) {
            try {
                this._eventEmitter.beginDeferredEmit();
                return this._pushEditOperations(beforeCursorState, editOperations, cursorStateComputer);
            }
            finally {
                this._eventEmitter.endDeferredEmit();
            }
        };
        EditableTextModel.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;
                            }
                            // Looks like we can't trim this line as it would interfere with an incoming edit
                            allowTrimLine = false;
                            break;
                        }
                        if (allowTrimLine) {
                            editOperations.push({
                                identifier: null,
                                range: new range_1.Range(trimLineNumber, 1, trimLineNumber, maxLineColumn),
                                text: null,
                                forceMoveMarkers: false,
                                isAutoWhitespaceEdit: false
                            });
                        }
                    }
                }
                this._trimAutoWhitespaceLines = null;
            }
            return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer);
        };
        /**
         * Transform operations such that they represent the same logic edit,
         * but that they also do not cause OOM crashes.
         */
        EditableTextModel.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 ammount 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)];
        };
        EditableTextModel.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._lines[lineNumber - 1].text.substring(lastEndColumn - 1));
                    }
                    else {
                        result.push('\n');
                        result.push(this._lines[lineNumber - 1].text);
                    }
                }
                if (range.startLineNumber === lastEndLineNumber) {
                    result.push(this._lines[range.startLineNumber - 1].text.substring(lastEndColumn - 1, range.startColumn - 1));
                }
                else {
                    result.push('\n');
                    result.push(this._lines[range.startLineNumber - 1].text.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,
                rangeLength: this.getValueLengthInRange(entireEditRange),
                lines: result.join('').split('\n'),
                forceMoveMarkers: forceMoveMarkers,
                isAutoWhitespaceEdit: false
            };
        };
        EditableTextModel._sortOpsAscending = function (a, b) {
            var r = range_1.Range.compareRangesUsingEnds(a.range, b.range);
            if (r === 0) {
                return a.sortIndex - b.sortIndex;
            }
            return r;
        };
        EditableTextModel._sortOpsDescending = function (a, b) {
            var r = range_1.Range.compareRangesUsingEnds(a.range, b.range);
            if (r === 0) {
                return b.sortIndex - a.sortIndex;
            }
            return -r;
        };
        EditableTextModel.prototype.applyEdits = function (rawOperations) {
            try {
                this._eventEmitter.beginDeferredEmit();
                var markersTracker = this._acquireMarkersTracker();
                return this._applyEdits(markersTracker, rawOperations);
            }
            finally {
                this._releaseMarkersTracker();
                this._eventEmitter.endDeferredEmit();
            }
        };
        EditableTextModel.prototype._applyEdits = function (markersTracker, rawOperations) {
            if (rawOperations.length === 0) {
                return [];
            }
            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 = this.validateRange(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,
                    range: validatedRange,
                    rangeLength: this.getValueLengthInRange(validatedRange),
                    lines: op.text ? op.text.split(/\r\n|\r|\n/) : null,
                    forceMoveMarkers: op.forceMoveMarkers,
                    isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false
                };
            }
            // Sort operations ascending
            operations.sort(EditableTextModel._sortOpsAscending);
            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.isBefore(rangeEnd)) {
                    // overlapping ranges
                    throw new Error('Overlapping ranges are not allowed!');
                }
            }
            if (canReduceOperations) {
                operations = this._reduceOperations(operations);
            }
            var editableRange = this.getEditableRange();
            var editableRangeStart = editableRange.getStartPosition();
            var editableRangeEnd = editableRange.getEndPosition();
            for (var i = 0; i < operations.length; i++) {
                var operationRange = operations[i].range;
                if (!editableRangeStart.isBeforeOrEqual(operationRange.getStartPosition()) || !operationRange.getEndPosition().isBeforeOrEqual(editableRangeEnd)) {
                    throw new Error('Editing outside of editable range not allowed!');
                }
            }
            // Delta encode operations
            var reverseRanges = EditableTextModel._getInverseEditRanges(operations);
            var reverseOperations = [];
            var newTrimAutoWhitespaceCandidates = [];
            for (var i = 0; i < operations.length; i++) {
                var op = operations[i];
                var reverseRange = reverseRanges[i];
                reverseOperations[i] = {
                    identifier: op.identifier,
                    range: reverseRange,
                    text: this.getValueInRange(op.range),
                    forceMoveMarkers: op.forceMoveMarkers
                };
                if (this._options.trimAutoWhitespace && 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 });
                    }
                }
            }
            this._mightContainRTL = mightContainRTL;
            this._mightContainNonBasicASCII = mightContainNonBasicASCII;
            this._doApplyEdits(markersTracker, operations);
            this._trimAutoWhitespaceLines = null;
            if (this._options.trimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) {
                // sort line numbers auto whitespace removal candidates for next edit descending
                newTrimAutoWhitespaceCandidates.sort(function (a, b) { return b.lineNumber - a.lineNumber; });
                this._trimAutoWhitespaceLines = [];
                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;
                    }
                    this._trimAutoWhitespaceLines.push(lineNumber);
                }
            }
            return reverseOperations;
        };
        /**
         * Assumes `operations` are validated and sorted ascending
         */
        EditableTextModel._getInverseEditRanges = function (operations) {
            var result = [];
            var prevOpEndLineNumber;
            var prevOpEndColumn;
            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;
        };
        EditableTextModel.prototype._doApplyEdits = function (markersTracker, operations) {
            var _this = this;
            var tabSize = this._options.tabSize;
            // Sort operations descending
            operations.sort(EditableTextModel._sortOpsDescending);
            var rawContentChanges = [];
            var contentChanges = [];
            var lineEditsQueue = [];
            var queueLineEdit = function (lineEdit) {
                if (lineEdit.startColumn === lineEdit.endColumn && lineEdit.text.length === 0) {
                    // empty edit => ignore it
                    return;
                }
                lineEditsQueue.push(lineEdit);
            };
            var flushLineEdits = function () {
                if (lineEditsQueue.length === 0) {
                    return;
                }
                lineEditsQueue.reverse();
                // `lineEditsQueue` now contains edits from smaller (line number,column) to larger (line number,column)
                var currentLineNumber = lineEditsQueue[0].lineNumber;
                var currentLineNumberStart = 0;
                for (var i = 1, len = lineEditsQueue.length; i < len; i++) {
                    var lineNumber = lineEditsQueue[i].lineNumber;
                    if (lineNumber === currentLineNumber) {
                        continue;
                    }
                    _this._invalidateLine(currentLineNumber - 1);
                    _this._lines[currentLineNumber - 1].applyEdits(markersTracker, lineEditsQueue.slice(currentLineNumberStart, i), tabSize);
                    if (_this._lineStarts) {
                        // update prefix sum
                        _this._lineStarts.changeValue(currentLineNumber - 1, _this._lines[currentLineNumber - 1].text.length + _this._EOL.length);
                    }
                    rawContentChanges.push(new textModelEvents.ModelRawLineChanged(currentLineNumber, _this._lines[currentLineNumber - 1].text));
                    currentLineNumber = lineNumber;
                    currentLineNumberStart = i;
                }
                _this._invalidateLine(currentLineNumber - 1);
                _this._lines[currentLineNumber - 1].applyEdits(markersTracker, lineEditsQueue.slice(currentLineNumberStart, lineEditsQueue.length), tabSize);
                if (_this._lineStarts) {
                    // update prefix sum
                    _this._lineStarts.changeValue(currentLineNumber - 1, _this._lines[currentLineNumber - 1].text.length + _this._EOL.length);
                }
                rawContentChanges.push(new textModelEvents.ModelRawLineChanged(currentLineNumber, _this._lines[currentLineNumber - 1].text));
                lineEditsQueue = [];
            };
            var minTouchedLineNumber = operations[operations.length - 1].range.startLineNumber;
            var maxTouchedLineNumber = operations[0].range.endLineNumber + 1;
            var totalLinesCountDelta = 0;
            for (var i = 0, len = operations.length; i < len; i++) {
                var op = operations[i];
                // console.log();
                // console.log('-------------------');
                // console.log('OPERATION #' + (i));
                // console.log('op: ', op);
                // console.log('<<<\n' + this._lines.map(l => l.text).join('\n') + '\n>>>');
                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);
                totalLinesCountDelta += (insertingLinesCnt - deletingLinesCnt);
                // Iterating descending to overlap with previous op
                // in case there are common lines being edited in both
                for (var j = editingLinesCnt; j >= 0; j--) {
                    var editLineNumber = startLineNumber + j;
                    queueLineEdit({
                        lineNumber: editLineNumber,
                        startColumn: (editLineNumber === startLineNumber ? startColumn : 1),
                        endColumn: (editLineNumber === endLineNumber ? endColumn : this.getLineMaxColumn(editLineNumber)),
                        text: (op.lines ? op.lines[j] : ''),
                        forceMoveMarkers: op.forceMoveMarkers
                    });
                }
                if (editingLinesCnt < deletingLinesCnt) {
                    // Must delete some lines
                    // Flush any pending line edits
                    flushLineEdits();
                    var spliceStartLineNumber = startLineNumber + editingLinesCnt;
                    var spliceStartColumn = this.getLineMaxColumn(spliceStartLineNumber);
                    var endLineRemains = this._lines[endLineNumber - 1].split(markersTracker, endColumn, false, tabSize);
                    this._invalidateLine(spliceStartLineNumber - 1);
                    var spliceCnt = endLineNumber - spliceStartLineNumber;
                    // Collect all these markers
                    var markersOnDeletedLines = [];
                    for (var j = 0; j < spliceCnt; j++) {
                        var deleteLineIndex = spliceStartLineNumber + j;
                        var deleteLineMarkers = this._lines[deleteLineIndex].getMarkers();
                        if (deleteLineMarkers) {
                            markersOnDeletedLines = markersOnDeletedLines.concat(deleteLineMarkers);
                        }
                    }
                    this._lines.splice(spliceStartLineNumber, spliceCnt);
                    if (this._lineStarts) {
                        // update prefix sum
                        this._lineStarts.removeValues(spliceStartLineNumber, spliceCnt);
                    }
                    // Reconstruct first line
                    this._lines[spliceStartLineNumber - 1].append(markersTracker, spliceStartLineNumber, endLineRemains, tabSize);
                    if (this._lineStarts) {
                        // update prefix sum
                        this._lineStarts.changeValue(spliceStartLineNumber - 1, this._lines[spliceStartLineNumber - 1].text.length + this._EOL.length);
                    }
                    // Update deleted markers
                    var deletedMarkersPosition = new position_1.Position(spliceStartLineNumber, spliceStartColumn);
                    for (var j = 0, lenJ = markersOnDeletedLines.length; j < lenJ; j++) {
                        markersOnDeletedLines[j].updatePosition(markersTracker, deletedMarkersPosition);
                    }
                    this._lines[spliceStartLineNumber - 1].addMarkers(markersOnDeletedLines);
                    rawContentChanges.push(new textModelEvents.ModelRawLineChanged(spliceStartLineNumber, this._lines[spliceStartLineNumber - 1].text));
                    rawContentChanges.push(new textModelEvents.ModelRawLinesDeleted(spliceStartLineNumber + 1, spliceStartLineNumber + spliceCnt));
                }
                if (editingLinesCnt < insertingLinesCnt) {
                    // Must insert some lines
                    // Flush any pending line edits
                    flushLineEdits();
                    var spliceLineNumber = startLineNumber + editingLinesCnt;
                    var spliceColumn = (spliceLineNumber === startLineNumber ? startColumn : 1);
                    if (op.lines) {
                        spliceColumn += op.lines[editingLinesCnt].length;
                    }
                    // Split last line
                    var leftoverLine = this._lines[spliceLineNumber - 1].split(markersTracker, spliceColumn, op.forceMoveMarkers, tabSize);
                    if (this._lineStarts) {
                        // update prefix sum
                        this._lineStarts.changeValue(spliceLineNumber - 1, this._lines[spliceLineNumber - 1].text.length + this._EOL.length);
                    }
                    rawContentChanges.push(new textModelEvents.ModelRawLineChanged(spliceLineNumber, this._lines[spliceLineNumber - 1].text));
                    this._invalidateLine(spliceLineNumber - 1);
                    // Lines in the middle
                    var newLines = [];
                    var newLinesContent = [];
                    var newLinesLengths = new Uint32Array(insertingLinesCnt - editingLinesCnt);
                    for (var j = editingLinesCnt + 1; j <= insertingLinesCnt; j++) {
                        newLines.push(this._createModelLine(op.lines[j], tabSize));
                        newLinesContent.push(op.lines[j]);
                        newLinesLengths[j - editingLinesCnt - 1] = op.lines[j].length + this._EOL.length;
                    }
                    this._lines = arrays.arrayInsert(this._lines, startLineNumber + editingLinesCnt, newLines);
                    newLinesContent[newLinesContent.length - 1] += leftoverLine.text;
                    if (this._lineStarts) {
                        // update prefix sum
                        this._lineStarts.insertValues(startLineNumber + editingLinesCnt, newLinesLengths);
                    }
                    // Last line
                    this._lines[startLineNumber + insertingLinesCnt - 1].append(markersTracker, startLineNumber + insertingLinesCnt, leftoverLine, tabSize);
                    if (this._lineStarts) {
                        // update prefix sum
                        this._lineStarts.changeValue(startLineNumber + insertingLinesCnt - 1, this._lines[startLineNumber + insertingLinesCnt - 1].text.length + this._EOL.length);
                    }
                    rawContentChanges.push(new textModelEvents.ModelRawLinesInserted(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLinesContent.join('\n')));
                }
                contentChanges.push({
                    range: new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn),
                    rangeLength: op.rangeLength,
                    text: op.lines ? op.lines.join(this.getEOL()) : ''
                });
                // console.log('AFTER:');
                // console.log('<<<\n' + this._lines.map(l => l.text).join('\n') + '\n>>>');
            }
            flushLineEdits();
            maxTouchedLineNumber = Math.max(1, Math.min(this.getLineCount(), maxTouchedLineNumber + totalLinesCountDelta));
            if (totalLinesCountDelta !== 0) {
                // must update line numbers all the way to the bottom
                maxTouchedLineNumber = this.getLineCount();
            }
            for (var lineNumber = minTouchedLineNumber; lineNumber <= maxTouchedLineNumber; lineNumber++) {
                this._lines[lineNumber - 1].updateLineNumber(markersTracker, lineNumber);
            }
            if (rawContentChanges.length !== 0 || contentChanges.length !== 0) {
                this._increaseVersionId();
                this._emitModelRawContentChangedEvent(new textModelEvents.ModelRawContentChangedEvent(rawContentChanges, this.getVersionId(), this._isUndoing, this._isRedoing));
                var e = {
                    changes: contentChanges,
                    eol: this._EOL,
                    versionId: this.getVersionId(),
                    isUndoing: this._isUndoing,
                    isRedoing: this._isRedoing,
                    isFlush: false
                };
                this._eventEmitter.emit(textModelEvents.TextModelEventType.ModelContentChanged, e);
            }
            // this._assertLineNumbersOK();
            this._resetIndentRanges();
        };
        EditableTextModel.prototype._assertLineNumbersOK = function () {
            var foundMarkersCnt = 0;
            for (var i = 0, len = this._lines.length; i < len; i++) {
                var line = this._lines[i];
                var lineNumber = i + 1;
                var markers = line.getMarkers();
                if (markers !== null) {
                    for (var j = 0, lenJ = markers.length; j < lenJ; j++) {
                        foundMarkersCnt++;
                        var markerId = markers[j].id;
                        var marker = this._markerIdToMarker[markerId];
                        if (marker.position.lineNumber !== lineNumber) {
                            throw new Error('Misplaced marker with id ' + markerId);
                        }
                    }
                }
            }
            var totalMarkersCnt = Object.keys(this._markerIdToMarker).length;
            if (totalMarkersCnt !== foundMarkersCnt) {
                throw new Error('There are misplaced markers!');
            }
        };
        EditableTextModel.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;
        };
        EditableTextModel.prototype.undo = function () {
            try {
                this._eventEmitter.beginDeferredEmit();
                this._acquireMarkersTracker();
                return this._undo();
            }
            finally {
                this._releaseMarkersTracker();
                this._eventEmitter.endDeferredEmit();
            }
        };
        EditableTextModel.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;
        };
        EditableTextModel.prototype.redo = function () {
            try {
                this._eventEmitter.beginDeferredEmit();
                this._acquireMarkersTracker();
                return this._redo();
            }
            finally {
                this._releaseMarkersTracker();
                this._eventEmitter.endDeferredEmit();
            }
        };
        EditableTextModel.prototype.setEditableRange = function (range) {
            var _this = this;
            this._commandManager.clear();
            if (!this._hasEditableRange && !range) {
                // Nothing to do
                return;
            }
            this.changeDecorations(function (changeAccessor) {
                if (_this._hasEditableRange) {
                    changeAccessor.removeDecoration(_this._editableRangeId);
                    _this._editableRangeId = null;
                    _this._hasEditableRange = false;
                }
                if (range) {
                    _this._hasEditableRange = true;
                    _this._editableRangeId = changeAccessor.addDecoration(range, EditableTextModel._DECORATION_OPTION);
                }
            });
        };
        EditableTextModel.prototype.hasEditableRange = function () {
            return this._hasEditableRange;
        };
        EditableTextModel.prototype.getEditableRange = function () {
            if (this._hasEditableRange) {
                return this.getDecorationRange(this._editableRangeId);
            }
            else {
                return this.getFullModelRange();
            }
        };
        EditableTextModel._DECORATION_OPTION = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges
        });
        return EditableTextModel;
    }(textModelWithDecorations_1.TextModelWithDecorations));
    exports.EditableTextModel = EditableTextModel;
});











define(__m[175/*vs/editor/common/model/model*/], __M([1/*require*/,0/*exports*/,24/*vs/base/common/uri*/,326/*vs/editor/common/model/editableTextModel*/,93/*vs/editor/common/model/textModel*/,101/*vs/editor/common/model/textSource*/,55/*vs/editor/common/model/textModelEvents*/]), function (require, exports, uri_1, editableTextModel_1, textModel_1, textSource_1, textModelEvents) {
    /*---------------------------------------------------------------------------------------------
     *  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 });
    // The hierarchy is:
    // Model -> EditableTextModel -> TextModelWithDecorations -> TextModelWithTrackedRanges -> TextModelWithMarkers -> TextModelWithTokens -> TextModel
    var MODEL_ID = 0;
    var Model = (function (_super) {
        __extends(Model, _super);
        function Model(rawTextSource, creationOptions, languageIdentifier, associatedResource) {
            if (associatedResource === void 0) { associatedResource = null; }
            var _this = _super.call(this, rawTextSource, creationOptions, languageIdentifier) || this;
            // Generate a new unique model id
            MODEL_ID++;
            _this.id = '$model' + MODEL_ID;
            if (typeof associatedResource === 'undefined' || associatedResource === null) {
                _this._associatedResource = uri_1.default.parse('inmemory://model/' + MODEL_ID);
            }
            else {
                _this._associatedResource = associatedResource;
            }
            _this._attachedEditorCount = 0;
            return _this;
        }
        Model.prototype.onDidChangeDecorations = function (listener) {
            return this._eventEmitter.addListener(textModelEvents.TextModelEventType.ModelDecorationsChanged, listener);
        };
        Model.prototype.onDidChangeOptions = function (listener) {
            return this._eventEmitter.addListener(textModelEvents.TextModelEventType.ModelOptionsChanged, listener);
        };
        Model.prototype.onWillDispose = function (listener) {
            return this._eventEmitter.addListener(textModelEvents.TextModelEventType.ModelDispose, listener);
        };
        Model.prototype.onDidChangeLanguage = function (listener) {
            return this._eventEmitter.addListener(textModelEvents.TextModelEventType.ModelLanguageChanged, listener);
        };
        Model.createFromString = function (text, options, languageIdentifier, uri) {
            if (options === void 0) { options = textModel_1.TextModel.DEFAULT_CREATION_OPTIONS; }
            if (languageIdentifier === void 0) { languageIdentifier = null; }
            if (uri === void 0) { uri = null; }
            return new Model(textSource_1.RawTextSource.fromString(text), options, languageIdentifier, uri);
        };
        Model.prototype.destroy = function () {
            this.dispose();
        };
        Model.prototype.dispose = function () {
            this._isDisposing = true;
            this._eventEmitter.emit(textModelEvents.TextModelEventType.ModelDispose);
            _super.prototype.dispose.call(this);
            this._isDisposing = false;
        };
        Model.prototype.onBeforeAttached = function () {
            this._attachedEditorCount++;
            // Warm up tokens for the editor
            this._warmUpTokens();
        };
        Model.prototype.onBeforeDetached = function () {
            this._attachedEditorCount--;
        };
        Model.prototype._shouldAutoTokenize = function () {
            return this.isAttachedToEditor();
        };
        Model.prototype.isAttachedToEditor = function () {
            return this._attachedEditorCount > 0;
        };
        Object.defineProperty(Model.prototype, "uri", {
            get: function () {
                return this._associatedResource;
            },
            enumerable: true,
            configurable: true
        });
        return Model;
    }(editableTextModel_1.EditableTextModel));
    exports.Model = Model;
});

define(__m[179/*vs/editor/common/viewModel/splitLinesCollection*/], __M([1/*require*/,0/*exports*/,12/*vs/editor/common/core/position*/,22/*vs/editor/common/core/selection*/,2/*vs/editor/common/core/range*/,104/*vs/editor/common/viewModel/prefixSumComputer*/,86/*vs/editor/common/viewModel/viewModel*/,57/*vs/editor/common/view/viewEvents*/,34/*vs/editor/common/model/textModelWithDecorations*/]), function (require, exports, position_1, selection_1, range_1, prefixSumComputer_1, viewModel_1, viewEvents, textModelWithDecorations_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var OutputPosition = (function () {
        function OutputPosition(outputLineIndex, outputOffset) {
            this.outputLineIndex = outputLineIndex;
            this.outputOffset = outputOffset;
        }
        return OutputPosition;
    }());
    exports.OutputPosition = OutputPosition;
    var CoordinatesConverter = (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.convertViewSelectionToModelSelection = function (viewSelection) {
            var selectionStart = this._lines.convertViewPositionToModelPosition(viewSelection.selectionStartLineNumber, viewSelection.selectionStartColumn);
            var position = this._lines.convertViewPositionToModelPosition(viewSelection.positionLineNumber, viewSelection.positionColumn);
            return new selection_1.Selection(selectionStart.lineNumber, selectionStart.column, position.lineNumber, position.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.convertModelSelectionToViewSelection = function (modelSelection) {
            var selectionStart = this._lines.convertModelPositionToViewPosition(modelSelection.selectionStartLineNumber, modelSelection.selectionStartColumn);
            var position = this._lines.convertModelPositionToViewPosition(modelSelection.positionLineNumber, modelSelection.positionColumn);
            return new selection_1.Selection(selectionStart.lineNumber, selectionStart.column, position.lineNumber, position.column);
        };
        CoordinatesConverter.prototype.modelPositionIsVisible = function (modelPosition) {
            return this._lines.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column);
        };
        return CoordinatesConverter;
    }());
    exports.CoordinatesConverter = CoordinatesConverter;
    var SplitLinesCollection = (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) {
                throw new Error('SplitLinesCollection: attempt to access a \'newer\' model');
            }
        };
        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);
            }).sort(range_1.Range.compareRangesUsingStarts);
        };
        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; i < newRanges.length; i++) {
                newDecorations.push({
                    range: newRanges[i],
                    options: textModelWithDecorations_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;
            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 {
                    // 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);
                }
            }
            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; i < hiddenAreas.length; i++) {
                if (hiddenAreas[i].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;
            }
            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;
        };
        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.getViewLineIndentGuide = function (viewLineNumber) {
            this._ensureValidState();
            viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
            var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
            return this.model.getLineIndentGuide(r.index + 1);
        };
        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.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;
        };
        return SplitLinesCollection;
    }());
    exports.SplitLinesCollection = SplitLinesCollection;
    var VisibleIdentitySplitLine = (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.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, 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.INSTANCE = new VisibleIdentitySplitLine();
        return VisibleIdentitySplitLine;
    }());
    var InvisibleIdentitySplitLine = (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.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.INSTANCE = new InvisibleIdentitySplitLine();
        return InvisibleIdentitySplitLine;
    }());
    var SplitLine = (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.getLineContent(modelLineNumber).substring(startOffset, endOffset);
            if (outputLineIndex > 0) {
                r = this.wrappedIndent + 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.getLineContent(modelLineNumber).substring(startOffset, endOffset);
            if (outputLineIndex > 0) {
                lineContent = this.wrappedIndent + lineContent;
            }
            var minColumn = (outputLineIndex > 0 ? this.wrappedIndentLength + 1 : 1);
            var maxColumn = lineContent.length + 1;
            var deltaStartIndex = 0;
            if (outputLineIndex > 0) {
                deltaStartIndex = this.wrappedIndentLength;
            }
            var lineTokens = model.getLineTokens(modelLineNumber);
            return new viewModel_1.ViewLineData(lineContent, 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);
        };
        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 = (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);
        };
        IdentityCoordinatesConverter.prototype._validSelection = function (selection) {
            var selectionStart = this._validPosition(new position_1.Position(selection.selectionStartLineNumber, selection.selectionStartColumn));
            var position = this._validPosition(new position_1.Position(selection.positionLineNumber, selection.positionColumn));
            return new selection_1.Selection(selectionStart.lineNumber, selectionStart.column, position.lineNumber, position.column);
        };
        // 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.convertViewSelectionToModelSelection = function (viewSelection) {
            return this._validSelection(viewSelection);
        };
        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.convertModelSelectionToViewSelection = function (modelSelection) {
            return this._validSelection(modelSelection);
        };
        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 = (function () {
        function IdentityLinesCollection(model) {
            this.model = model;
        }
        IdentityLinesCollection.prototype.dispose = function () {
        };
        IdentityLinesCollection.prototype.createCoordinatesConverter = function () {
            return new IdentityCoordinatesConverter(this);
        };
        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.getViewLineIndentGuide = function (viewLineNumber) {
            return 0;
        };
        IdentityLinesCollection.prototype.getViewLineContent = function (viewLineNumber) {
            return this.model.getLineContent(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, 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;
        };
        return IdentityLinesCollection;
    }());
    exports.IdentityLinesCollection = IdentityLinesCollection;
});











define(__m[329/*vs/editor/common/viewModel/characterHardWrappingLineMapper*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,104/*vs/editor/common/viewModel/prefixSumComputer*/,179/*vs/editor/common/viewModel/splitLinesCollection*/,89/*vs/editor/common/core/characterClassifier*/,96/*vs/editor/common/core/uint*/,49/*vs/editor/common/config/editorOptions*/]), function (require, exports, strings, prefixSumComputer_1, splitLinesCollection_1, characterClassifier_1, uint_1, editorOptions_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CharacterClass;
    (function (CharacterClass) {
        CharacterClass[CharacterClass["NONE"] = 0] = "NONE";
        CharacterClass[CharacterClass["BREAK_BEFORE"] = 1] = "BREAK_BEFORE";
        CharacterClass[CharacterClass["BREAK_AFTER"] = 2] = "BREAK_AFTER";
        CharacterClass[CharacterClass["BREAK_OBTRUSIVE"] = 3] = "BREAK_OBTRUSIVE";
        CharacterClass[CharacterClass["BREAK_IDEOGRAPHIC"] = 4] = "BREAK_IDEOGRAPHIC"; // for Han and Kana.
    })(CharacterClass || (CharacterClass = {}));
    var WrappingCharacterClassifier = (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 = (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 !== editorOptions_1.WrappingIndent.None) {
                firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineText);
                if (firstNonWhitespaceIndex !== -1) {
                    wrappedTextIndent = lineText.substring(0, firstNonWhitespaceIndex);
                    for (var i = 0; i < firstNonWhitespaceIndex; i++) {
                        wrappedTextIndentVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(wrappedTextIndentVisibleColumn, tabSize, lineText.charCodeAt(i) === 9 /* Tab */, 1);
                    }
                    if (hardWrappingIndent === editorOptions_1.WrappingIndent.Indent) {
                        wrappedTextIndent += '\t';
                        wrappedTextIndentVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(wrappedTextIndentVisibleColumn, tabSize, true, 1);
                    }
                    // Force sticking to beginning of line if indentColumn > 66% breakingColumn
                    if (wrappedTextIndentVisibleColumn > 1 / 2 * 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 */) {
                        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 === editorOptions_1.WrappingIndent.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 */) {
                        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 = (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;
});











define(__m[330/*vs/editor/common/viewModel/viewModelImpl*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,17/*vs/editor/common/modes*/,122/*vs/editor/common/modes/textToHtmlTokenizer*/,240/*vs/editor/common/viewModel/viewModelDecorations*/,86/*vs/editor/common/viewModel/viewModel*/,179/*vs/editor/common/viewModel/splitLinesCollection*/,57/*vs/editor/common/view/viewEvents*/,111/*vs/editor/common/view/minimapCharRenderer*/,55/*vs/editor/common/model/textModelEvents*/,329/*vs/editor/common/viewModel/characterHardWrappingLineMapper*/,239/*vs/editor/common/viewLayout/viewLayout*/]), function (require, exports, strings, position_1, range_1, editorCommon, modes_1, textToHtmlTokenizer_1, viewModelDecorations_1, viewModel_1, splitLinesCollection_1, viewEvents, minimapCharRenderer_1, textModelEvents, characterHardWrappingLineMapper_1, viewLayout_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var USE_IDENTITY_LINES_COLLECTION = true;
    var ViewModel = (function (_super) {
        __extends(ViewModel, _super);
        function ViewModel(editorId, configuration, model) {
            var _this = _super.call(this) || this;
            _this.editorId = editorId;
            _this.configuration = configuration;
            _this.model = model;
            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()));
            _this._register(_this.viewLayout.onDidScroll(function (e) {
                _this._emit([new viewEvents.ViewScrollChangedEvent(e)]);
            }));
            _this._isDisposing = false;
            _this._centeredViewLine = -1;
            _this.decorations = new viewModelDecorations_1.ViewModelDecorations(_this.editorId, _this.model, _this.configuration, _this.coordinatesConverter);
            _this._register(_this.model.addBulkListener(function (events) {
                if (_this._isDisposing) {
                    // Disposing the lines might end up sending model decoration changed events
                    // ...we no longer care about them...
                    return;
                }
                var eventsCollector = new viewModel_1.ViewEventsCollector();
                _this._onModelEvents(eventsCollector, events);
                _this._emit(eventsCollector.finalize());
            }));
            _this._register(_this.configuration.onDidChange(function (e) {
                var eventsCollector = new viewModel_1.ViewEventsCollector();
                _this._onConfigurationChanged(eventsCollector, e);
                _this._emit(eventsCollector.finalize());
            }));
            _this._register(minimapCharRenderer_1.MinimapTokensColorTracker.getInstance().onDidChange(function () {
                _this._emit([new viewEvents.ViewTokensColorsChangedEvent()]);
            }));
            return _this;
        }
        ViewModel.prototype.dispose = function () {
            this._isDisposing = true;
            this.decorations.dispose();
            this.lines.dispose();
            _super.prototype.dispose.call(this);
        };
        ViewModel.prototype._onConfigurationChanged = function (eventsCollector, e) {
            // We might need to restore the current centered view range, so save it (if available)
            var previousCenteredModelRange = this.getCenteredRangeInViewport();
            var revealPreviousCenteredModelRange = 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.getScrollTop() !== 0) {
                    // Never change the scroll position from 0 to something else...
                    revealPreviousCenteredModelRange = 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 (revealPreviousCenteredModelRange && previousCenteredModelRange) {
                // modelLine -> viewLine
                var newCenteredViewRange = this.coordinatesConverter.convertModelRangeToViewRange(previousCenteredModelRange);
                // Send a reveal event to restore the centered content
                eventsCollector.emit(new viewEvents.ViewRevealRangeRequestEvent(newCenteredViewRange, 1 /* Center */, false));
            }
        };
        ViewModel.prototype._onModelEvents = function (eventsCollector, events) {
            // A quick check if there are model content change events incoming
            // in order to update the configuration and reset the centered view line
            for (var i = 0, len = events.length; i < len; i++) {
                var eventType = events[i].type;
                if (eventType === textModelEvents.TextModelEventType.ModelRawContentChanged2) {
                    // There is a content change event
                    this._centeredViewLine = -1;
                    this.configuration.setMaxLineNumber(this.model.getLineCount());
                    break;
                }
            }
            var hadOtherModelChange = false;
            var hadModelLineChangeThatChangedLineMapping = false;
            for (var i = 0, len = events.length; i < len; i++) {
                var _e = events[i];
                var type = _e.type;
                var data = _e.data;
                switch (type) {
                    case textModelEvents.TextModelEventType.ModelRawContentChanged2: {
                        var e = data;
                        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.split('\n'));
                                    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);
                        break;
                    }
                    case textModelEvents.TextModelEventType.ModelTokensChanged: {
                        var e = data;
                        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
                            };
                        }
                        eventsCollector.emit(new viewEvents.ViewTokensChangedEvent(viewRanges));
                        break;
                    }
                    case textModelEvents.TextModelEventType.ModelLanguageChanged: {
                        // That's ok, a model tokens changed event will follow shortly
                        break;
                    }
                    case textModelEvents.TextModelEventType.ModelContentChanged: {
                        // Ignore
                        break;
                    }
                    case textModelEvents.TextModelEventType.ModelOptionsChanged: {
                        // 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)) {
                            eventsCollector.emit(new viewEvents.ViewFlushedEvent());
                            eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent());
                            eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());
                            this.decorations.onLineMappingChanged();
                            this.viewLayout.onFlushed(this.getLineCount());
                        }
                        break;
                    }
                    case textModelEvents.TextModelEventType.ModelDecorationsChanged: {
                        var e = data;
                        this.decorations.onModelDecorationsChanged(e);
                        eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());
                        break;
                    }
                    case textModelEvents.TextModelEventType.ModelDispose: {
                        // Ignore, since the editor will take care of this and destroy the view shortly
                        break;
                    }
                    default:
                        console.info('View received unknown event: ');
                        console.info(type, data);
                }
            }
            if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) {
                eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent());
                eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());
                this.decorations.onLineMappingChanged();
            }
        };
        ViewModel.prototype.setHiddenAreas = function (ranges) {
            var eventsCollector = new viewModel_1.ViewEventsCollector();
            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._emit(eventsCollector.finalize());
        };
        ViewModel.prototype.getCenteredRangeInViewport = function () {
            if (this._centeredViewLine === -1) {
                // Never got rendered or not rendered since last content change event
                return null;
            }
            var viewLineNumber = this._centeredViewLine;
            var currentCenteredViewRange = new range_1.Range(viewLineNumber, this.getLineMinColumn(viewLineNumber), viewLineNumber, this.getLineMaxColumn(viewLineNumber));
            return this.coordinatesConverter.convertViewRangeToModelRange(currentCenteredViewRange);
        };
        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.getTabSize = function () {
            return this.model.getOptions().tabSize;
        };
        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._centeredViewLine = centeredLineNumber;
            this.lines.warmUpLookupCache(startLineNumber, endLineNumber);
        };
        ViewModel.prototype.getLineIndentGuide = function (lineNumber) {
            return this.lines.getViewLineIndentGuide(lineNumber);
        };
        ViewModel.prototype.getLineContent = function (lineNumber) {
            return this.lines.getViewLineContent(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, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize);
        };
        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 () {
            return this.decorations.getAllOverviewRulerDecorations();
        };
        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.getPlainTextToCopy = function (ranges, emptySelectionClipboard) {
            var newLineCharacter = this.model.getEOL();
            if (ranges.length === 1) {
                var range = ranges[0];
                if (range.isEmpty()) {
                    if (emptySelectionClipboard) {
                        var modelLineNumber = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(range.startLineNumber, 1)).lineNumber;
                        return this.model.getLineContent(modelLineNumber) + newLineCharacter;
                    }
                    else {
                        return '';
                    }
                }
                return this.getValueInRange(range, editorCommon.EndOfLinePreference.TextDefined);
            }
            else {
                ranges = ranges.slice(0).sort(range_1.Range.compareRangesUsingStarts);
                var result = [];
                for (var i = 0; i < ranges.length; i++) {
                    result.push(this.getValueInRange(ranges[i], editorCommon.EndOfLinePreference.TextDefined));
                }
                return result.join(newLineCharacter);
            }
        };
        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 ("<div style=\""
                + ("color: " + colorMap[1 /* DefaultForeground */] + ";")
                + ("background-color: " + colorMap[2 /* DefaultBackground */] + ";")
                + ("font-family: " + fontInfo.fontFamily + ";")
                + ("font-weight: " + fontInfo.fontWeight + ";")
                + ("font-size: " + fontInfo.fontSize + "px;")
                + ("line-height: " + fontInfo.lineHeight + "px;")
                + "white-space: pre;"
                + "\">"
                + this._getHTMLToCopy(range, colorMap)
                + '</div>');
        };
        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 += '<br>';
                }
                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 = [null];
            for (var i = 1, len = colorMap.length; i < len; i++) {
                result[i] = colorMap[i].toRGBHex();
            }
            return result;
        };
        return ViewModel;
    }(viewEvents.ViewEventEmitter));
    exports.ViewModel = ViewModel;
});

define(__m[331/*vs/editor/contrib/find/common/findDecorations*/], __M([1/*require*/,0/*exports*/,20/*vs/editor/common/editorCommon*/,34/*vs/editor/common/model/textModelWithDecorations*/]), function (require, exports, editorCommon, textModelWithDecorations_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var FindDecorations = (function () {
        function FindDecorations(editor) {
            this._editor = editor;
            this._decorations = [];
            this._findScopeDecorationId = null;
            this._rangeHighlightDecorationId = null;
            this._highlightedDecorationId = null;
            this._startPosition = this._editor.getPosition();
        }
        FindDecorations.prototype.dispose = function () {
            this._editor.deltaDecorations(this._allDecorations(), []);
            this._editor = null;
            this._decorations = [];
            this._findScopeDecorationId = null;
            this._rangeHighlightDecorationId = null;
            this._highlightedDecorationId = null;
            this._startPosition = null;
        };
        FindDecorations.prototype.reset = function () {
            this._decorations = [];
            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.getCurrentMatchesPosition = function (desiredRange) {
            for (var i = 0, len = this._decorations.length; i < len; i++) {
                var range = this._editor.getModel().getDecorationRange(this._decorations[i]);
                if (desiredRange.equalsRange(range)) {
                    return (i + 1);
                }
            }
            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.createFindMatchDecorationOptions(false));
                        _this._highlightedDecorationId = null;
                    }
                    if (newCurrentDecorationId !== null) {
                        _this._highlightedDecorationId = newCurrentDecorationId;
                        changeAccessor.changeDecorationOptions(_this._highlightedDecorationId, FindDecorations.createFindMatchDecorationOptions(true));
                    }
                    if (_this._rangeHighlightDecorationId !== null) {
                        changeAccessor.removeDecoration(_this._rangeHighlightDecorationId);
                        _this._rangeHighlightDecorationId = null;
                    }
                    if (newCurrentDecorationId !== null) {
                        var rng = _this._editor.getModel().getDecorationRange(newCurrentDecorationId);
                        _this._rangeHighlightDecorationId = changeAccessor.addDecoration(rng, FindDecorations._RANGE_HIGHLIGHT_DECORATION);
                    }
                });
            }
            return matchPosition;
        };
        FindDecorations.prototype.set = function (matches, findScope) {
            var newDecorations = matches.map(function (match) {
                return {
                    range: match,
                    options: FindDecorations.createFindMatchDecorationOptions(false)
                };
            });
            if (findScope) {
                newDecorations.unshift({
                    range: findScope,
                    options: FindDecorations._FIND_SCOPE_DECORATION
                });
            }
            var tmpDecorations = this._editor.deltaDecorations(this._allDecorations(), newDecorations);
            if (findScope) {
                this._findScopeDecorationId = tmpDecorations.shift();
            }
            else {
                this._findScopeDecorationId = null;
            }
            this._decorations = tmpDecorations;
            this._rangeHighlightDecorationId = null;
            this._highlightedDecorationId = null;
        };
        FindDecorations.prototype._allDecorations = function () {
            var result = [];
            result = result.concat(this._decorations);
            if (this._findScopeDecorationId) {
                result.push(this._findScopeDecorationId);
            }
            if (this._rangeHighlightDecorationId) {
                result.push(this._rangeHighlightDecorationId);
            }
            return result;
        };
        FindDecorations.createFindMatchDecorationOptions = function (isCurrent) {
            return (isCurrent ? this._CURRENT_FIND_MATCH_DECORATION : this._FIND_MATCH_DECORATION);
        };
        FindDecorations._CURRENT_FIND_MATCH_DECORATION = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            className: 'currentFindMatch',
            showIfCollapsed: true,
            overviewRuler: {
                color: 'rgba(246, 185, 77, 0.7)',
                darkColor: 'rgba(246, 185, 77, 0.7)',
                position: editorCommon.OverviewRulerLane.Center
            }
        });
        FindDecorations._FIND_MATCH_DECORATION = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            className: 'findMatch',
            showIfCollapsed: true,
            overviewRuler: {
                color: 'rgba(246, 185, 77, 0.7)',
                darkColor: 'rgba(246, 185, 77, 0.7)',
                position: editorCommon.OverviewRulerLane.Center
            }
        });
        FindDecorations._RANGE_HIGHLIGHT_DECORATION = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            className: 'rangeHighlight',
            isWholeLine: true
        });
        FindDecorations._FIND_SCOPE_DECORATION = textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'findScope',
            isWholeLine: true
        });
        return FindDecorations;
    }());
    exports.FindDecorations = FindDecorations;
});

define(__m[121/*vs/editor/contrib/find/common/findModel*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/async*/,3/*vs/base/common/lifecycle*/,255/*vs/editor/contrib/find/common/replacePattern*/,73/*vs/editor/common/commands/replaceCommand*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,331/*vs/editor/contrib/find/common/findDecorations*/,254/*vs/editor/contrib/find/common/replaceAllCommand*/,22/*vs/editor/common/core/selection*/,158/*vs/editor/common/model/textModelSearch*/,54/*vs/editor/common/controller/cursorEvents*/]), function (require, exports, async_1, lifecycle_1, replacePattern_1, replaceCommand_1, position_1, range_1, editorCommon, findDecorations_1, replaceAllCommand_1, selection_1, textModelSearch_1, cursorEvents_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.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.ShowPreviousFindTermKeybinding = {
        primary: 512 /* Alt */ | 16 /* UpArrow */
    };
    exports.ShowNextFindTermKeybinding = {
        primary: 512 /* Alt */ | 18 /* DownArrow */
    };
    exports.FIND_IDS = {
        StartFindAction: 'actions.find',
        NextMatchFindAction: 'editor.action.nextMatchFindAction',
        PreviousMatchFindAction: 'editor.action.previousMatchFindAction',
        NextSelectionMatchFindAction: 'editor.action.nextSelectionMatchFindAction',
        PreviousSelectionMatchFindAction: 'editor.action.previousSelectionMatchFindAction',
        AddSelectionToNextFindMatchAction: 'editor.action.addSelectionToNextFindMatch',
        AddSelectionToPreviousFindMatchAction: 'editor.action.addSelectionToPreviousFindMatch',
        MoveSelectionToNextFindMatchAction: 'editor.action.moveSelectionToNextFindMatch',
        MoveSelectionToPreviousFindMatchAction: 'editor.action.moveSelectionToPreviousFindMatch',
        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',
        ShowPreviousFindTermAction: 'find.history.showPrevious',
        ShowNextFindTermAction: 'find.history.showNext'
    };
    exports.MATCHES_LIMIT = 999;
    var FindModelBoundToEditorModel = (function () {
        function FindModelBoundToEditorModel(editor, state) {
            var _this = this;
            this._editor = editor;
            this._state = state;
            this._toDispose = [];
            this._isDisposed = false;
            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 === cursorEvents_1.CursorChangeReason.Explicit
                    || e.reason === cursorEvents_1.CursorChangeReason.Undo
                    || e.reason === cursorEvents_1.CursorChangeReason.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.addChangeListener(function (e) { return _this._onStateChanged(e); }));
            this.research(false, this._state.searchScope);
        }
        FindModelBoundToEditorModel.prototype.dispose = function () {
            this._isDisposed = true;
            this._toDispose = lifecycle_1.dispose(this._toDispose);
        };
        FindModelBoundToEditorModel.prototype._onStateChanged = function (e) {
            if (this._isDisposed) {
                // The find model is disposed during a find state changed event
                return;
            }
            if (e.searchString || e.isReplaceRevealed || e.isRegex || e.wholeWord || e.matchCase || e.searchScope) {
                if (e.searchScope) {
                    this.research(e.moveCursor, this._state.searchScope);
                }
                else {
                    this.research(e.moveCursor);
                }
            }
        };
        FindModelBoundToEditorModel._getSearchRange = function (model, searchOnlyEditableRange, findScope) {
            var searchRange;
            if (searchOnlyEditableRange) {
                searchRange = model.getEditableRange();
            }
            else {
                searchRange = model.getFullModelRange();
            }
            // If we have set now or before a find scope, use it for computing the search range
            if (findScope) {
                searchRange = searchRange.intersectRanges(findScope);
            }
            return searchRange;
        };
        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) {
                    // 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.map(function (match) { return match.range; }), 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);
                }
                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);
        };
        FindModelBoundToEditorModel.prototype._moveToPrevMatch = function (before, isRecursed) {
            if (isRecursed === void 0) { isRecursed = false; }
            if (this._cannotFind()) {
                return;
            }
            var findScope = this._decorations.getFindScope();
            var searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), this._state.isReplaceRevealed, 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!
                var isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf('^') >= 0
                    || this._state.searchString.indexOf('$') >= 0);
                if (isUsingLineStops || column === 1) {
                    if (lineNumber === 1) {
                        lineNumber = model.getLineCount();
                    }
                    else {
                        lineNumber--;
                    }
                    column = model.getLineMaxColumn(lineNumber);
                }
                else {
                    column--;
                }
                position = new position_1.Position(lineNumber, column);
                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 null;
            }
            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._moveToNextMatch = function (after) {
            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(), this._state.isReplaceRevealed, 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!
                var isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf('^') >= 0
                    || this._state.searchString.indexOf('$') >= 0);
                if (isUsingLineStops || column === model.getLineMaxColumn(lineNumber)) {
                    if (lineNumber === model.getLineCount()) {
                        lineNumber = 1;
                    }
                    else {
                        lineNumber++;
                    }
                    column = 1;
                }
                else {
                    column++;
                }
                position = new position_1.Position(lineNumber, column);
                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(), this._state.isReplaceRevealed, 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 1k 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 model = this._editor.getModel();
            var modelText = model.getValue(editorCommon.EndOfLinePreference.LF);
            var fullModelRange = model.getFullModelRange();
            var replacePattern = this._getReplacePattern();
            var resultText;
            if (replacePattern.hasReplacementPatterns) {
                resultText = modelText.replace(searchData.regex, function () {
                    return replacePattern.buildReplaceString(arguments);
                });
            }
            else {
                resultText = modelText.replace(searchData.regex, 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[333/*vs/editor/contrib/folding/common/foldingModel*/], __M([1/*require*/,0/*exports*/,20/*vs/editor/common/editorCommon*/,2/*vs/editor/common/core/range*/,34/*vs/editor/common/model/textModelWithDecorations*/]), function (require, exports, editorCommon, range_1, textModelWithDecorations_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function toString(range) {
        return (range ? range.startLineNumber + '/' + range.endLineNumber : 'null') + (range.isCollapsed ? ' (collapsed)' : '') + ' - ' + range.indent;
    }
    exports.toString = toString;
    var CollapsibleRegion = (function () {
        function CollapsibleRegion(range, model, changeAccessor) {
            this.decorationIds = [];
            this.update(range, model, changeAccessor);
        }
        Object.defineProperty(CollapsibleRegion.prototype, "isCollapsed", {
            get: function () {
                return this._isCollapsed;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CollapsibleRegion.prototype, "isExpanded", {
            get: function () {
                return !this._isCollapsed;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CollapsibleRegion.prototype, "indent", {
            get: function () {
                return this._indent;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CollapsibleRegion.prototype, "foldingRange", {
            get: function () {
                return this._lastRange;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CollapsibleRegion.prototype, "startLineNumber", {
            get: function () {
                return this._lastRange ? this._lastRange.startLineNumber : void 0;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CollapsibleRegion.prototype, "endLineNumber", {
            get: function () {
                return this._lastRange ? this._lastRange.endLineNumber : void 0;
            },
            enumerable: true,
            configurable: true
        });
        CollapsibleRegion.prototype.setCollapsed = function (isCollaped, changeAccessor) {
            this._isCollapsed = isCollaped;
            if (this.decorationIds.length > 0) {
                changeAccessor.changeDecorationOptions(this.decorationIds[0], this.getVisualDecorationOptions());
            }
        };
        CollapsibleRegion.prototype.getDecorationRange = function (model) {
            if (this.decorationIds.length > 0) {
                return model.getDecorationRange(this.decorationIds[1]);
            }
            return null;
        };
        CollapsibleRegion.prototype.getVisualDecorationOptions = function () {
            if (this._isCollapsed) {
                return CollapsibleRegion._COLLAPSED_VISUAL_DECORATION;
            }
            else {
                return CollapsibleRegion._EXPANDED_VISUAL_DECORATION;
            }
        };
        CollapsibleRegion.prototype.getRangeDecorationOptions = function () {
            return CollapsibleRegion._RANGE_DECORATION;
        };
        CollapsibleRegion.prototype.update = function (newRange, model, changeAccessor) {
            this._lastRange = newRange;
            this._isCollapsed = !!newRange.isCollapsed;
            this._indent = newRange.indent;
            var newDecorations = [];
            var maxColumn = model.getLineMaxColumn(newRange.startLineNumber);
            var visualRng = {
                startLineNumber: newRange.startLineNumber,
                startColumn: maxColumn - 1,
                endLineNumber: newRange.startLineNumber,
                endColumn: maxColumn
            };
            newDecorations.push({ range: visualRng, options: this.getVisualDecorationOptions() });
            var colRng = {
                startLineNumber: newRange.startLineNumber,
                startColumn: 1,
                endLineNumber: newRange.endLineNumber,
                endColumn: model.getLineMaxColumn(newRange.endLineNumber)
            };
            newDecorations.push({ range: colRng, options: this.getRangeDecorationOptions() });
            this.decorationIds = changeAccessor.deltaDecorations(this.decorationIds, newDecorations);
        };
        CollapsibleRegion.prototype.dispose = function (changeAccessor) {
            this._lastRange = null;
            this.decorationIds = changeAccessor.deltaDecorations(this.decorationIds, []);
        };
        CollapsibleRegion.prototype.toString = function () {
            var str = this.isCollapsed ? 'collapsed ' : 'expanded ';
            if (this._lastRange) {
                str += (this._lastRange.startLineNumber + '/' + this._lastRange.endLineNumber);
            }
            else {
                str += 'no range';
            }
            return str;
        };
        CollapsibleRegion._COLLAPSED_VISUAL_DECORATION = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            afterContentClassName: 'inline-folded',
            linesDecorationsClassName: 'folding collapsed'
        });
        CollapsibleRegion._EXPANDED_VISUAL_DECORATION = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            linesDecorationsClassName: 'folding'
        });
        CollapsibleRegion._RANGE_DECORATION = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore
        });
        return CollapsibleRegion;
    }());
    exports.CollapsibleRegion = CollapsibleRegion;
    function getCollapsibleRegionsToFoldAtLine(allRegions, model, lineNumber, levels, up) {
        var surroundingRegion = getCollapsibleRegionAtLine(allRegions, model, lineNumber);
        if (!surroundingRegion) {
            return [];
        }
        if (levels === 1) {
            return [surroundingRegion];
        }
        var result = getCollapsibleRegionsFor(surroundingRegion, allRegions, model, levels, up);
        return result.filter(function (collapsibleRegion) { return !collapsibleRegion.isCollapsed; });
    }
    exports.getCollapsibleRegionsToFoldAtLine = getCollapsibleRegionsToFoldAtLine;
    function getCollapsibleRegionsToUnfoldAtLine(allRegions, model, lineNumber, levels) {
        var surroundingRegion = getCollapsibleRegionAtLine(allRegions, model, lineNumber);
        if (!surroundingRegion) {
            return [];
        }
        if (levels === 1) {
            var regionToUnfold = surroundingRegion.isCollapsed ? surroundingRegion : getFoldedCollapsibleRegionAfterLine(allRegions, model, surroundingRegion, lineNumber);
            return regionToUnfold ? [regionToUnfold] : [];
        }
        var result = getCollapsibleRegionsFor(surroundingRegion, allRegions, model, levels, false);
        return result.filter(function (collapsibleRegion) { return collapsibleRegion.isCollapsed; });
    }
    exports.getCollapsibleRegionsToUnfoldAtLine = getCollapsibleRegionsToUnfoldAtLine;
    function getCollapsibleRegionAtLine(allRegions, model, lineNumber) {
        var collapsibleRegion = null;
        for (var i = 0, len = allRegions.length; i < len; i++) {
            var dec = allRegions[i];
            var decRange = dec.getDecorationRange(model);
            if (decRange) {
                if (doesLineBelongsToCollapsibleRegion(decRange, lineNumber)) {
                    collapsibleRegion = dec;
                }
                if (doesCollapsibleRegionIsAfterLine(decRange, lineNumber)) {
                    break;
                }
            }
        }
        return collapsibleRegion;
    }
    function getFoldedCollapsibleRegionAfterLine(allRegions, model, surroundingRegion, lineNumber) {
        var index = allRegions.indexOf(surroundingRegion);
        for (var i = index + 1; i < allRegions.length; i++) {
            var dec = allRegions[i];
            var decRange = dec.getDecorationRange(model);
            if (decRange) {
                if (doesCollapsibleRegionIsAfterLine(decRange, lineNumber)) {
                    if (!doesCollapsibleRegionContains(surroundingRegion.foldingRange, decRange)) {
                        return null;
                    }
                    if (dec.isCollapsed) {
                        return dec;
                    }
                }
            }
        }
        return null;
    }
    function doesLineBelongsToCollapsibleRegion(range, lineNumber) {
        return lineNumber >= range.startLineNumber && lineNumber <= range.endLineNumber;
    }
    exports.doesLineBelongsToCollapsibleRegion = doesLineBelongsToCollapsibleRegion;
    function doesCollapsibleRegionIsAfterLine(range, lineNumber) {
        return lineNumber < range.startLineNumber;
    }
    function doesCollapsibleRegionIsBeforeLine(range, lineNumber) {
        return lineNumber > range.endLineNumber;
    }
    function doesCollapsibleRegionContains(range1, range2) {
        if (range1 instanceof range_1.Range && range2 instanceof range_1.Range) {
            return range1.containsRange(range2);
        }
        return range1.startLineNumber <= range2.startLineNumber && range1.endLineNumber >= range2.endLineNumber;
    }
    function getCollapsibleRegionsFor(surroundingRegion, allRegions, model, levels, up) {
        var collapsibleRegionsHierarchy = up ? new CollapsibleRegionsParentHierarchy(surroundingRegion, allRegions, model) : new CollapsibleRegionsChildrenHierarchy(surroundingRegion, allRegions, model);
        return collapsibleRegionsHierarchy.getRegionsTill(levels);
    }
    var CollapsibleRegionsChildrenHierarchy = (function () {
        function CollapsibleRegionsChildrenHierarchy(region, allRegions, model) {
            this.region = region;
            this.children = [];
            for (var index = allRegions.indexOf(region) + 1; index < allRegions.length; index++) {
                var dec = allRegions[index];
                var decRange = dec.getDecorationRange(model);
                if (decRange) {
                    if (doesCollapsibleRegionContains(region.foldingRange, decRange)) {
                        index = this.processChildRegion(dec, allRegions, model, index);
                    }
                    if (doesCollapsibleRegionIsAfterLine(decRange, region.foldingRange.endLineNumber)) {
                        break;
                    }
                }
            }
        }
        CollapsibleRegionsChildrenHierarchy.prototype.processChildRegion = function (dec, allRegions, model, index) {
            var childRegion = new CollapsibleRegionsChildrenHierarchy(dec, allRegions, model);
            this.children.push(childRegion);
            this.lastChildIndex = index;
            return childRegion.children.length > 0 ? childRegion.lastChildIndex : index;
        };
        CollapsibleRegionsChildrenHierarchy.prototype.getRegionsTill = function (level) {
            var result = [this.region];
            if (level > 1) {
                this.children.forEach(function (region) { return result = result.concat(region.getRegionsTill(level - 1)); });
            }
            return result;
        };
        return CollapsibleRegionsChildrenHierarchy;
    }());
    var CollapsibleRegionsParentHierarchy = (function () {
        function CollapsibleRegionsParentHierarchy(region, allRegions, model) {
            this.region = region;
            for (var index = allRegions.indexOf(region) - 1; index >= 0; index--) {
                var dec = allRegions[index];
                var decRange = dec.getDecorationRange(model);
                if (decRange) {
                    if (doesCollapsibleRegionContains(decRange, region.foldingRange)) {
                        this.parent = new CollapsibleRegionsParentHierarchy(dec, allRegions, model);
                        break;
                    }
                    if (doesCollapsibleRegionIsBeforeLine(decRange, region.foldingRange.endLineNumber)) {
                        break;
                    }
                }
            }
        }
        CollapsibleRegionsParentHierarchy.prototype.getRegionsTill = function (level) {
            var result = [this.region];
            if (this.parent && level > 1) {
                result = result.concat(this.parent.getRegionsTill(level - 1));
            }
            return result;
        };
        return CollapsibleRegionsParentHierarchy;
    }());
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[334/*vs/editor/contrib/snippet/browser/snippetSession*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,20/*vs/editor/common/editorCommon*/,59/*vs/editor/common/core/editOperation*/,142/*vs/editor/contrib/snippet/browser/snippetParser*/,22/*vs/editor/common/core/selection*/,2/*vs/editor/common/core/range*/,33/*vs/base/common/arrays*/,3/*vs/base/common/lifecycle*/,271/*vs/editor/contrib/snippet/browser/snippetVariables*/,34/*vs/editor/common/model/textModelWithDecorations*/,394/*vs/css!vs/editor/contrib/snippet/browser/snippetSession*/]), function (require, exports, strings_1, editorCommon_1, editOperation_1, snippetParser_1, selection_1, range_1, arrays_1, lifecycle_1, snippetVariables_1, textModelWithDecorations_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var OneSnippet = (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 () {
            var _this = this;
            if (this._placeholderDecorations) {
                this._editor.changeDecorations(function (accessor) { return _this._placeholderDecorations.forEach(function (handle) { return accessor.removeDecoration(handle); }); });
            }
            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;
            this._initDecorations();
            if (fwd === true && this._placeholderGroupsIdx < this._placeholderGroups.length - 1) {
                this._placeholderGroupsIdx += 1;
            }
            else if (fwd === false && this._placeholderGroupsIdx > 0) {
                this._placeholderGroupsIdx -= 1;
            }
            else {
                // the selection of the current placeholder might
                // not acurate any more -> simply restore it
            }
            return 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));
                    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;
            });
        };
        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
        });
        Object.defineProperty(OneSnippet.prototype, "placeholderRanges", {
            get: function () {
                var _this = this;
                var ret = [];
                this._placeholderDecorations.forEach(function (id, placeholder) {
                    if (!placeholder.isFinalTabstop) {
                        var range = _this._editor.getModel().getDecorationRange(id);
                        if (range) {
                            ret.push(range);
                        }
                    }
                });
                return ret;
            },
            enumerable: true,
            configurable: true
        });
        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
                    for (var _b = 0, _c = nested._snippet.placeholders; _b < _c.length; _b++) {
                        var nestedPlaceholder = _c[_b];
                        if (nestedPlaceholder.isFinalTabstop) {
                            nestedPlaceholder.index = placeholder.index + (nested._snippet.placeholders.length / _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: textModelWithDecorations_1.ModelDecorationOptions.register({ stickiness: editorCommon_1.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges, className: 'snippet-placeholder' }),
            inactive: textModelWithDecorations_1.ModelDecorationOptions.register({ stickiness: editorCommon_1.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, className: 'snippet-placeholder' }),
            activeFinal: textModelWithDecorations_1.ModelDecorationOptions.register({ stickiness: editorCommon_1.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, className: 'finish-snippet-placeholder' }),
            inactiveFinal: textModelWithDecorations_1.ModelDecorationOptions.register({ stickiness: editorCommon_1.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, className: 'finish-snippet-placeholder' }),
        };
        return OneSnippet;
    }());
    exports.OneSnippet = OneSnippet;
    var SnippetSession = (function () {
        function SnippetSession(editor, template, overwriteBefore, overwriteAfter) {
            if (overwriteBefore === void 0) { overwriteBefore = 0; }
            if (overwriteAfter === void 0) { overwriteAfter = 0; }
            this._snippets = [];
            this._editor = editor;
            this._template = template;
            this._overwriteBefore = overwriteBefore;
            this._overwriteAfter = overwriteAfter;
        }
        SnippetSession.adjustWhitespace = function (model, position, template) {
            var line = model.getLineContent(position.lineNumber);
            var lineLeadingWhitespace = strings_1.getLeadingWhitespace(line, 0, position.column - 1);
            var templateLines = template.split(/\r\n|\r|\n/);
            for (var i = 1; i < templateLines.length; i++) {
                var templateLeadingWhitespace = strings_1.getLeadingWhitespace(templateLines[i]);
                templateLines[i] = model.normalizeIndentation(lineLeadingWhitespace + templateLeadingWhitespace) + templateLines[i].substr(templateLeadingWhitespace.length);
            }
            return templateLines.join(model.getEOL());
        };
        SnippetSession.adjustSelection = function (model, selection, overwriteBefore, overwriteAfter) {
            if (overwriteBefore !== 0 || overwriteAfter !== 0) {
                var startLineNumber = selection.startLineNumber, startColumn = selection.startColumn, endLineNumber = selection.endLineNumber, endColumn = selection.endColumn;
                startColumn -= overwriteBefore;
                endColumn += overwriteAfter;
                var range = model.validateRange(range_1.Range.plusRange(selection, {
                    startLineNumber: startLineNumber,
                    startColumn: startColumn,
                    endLineNumber: endLineNumber,
                    endColumn: endColumn,
                }));
                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) {
            var model = editor.getModel();
            var edits = [];
            var snippets = [];
            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));
            // 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 indexedSelection = 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, indexedSelection_1 = indexedSelection; _i < indexedSelection_1.length; _i++) {
                var _a = indexedSelection_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);
                // adjust the template string to match the indentation and
                // whitespace rules of this insert location (can be different for each cursor)
                var start = snippetSelection.getStartPosition();
                var adjustedTemplate = SnippetSession.adjustWhitespace(model, start, template);
                var snippet = new snippetParser_1.SnippetParser()
                    .parse(adjustedTemplate, true, enforceFinalTabstop)
                    .resolveVariables(new snippetVariables_1.EditorSnippetVariableResolver(model, selection));
                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.insert = function () {
            var _this = this;
            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), edits = _a.edits, snippets = _a.snippets;
            this._snippets = snippets;
            this._editor.setSelections(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()); });
                }
            }));
        };
        SnippetSession.prototype.merge = function (template, overwriteBefore, overwriteAfter) {
            var _this = this;
            if (overwriteBefore === void 0) { overwriteBefore = 0; }
            if (overwriteAfter === void 0) { overwriteAfter = 0; }
            var _a = SnippetSession.createEditsAndSnippets(this._editor, template, overwriteBefore, overwriteAfter, true), 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);
        };
        SnippetSession.prototype.prev = function () {
            var newSelections = this._move(false);
            this._editor.setSelections(newSelections);
        };
        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 ranges = [];
            for (var _i = 0, _a = this._snippets; _i < _a.length; _i++) {
                var snippet = _a[_i];
                ranges.push.apply(ranges, snippet.placeholderRanges);
            }
            if (selections.length > ranges.length) {
                return false;
            }
            // sort selections and ranges by their start position
            // and then make sure each selection is contained by
            // a placeholder range
            selections.sort(range_1.Range.compareRangesUsingStarts);
            ranges.sort(range_1.Range.compareRangesUsingStarts);
            outer: for (var _b = 0, selections_1 = selections; _b < selections_1.length; _b++) {
                var selection = selections_1[_b];
                var range = void 0;
                while (range = ranges.shift()) {
                    if (range.containsRange(selection)) {
                        continue outer;
                    }
                }
                return false;
            }
            return true;
        };
        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[183/*vs/editor/contrib/zoneWidget/browser/zoneWidget*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,41/*vs/base/browser/ui/widget*/,26/*vs/base/common/objects*/,4/*vs/base/browser/dom*/,99/*vs/base/browser/ui/sash/sash*/,2/*vs/editor/common/core/range*/,32/*vs/base/common/color*/,34/*vs/editor/common/model/textModelWithDecorations*/,108/*vs/base/common/idGenerator*/,399/*vs/css!vs/editor/contrib/zoneWidget/browser/zoneWidget*/]), function (require, exports, lifecycle_1, widget_1, objects, dom, sash_1, range_1, color_1, textModelWithDecorations_1, idGenerator_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var defaultColor = color_1.Color.fromRGBA(new color_1.RGBA(0, 122, 204));
    var defaultOptions = {
        showArrow: true,
        showFrame: true,
        className: '',
        frameColor: defaultColor,
        arrowColor: defaultColor
    };
    var WIDGET_ID = 'vs.editor.contrib.zoneWidget';
    var ViewZoneDelegate = (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 = (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 = (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 } }]);
        };
        Arrow.prototype.hide = function () {
            this._editor.deltaDecorations(this._decorations, []);
        };
        Arrow._IdGenerator = new idGenerator_1.IdGenerator('.arrow-decoration-');
        return Arrow;
    }());
    var ZoneWidget = (function (_super) {
        __extends(ZoneWidget, _super);
        function ZoneWidget(editor, options) {
            if (options === void 0) { options = {}; }
            var _this = _super.call(this) || this;
            _this._positionMarkerId = [];
            _this._disposables = [];
            _this._isShowing = false;
            _this.editor = editor;
            _this.options = objects.clone(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._onWidth(width);
            }));
            return _this;
        }
        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) {
                    accessor.removeZone(_this._viewZone.id);
                    _this._viewZone = null;
                });
            }
            this.editor.deltaDecorations(this._positionMarkerId, []);
        };
        ZoneWidget.prototype.create = function () {
            dom.addClass(this.domNode, 'zone-widget');
            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) {
                var frameColor = this.options.frameColor.toString();
                this.container.style.borderTopColor = frameColor;
                this.container.style.borderBottomColor = frameColor;
            }
            if (this._arrow) {
                var arrowColor = this.options.arrowColor.toString();
                this._arrow.color = arrowColor;
            }
        };
        ZoneWidget.prototype._getWidth = function (info) {
            if (info === void 0) { info = this.editor.getLayoutInfo(); }
            return info.width - info.minimapWidth - info.verticalScrollbarWidth;
        };
        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";
            this._doLayout(containerHeight, this._getWidth());
            this._resizeSash.layout();
        };
        Object.defineProperty(ZoneWidget.prototype, "position", {
            get: function () {
                var id = this._positionMarkerId[0];
                if (id) {
                    return this.editor.getModel().getDecorationRange(id).getStartPosition();
                }
                return undefined;
            },
            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: textModelWithDecorations_1.ModelDecorationOptions.EMPTY }]);
        };
        ZoneWidget.prototype.hide = function () {
            var _this = this;
            if (this._viewZone) {
                this.editor.changeViewZones(function (accessor) {
                    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 width = this._getWidth();
            this.domNode.style.width = width + "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) * .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);
            this.editor.setSelection(where);
            // Reveal the line above or below the zone widget, to get the zone widget in the viewport
            var revealLineNumber = Math.min(this.editor.getModel().getLineCount(), Math.max(1, where.endLineNumber + 1));
            this.editor.revealLine(revealLineNumber);
        };
        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.heightInLines !== newHeightInLines) {
                this.editor.changeViewZones(function (accessor) {
                    _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: sash_1.Orientation.HORIZONTAL });
            if (!this.options.isResizeable) {
                this._resizeSash.hide();
                this._resizeSash.disable();
            }
            var data;
            this._disposables.push(this._resizeSash.addListener('start', function (e) {
                if (_this._viewZone) {
                    data = {
                        startY: e.startY,
                        heightInLines: _this._viewZone.heightInLines,
                    };
                }
            }));
            this._disposables.push(this._resizeSash.addListener('end', function () {
                data = undefined;
            }));
            this._disposables.push(this._resizeSash.addListener('change', 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 parseInt(this.domNode.style.height) - (this._decoratingElementsHeight() / 2);
        };
        ZoneWidget.prototype.getHorizontalSashWidth = function () {
            var layoutInfo = this.editor.getLayoutInfo();
            return layoutInfo.width - layoutInfo.minimapWidth;
        };
        return ZoneWidget;
    }(widget_1.Widget));
    exports.ZoneWidget = ZoneWidget;
});

define(__m[336/*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[337/*vs/nls!vs/editor/common/services/bulkEdit*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/services/bulkEdit", data); });










define(__m[338/*vs/editor/common/services/bulkEdit*/], __M([1/*require*/,0/*exports*/,337/*vs/nls!vs/editor/common/services/bulkEdit*/,33/*vs/base/common/arrays*/,157/*vs/base/common/collections*/,3/*vs/base/common/lifecycle*/,24/*vs/base/common/uri*/,7/*vs/base/common/winjs.base*/,59/*vs/editor/common/core/editOperation*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/]), function (require, exports, nls, arrays_1, collections_1, lifecycle_1, uri_1, winjs_base_1, editOperation_1, range_1, selection_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ChangeRecorder = (function () {
        function ChangeRecorder(fileService) {
            this._fileService = fileService;
        }
        ChangeRecorder.prototype.start = function () {
            var changes = Object.create(null);
            var stop;
            if (this._fileService) {
                stop = this._fileService.onFileChanges(function (event) {
                    event.changes.forEach(function (change) {
                        var key = String(change.resource);
                        var array = changes[key];
                        if (!array) {
                            changes[key] = array = [];
                        }
                        array.push(change);
                    });
                });
            }
            return {
                stop: function () { return stop && stop.dispose(); },
                hasChanged: function (resource) { return !!changes[resource.toString()]; },
                allChanges: function () { return arrays_1.flatten(collections_1.values(changes)); }
            };
        };
        return ChangeRecorder;
    }());
    var EditTask = (function () {
        function EditTask(modelReference) {
            this._endCursorSelection = null;
            this._modelReference = modelReference;
            this._edits = [];
        }
        Object.defineProperty(EditTask.prototype, "_model", {
            get: function () { return this._modelReference.object.textEditorModel; },
            enumerable: true,
            configurable: true
        });
        EditTask.prototype.addEdit = function (edit) {
            if (typeof edit.newEol === 'number') {
                // honor eol-change
                this._newEol = edit.newEol;
            }
            if (edit.range || edit.newText) {
                // create edit operation
                var range = void 0;
                if (!edit.range) {
                    range = this._model.getFullModelRange();
                }
                else {
                    range = range_1.Range.lift(edit.range);
                }
                this._edits.push(editOperation_1.EditOperation.replaceMove(range, edit.newText));
            }
        };
        EditTask.prototype.apply = function () {
            var _this = this;
            if (this._edits.length > 0) {
                this._edits = this._edits.map(function (value, index) { return ({ value: value, index: index }); }).sort(function (a, b) {
                    var ret = range_1.Range.compareRangesUsingStarts(a.value.range, b.value.range);
                    if (ret === 0) {
                        ret = a.index - b.index;
                    }
                    return ret;
                }).map(function (element) { return element.value; });
                this._initialSelections = this._getInitialSelections();
                this._model.pushEditOperations(this._initialSelections, this._edits, function (edits) { return _this._getEndCursorSelections(edits); });
            }
            if (this._newEol !== undefined) {
                this._model.setEOL(this._newEol);
            }
        };
        EditTask.prototype._getInitialSelections = function () {
            var firstRange = this._edits[0].range;
            var initialSelection = new selection_1.Selection(firstRange.startLineNumber, firstRange.startColumn, firstRange.endLineNumber, firstRange.endColumn);
            return [initialSelection];
        };
        EditTask.prototype._getEndCursorSelections = function (inverseEditOperations) {
            var relevantEditIndex = 0;
            for (var i = 0; i < inverseEditOperations.length; i++) {
                var editRange = inverseEditOperations[i].range;
                for (var j = 0; j < this._initialSelections.length; j++) {
                    var selectionRange = this._initialSelections[j];
                    if (range_1.Range.areIntersectingOrTouching(editRange, selectionRange)) {
                        relevantEditIndex = i;
                        break;
                    }
                }
            }
            var srcRange = inverseEditOperations[relevantEditIndex].range;
            this._endCursorSelection = new selection_1.Selection(srcRange.endLineNumber, srcRange.endColumn, srcRange.endLineNumber, srcRange.endColumn);
            return [this._endCursorSelection];
        };
        EditTask.prototype.getEndCursorSelection = function () {
            return this._endCursorSelection;
        };
        EditTask.prototype.dispose = function () {
            if (this._model) {
                this._modelReference.dispose();
                this._modelReference = null;
            }
        };
        return EditTask;
    }());
    var SourceModelEditTask = (function (_super) {
        __extends(SourceModelEditTask, _super);
        function SourceModelEditTask(modelReference, initialSelections) {
            var _this = _super.call(this, modelReference) || this;
            _this._knownInitialSelections = initialSelections;
            return _this;
        }
        SourceModelEditTask.prototype._getInitialSelections = function () {
            return this._knownInitialSelections;
        };
        return SourceModelEditTask;
    }(EditTask));
    var BulkEditModel = (function () {
        function BulkEditModel(textModelResolverService, sourceModel, sourceSelections, edits, progress) {
            if (progress === void 0) { progress = null; }
            this.progress = progress;
            this._numberOfResourcesToModify = 0;
            this._numberOfChanges = 0;
            this._edits = Object.create(null);
            this._textModelResolverService = textModelResolverService;
            this._sourceModel = sourceModel;
            this._sourceSelections = sourceSelections;
            this._sourceModelTask = null;
            for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
                var edit = edits_1[_i];
                this._addEdit(edit);
            }
        }
        BulkEditModel.prototype.resourcesCount = function () {
            return this._numberOfResourcesToModify;
        };
        BulkEditModel.prototype.changeCount = function () {
            return this._numberOfChanges;
        };
        BulkEditModel.prototype._addEdit = function (edit) {
            var array = this._edits[edit.resource.toString()];
            if (!array) {
                this._edits[edit.resource.toString()] = array = [];
                this._numberOfResourcesToModify += 1;
            }
            this._numberOfChanges += 1;
            array.push(edit);
        };
        BulkEditModel.prototype.prepare = function () {
            var _this = this;
            if (this._tasks) {
                throw new Error('illegal state - already prepared');
            }
            this._tasks = [];
            var promises = [];
            if (this.progress) {
                this.progress.total(this._numberOfResourcesToModify * 2);
            }
            collections_1.forEach(this._edits, function (entry) {
                var promise = _this._textModelResolverService.createModelReference(uri_1.default.parse(entry.key)).then(function (ref) {
                    var model = ref.object;
                    if (!model || !model.textEditorModel) {
                        throw new Error("Cannot load file " + entry.key);
                    }
                    var textEditorModel = model.textEditorModel;
                    var task;
                    if (_this._sourceModel && textEditorModel.uri.toString() === _this._sourceModel.toString()) {
                        _this._sourceModelTask = new SourceModelEditTask(ref, _this._sourceSelections);
                        task = _this._sourceModelTask;
                    }
                    else {
                        task = new EditTask(ref);
                    }
                    entry.value.forEach(function (edit) { return task.addEdit(edit); });
                    _this._tasks.push(task);
                    if (_this.progress) {
                        _this.progress.worked(1);
                    }
                });
                promises.push(promise);
            });
            return winjs_base_1.TPromise.join(promises).then(function (_) { return _this; });
        };
        BulkEditModel.prototype.apply = function () {
            var _this = this;
            this._tasks.forEach(function (task) { return _this.applyTask(task); });
            var r = null;
            if (this._sourceModelTask) {
                r = this._sourceModelTask.getEndCursorSelection();
            }
            return r;
        };
        BulkEditModel.prototype.applyTask = function (task) {
            task.apply();
            if (this.progress) {
                this.progress.worked(1);
            }
        };
        BulkEditModel.prototype.dispose = function () {
            this._tasks = lifecycle_1.dispose(this._tasks);
        };
        return BulkEditModel;
    }());
    function bulkEdit(textModelResolverService, editor, edits, fileService, progress) {
        if (progress === void 0) { progress = null; }
        var bulk = createBulkEdit(textModelResolverService, editor, fileService);
        bulk.add(edits);
        bulk.progress(progress);
        return bulk.finish();
    }
    exports.bulkEdit = bulkEdit;
    function createBulkEdit(textModelResolverService, editor, fileService) {
        var all = [];
        var recording = new ChangeRecorder(fileService).start();
        var progressRunner;
        function progress(progress) {
            progressRunner = progress;
        }
        function add(edits) {
            all.push.apply(all, edits);
        }
        function getConcurrentEdits() {
            var names;
            for (var _i = 0, all_1 = all; _i < all_1.length; _i++) {
                var edit = all_1[_i];
                if (recording.hasChanged(edit.resource)) {
                    if (!names) {
                        names = [];
                    }
                    names.push(edit.resource.fsPath);
                }
            }
            if (names) {
                return nls.localize(0, null, names.join(', '));
            }
            return undefined;
        }
        function finish() {
            if (all.length === 0) {
                return winjs_base_1.TPromise.as(undefined);
            }
            var concurrentEdits = getConcurrentEdits();
            if (concurrentEdits) {
                return winjs_base_1.TPromise.wrapError(new Error(concurrentEdits));
            }
            var uri;
            var selections;
            if (editor && editor.getModel()) {
                uri = editor.getModel().uri;
                selections = editor.getSelections();
            }
            var model = new BulkEditModel(textModelResolverService, uri, selections, all, progressRunner);
            return model.prepare().then(function (_) {
                var concurrentEdits = getConcurrentEdits();
                if (concurrentEdits) {
                    throw new Error(concurrentEdits);
                }
                recording.stop();
                var result = model.apply();
                model.dispose();
                return result;
            });
        }
        function ariaMessage() {
            var editCount = all.length;
            var resourceCount = collections_1.size(collections_1.groupBy(all, function (edit) { return edit.resource.toString(); }));
            if (editCount === 0) {
                return nls.localize(1, null);
            }
            else if (editCount > 1 && resourceCount > 1) {
                return nls.localize(2, null, editCount, resourceCount);
            }
            else {
                return nls.localize(3, null, editCount, resourceCount);
            }
        }
        return {
            progress: progress,
            add: add,
            finish: finish,
            ariaMessage: ariaMessage
        };
    }
    exports.createBulkEdit = createBulkEdit;
});

define(__m[339/*vs/nls!vs/editor/common/services/modelServiceImpl*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/services/modelServiceImpl", data); });
define(__m[340/*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[341/*vs/nls!vs/editor/contrib/bracketMatching/common/bracketMatching*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/bracketMatching/common/bracketMatching", data); });
define(__m[342/*vs/nls!vs/editor/contrib/caretOperations/common/caretOperations*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/common/caretOperations", data); });
define(__m[343/*vs/nls!vs/editor/contrib/caretOperations/common/transpose*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/common/transpose", data); });
define(__m[344/*vs/nls!vs/editor/contrib/clipboard/browser/clipboard*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/clipboard/browser/clipboard", data); });
define(__m[345/*vs/nls!vs/editor/contrib/comment/common/comment*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/comment/common/comment", data); });
define(__m[346/*vs/nls!vs/editor/contrib/contextmenu/browser/contextmenu*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/contextmenu/browser/contextmenu", data); });
define(__m[347/*vs/nls!vs/editor/contrib/find/browser/findWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/browser/findWidget", data); });
define(__m[348/*vs/nls!vs/editor/contrib/find/common/findController*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/common/findController", data); });
define(__m[349/*vs/nls!vs/editor/contrib/folding/browser/folding*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/folding/browser/folding", data); });
define(__m[350/*vs/nls!vs/editor/contrib/format/browser/formatActions*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/browser/formatActions", data); });
define(__m[351/*vs/nls!vs/editor/contrib/goToDeclaration/browser/goToDeclarationCommands*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/goToDeclaration/browser/goToDeclarationCommands", data); });
define(__m[352/*vs/nls!vs/editor/contrib/goToDeclaration/browser/goToDeclarationMouse*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/goToDeclaration/browser/goToDeclarationMouse", data); });
define(__m[353/*vs/nls!vs/editor/contrib/gotoError/browser/gotoError*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/browser/gotoError", data); });
define(__m[354/*vs/nls!vs/editor/contrib/hover/browser/hover*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/browser/hover", data); });
define(__m[355/*vs/nls!vs/editor/contrib/hover/browser/modesContentHover*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/browser/modesContentHover", data); });
define(__m[356/*vs/nls!vs/editor/contrib/inPlaceReplace/common/inPlaceReplace*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inPlaceReplace/common/inPlaceReplace", data); });
define(__m[357/*vs/nls!vs/editor/contrib/linesOperations/common/linesOperations*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/linesOperations/common/linesOperations", data); });
define(__m[358/*vs/nls!vs/editor/contrib/links/browser/links*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/links/browser/links", data); });
define(__m[359/*vs/nls!vs/editor/contrib/multicursor/common/multicursor*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/multicursor/common/multicursor", data); });
define(__m[360/*vs/nls!vs/editor/contrib/parameterHints/browser/parameterHints*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/browser/parameterHints", data); });
define(__m[361/*vs/nls!vs/editor/contrib/parameterHints/browser/parameterHintsWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/browser/parameterHintsWidget", data); });
define(__m[362/*vs/nls!vs/editor/contrib/quickFix/browser/quickFixCommands*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/quickFix/browser/quickFixCommands", data); });
define(__m[363/*vs/nls!vs/editor/contrib/referenceSearch/browser/referenceSearch*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/referenceSearch/browser/referenceSearch", data); });
define(__m[364/*vs/nls!vs/editor/contrib/referenceSearch/browser/referencesController*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/referenceSearch/browser/referencesController", data); });
define(__m[365/*vs/nls!vs/editor/contrib/referenceSearch/browser/referencesModel*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/referenceSearch/browser/referencesModel", data); });
define(__m[125/*vs/editor/contrib/referenceSearch/browser/referencesModel*/], __M([1/*require*/,0/*exports*/,365/*vs/nls!vs/editor/contrib/referenceSearch/browser/referencesModel*/,38/*vs/base/common/eventEmitter*/,11/*vs/base/common/event*/,45/*vs/base/common/paths*/,3/*vs/base/common/lifecycle*/,9/*vs/base/common/strings*/,108/*vs/base/common/idGenerator*/,7/*vs/base/common/winjs.base*/,2/*vs/editor/common/core/range*/]), function (require, exports, nls_1, eventEmitter_1, event_1, paths_1, lifecycle_1, strings, idGenerator_1, winjs_base_1, range_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var OneReference = (function () {
        function OneReference(_parent, _range, _eventBus) {
            this._parent = _parent;
            this._range = _range;
            this._eventBus = _eventBus;
            this._id = idGenerator_1.defaultGenerator.nextId();
        }
        Object.defineProperty(OneReference.prototype, "id", {
            get: function () {
                return this._id;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OneReference.prototype, "model", {
            get: function () {
                return this._parent;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OneReference.prototype, "parent", {
            get: function () {
                return this._parent;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OneReference.prototype, "uri", {
            get: function () {
                return this._parent.uri;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OneReference.prototype, "name", {
            get: function () {
                return this._parent.name;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OneReference.prototype, "directory", {
            get: function () {
                return this._parent.directory;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OneReference.prototype, "range", {
            get: function () {
                return this._range;
            },
            set: function (value) {
                this._range = value;
                this._eventBus.emit('ref/changed', this);
            },
            enumerable: true,
            configurable: true
        });
        OneReference.prototype.getAriaMessage = function () {
            return nls_1.localize(0, null, paths_1.basename(this.uri.fsPath), this.range.startLineNumber, this.range.startColumn);
        };
        return OneReference;
    }());
    exports.OneReference = OneReference;
    var FilePreview = (function () {
        function FilePreview(_modelReference) {
            this._modelReference = _modelReference;
        }
        Object.defineProperty(FilePreview.prototype, "_model", {
            get: function () { return this._modelReference.object.textEditorModel; },
            enumerable: true,
            configurable: true
        });
        FilePreview.prototype.preview = function (range, n) {
            if (n === void 0) { n = 8; }
            var model = this._model;
            if (!model) {
                return undefined;
            }
            var startLineNumber = range.startLineNumber, startColumn = range.startColumn, 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(startLineNumber, endColumn, startLineNumber, 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;
        };
        FilePreview.prototype.dispose = function () {
            if (this._modelReference) {
                this._modelReference.dispose();
                this._modelReference = null;
            }
        };
        return FilePreview;
    }());
    exports.FilePreview = FilePreview;
    var FileReferences = (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, "name", {
            get: function () {
                return paths_1.basename(this.uri.fsPath);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FileReferences.prototype, "directory", {
            get: function () {
                return paths_1.dirname(this.uri.fsPath);
            },
            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, paths_1.basename(this.uri.fsPath), this.uri.fsPath);
            }
            else {
                return nls_1.localize(2, null, len, paths_1.basename(this.uri.fsPath), this.uri.fsPath);
            }
        };
        FileReferences.prototype.resolve = function (textModelResolverService) {
            var _this = this;
            if (this._resolved) {
                return winjs_base_1.TPromise.as(this);
            }
            return 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 = null;
            }
        };
        return FileReferences;
    }());
    exports.FileReferences = FileReferences;
    var ReferencesModel = (function () {
        function ReferencesModel(references) {
            this._groups = [];
            this._references = [];
            this._eventBus = new eventEmitter_1.EventEmitter();
            this.onDidChangeReferenceRange = event_1.fromEventEmitter(this._eventBus, 'ref/changed');
            // grouping and sorting
            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.range, this._eventBus);
                    this._references.push(oneRef);
                    current.children.push(oneRef);
                }
            }
        }
        Object.defineProperty(ReferencesModel.prototype, "empty", {
            get: function () {
                return this._groups.length === 0;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ReferencesModel.prototype, "references", {
            get: function () {
                return this._references;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ReferencesModel.prototype, "groups", {
            get: function () {
                return this._groups;
            },
            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.nextReference = function (reference) {
            var idx = reference.parent.children.indexOf(reference), len = reference.parent.children.length, totalLength = reference.parent.parent.groups.length;
            if (idx + 1 < len || totalLength === 1) {
                return reference.parent.children[(idx + 1) % len];
            }
            idx = reference.parent.parent.groups.indexOf(reference.parent);
            idx = (idx + 1) % totalLength;
            return reference.parent.parent.groups[idx].children[0];
        };
        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.dispose = function () {
            this._groups = lifecycle_1.dispose(this._groups);
        };
        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[367/*vs/nls!vs/editor/contrib/referenceSearch/browser/referencesWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/referenceSearch/browser/referencesWidget", data); });
define(__m[368/*vs/nls!vs/editor/contrib/rename/browser/rename*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/browser/rename", data); });
define(__m[369/*vs/nls!vs/editor/contrib/rename/browser/renameInputField*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/browser/renameInputField", data); });
define(__m[370/*vs/nls!vs/editor/contrib/smartSelect/common/smartSelect*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/smartSelect/common/smartSelect", data); });
define(__m[371/*vs/nls!vs/editor/contrib/suggest/browser/suggestController*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/browser/suggestController", data); });
define(__m[372/*vs/nls!vs/editor/contrib/suggest/browser/suggestWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/browser/suggestWidget", data); });
define(__m[373/*vs/nls!vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode", data); });
define(__m[374/*vs/nls!vs/editor/contrib/wordHighlighter/common/wordHighlighter*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/wordHighlighter/common/wordHighlighter", data); });
define(__m[375/*vs/nls!vs/editor/contrib/zoneWidget/browser/peekViewWidget*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/zoneWidget/browser/peekViewWidget", data); });
define(__m[376/*vs/nls!vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/standalone/browser/inspectTokens/inspectTokens", data); });
define(__m[377/*vs/nls!vs/editor/standalone/browser/quickOpen/gotoLine*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/standalone/browser/quickOpen/gotoLine", data); });
define(__m[378/*vs/nls!vs/editor/standalone/browser/quickOpen/quickCommand*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/standalone/browser/quickOpen/quickCommand", data); });
define(__m[379/*vs/nls!vs/editor/standalone/browser/quickOpen/quickOutline*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/standalone/browser/quickOpen/quickOutline", data); });
define(__m[380/*vs/nls!vs/editor/standalone/browser/standaloneCodeEditor*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/standalone/browser/standaloneCodeEditor", data); });
define(__m[381/*vs/nls!vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast", data); });
define(__m[382/*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[383/*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[384/*vs/nls!vs/platform/message/common/message*/], __M([6/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/message/common/message", data); });
define(__m[385/*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[386/*vs/platform/contextview/browser/contextMenuHandler*/], __M([1/*require*/,0/*exports*/,52/*vs/base/browser/builder*/,3/*vs/base/common/lifecycle*/,47/*vs/base/browser/mouseEvent*/,53/*vs/base/common/actions*/,281/*vs/base/browser/ui/menu/menu*/,79/*vs/base/common/events*/,36/*vs/base/common/severity*/,409/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/]), function (require, exports, builder_1, lifecycle_1, mouseEvent_1, actions_1, menu_1, events_1, severity_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ContextMenuHandler = (function () {
        function ContextMenuHandler(element, contextViewService, telemetryService, messageService) {
            var _this = this;
            this.setContainer(element);
            this.contextViewService = contextViewService;
            this.telemetryService = telemetryService;
            this.messageService = messageService;
            this.actionRunner = new actions_1.ActionRunner();
            this.menuContainerElement = null;
            this.toDispose = [];
            var hideViewOnRun = false;
            this.toDispose.push(this.actionRunner.addListener(events_1.EventType.BEFORE_RUN, function (e) {
                if (_this.telemetryService) {
                    _this.telemetryService.publicLog('workbenchActionExecuted', { id: e.action.id, from: 'contextMenu' });
                }
                hideViewOnRun = !!e.retainActionItem;
                if (!hideViewOnRun) {
                    _this.contextViewService.hideContextView(false);
                }
            }));
            this.toDispose.push(this.actionRunner.addListener(events_1.EventType.RUN, function (e) {
                if (hideViewOnRun) {
                    _this.contextViewService.hideContextView(false);
                }
                hideViewOnRun = false;
                if (e.error && _this.messageService) {
                    _this.messageService.show(severity_1.default.Error, e.error);
                }
            }));
        }
        ContextMenuHandler.prototype.setContainer = function (container) {
            var _this = this;
            if (this.$el) {
                this.$el.off(['click', 'mousedown']);
                this.$el = null;
            }
            if (container) {
                this.$el = builder_1.$(container);
                this.$el.on('mousedown', function (e) { return _this.onMouseDown(e); });
            }
        };
        ContextMenuHandler.prototype.showContextMenu = function (delegate) {
            var _this = this;
            delegate.getActions().done(function (actions) {
                _this.contextViewService.showContextView({
                    getAnchor: function () { return delegate.getAnchor(); },
                    canRelayout: false,
                    render: function (container) {
                        _this.menuContainerElement = container;
                        var className = delegate.getMenuClassName ? delegate.getMenuClassName() : '';
                        if (className) {
                            container.className += ' ' + className;
                        }
                        var menu = new menu_1.Menu(container, actions, {
                            actionItemProvider: delegate.getActionItem,
                            context: delegate.getActionsContext ? delegate.getActionsContext() : null,
                            actionRunner: _this.actionRunner
                        });
                        var listener1 = menu.addListener(events_1.EventType.CANCEL, function (e) {
                            _this.contextViewService.hideContextView(true);
                        });
                        var listener2 = menu.addListener(events_1.EventType.BLUR, function (e) {
                            _this.contextViewService.hideContextView(true);
                        });
                        menu.focus();
                        return lifecycle_1.combinedDisposable([listener1, listener2, menu]);
                    },
                    onHide: function (didCancel) {
                        if (delegate.onHide) {
                            delegate.onHide(didCancel);
                        }
                        _this.menuContainerElement = null;
                    }
                });
            });
        };
        ContextMenuHandler.prototype.onMouseDown = function (e) {
            if (!this.menuContainerElement) {
                return;
            }
            var event = new mouseEvent_1.StandardMouseEvent(e);
            var element = event.target;
            while (element) {
                if (element === this.menuContainerElement) {
                    return;
                }
                element = element.parentElement;
            }
            this.contextViewService.hideContextView();
        };
        ContextMenuHandler.prototype.dispose = function () {
            this.setContainer(null);
        };
        return ContextMenuHandler;
    }());
    exports.ContextMenuHandler = ContextMenuHandler;
});

define(__m[387/*vs/platform/contextview/browser/contextMenuService*/], __M([1/*require*/,0/*exports*/,386/*vs/platform/contextview/browser/contextMenuHandler*/]), function (require, exports, contextMenuHandler_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ContextMenuService = (function () {
        function ContextMenuService(container, telemetryService, messageService, contextViewService) {
            this.contextMenuHandler = new contextMenuHandler_1.ContextMenuHandler(container, contextViewService, telemetryService, messageService);
        }
        ContextMenuService.prototype.dispose = function () {
            this.contextMenuHandler.dispose();
        };
        ContextMenuService.prototype.setContainer = function (container) {
            this.contextMenuHandler.setContainer(container);
        };
        // ContextMenu
        ContextMenuService.prototype.showContextMenu = function (delegate) {
            this.contextMenuHandler.showContextMenu(delegate);
        };
        return ContextMenuService;
    }());
    exports.ContextMenuService = ContextMenuService;
});











define(__m[187/*vs/platform/instantiation/common/descriptors*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/]), function (require, exports, errors_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var AbstractDescriptor = (function () {
        function AbstractDescriptor(_staticArguments) {
            this._staticArguments = _staticArguments;
            // empty
        }
        AbstractDescriptor.prototype.appendStaticArguments = function (more) {
            this._staticArguments.push.apply(this._staticArguments, more);
        };
        AbstractDescriptor.prototype.staticArguments = function (nth) {
            if (isNaN(nth)) {
                return this._staticArguments.slice(0);
            }
            else {
                return this._staticArguments[nth];
            }
        };
        AbstractDescriptor.prototype._validate = function (type) {
            if (!type) {
                throw errors_1.illegalArgument('can not be falsy');
            }
        };
        return AbstractDescriptor;
    }());
    exports.AbstractDescriptor = AbstractDescriptor;
    var SyncDescriptor = (function (_super) {
        __extends(SyncDescriptor, _super);
        function SyncDescriptor(_ctor) {
            var staticArguments = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                staticArguments[_i - 1] = arguments[_i];
            }
            var _this = _super.call(this, staticArguments) || this;
            _this._ctor = _ctor;
            return _this;
        }
        Object.defineProperty(SyncDescriptor.prototype, "ctor", {
            get: function () {
                return this._ctor;
            },
            enumerable: true,
            configurable: true
        });
        SyncDescriptor.prototype.bind = function () {
            var moreStaticArguments = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                moreStaticArguments[_i] = arguments[_i];
            }
            var allArgs = [];
            allArgs = allArgs.concat(this.staticArguments());
            allArgs = allArgs.concat(moreStaticArguments);
            return new (SyncDescriptor.bind.apply(SyncDescriptor, [void 0, this._ctor].concat(allArgs)))();
        };
        return SyncDescriptor;
    }(AbstractDescriptor));
    exports.SyncDescriptor = SyncDescriptor;
    exports.createSyncDescriptor = function (ctor) {
        var staticArguments = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            staticArguments[_i - 1] = arguments[_i];
        }
        return new (SyncDescriptor.bind.apply(SyncDescriptor, [void 0, ctor].concat(staticArguments)))();
    };
    var AsyncDescriptor = (function (_super) {
        __extends(AsyncDescriptor, _super);
        function AsyncDescriptor(_moduleName, _ctorName) {
            var staticArguments = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                staticArguments[_i - 2] = arguments[_i];
            }
            var _this = _super.call(this, staticArguments) || this;
            _this._moduleName = _moduleName;
            _this._ctorName = _ctorName;
            if (typeof _moduleName !== 'string') {
                throw new Error('Invalid AsyncDescriptor arguments, expected `moduleName` to be a string!');
            }
            return _this;
        }
        AsyncDescriptor.create = function (moduleName, ctorName) {
            return new AsyncDescriptor(moduleName, ctorName);
        };
        Object.defineProperty(AsyncDescriptor.prototype, "moduleName", {
            get: function () {
                return this._moduleName;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AsyncDescriptor.prototype, "ctorName", {
            get: function () {
                return this._ctorName;
            },
            enumerable: true,
            configurable: true
        });
        AsyncDescriptor.prototype.bind = function () {
            var moreStaticArguments = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                moreStaticArguments[_i] = arguments[_i];
            }
            var allArgs = [];
            allArgs = allArgs.concat(this.staticArguments());
            allArgs = allArgs.concat(moreStaticArguments);
            return new (AsyncDescriptor.bind.apply(AsyncDescriptor, [void 0, this.moduleName, this.ctorName].concat(allArgs)))();
        };
        return AsyncDescriptor;
    }(AbstractDescriptor));
    exports.AsyncDescriptor = AsyncDescriptor;
});

define(__m[16/*vs/platform/instantiation/common/instantiation*/], __M([1/*require*/,0/*exports*/]), 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 });
    // ------ 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;
});

define(__m[42/*vs/editor/common/services/codeEditorService*/], __M([1/*require*/,0/*exports*/,16/*vs/platform/instantiation/common/instantiation*/,20/*vs/editor/common/editorCommon*/]), function (require, exports, instantiation_1, editorCommon_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ICodeEditorService = instantiation_1.createDecorator('codeEditorService');
    /**
     * Uses `editor.getControl()` and returns either a `codeEditor` or a `diffEditor` or nothing.
     */
    function getCodeOrDiffEditor(editor) {
        if (editor) {
            var control = editor.getControl();
            if (control) {
                if (editorCommon_1.isCommonCodeEditor(control)) {
                    return {
                        codeEditor: control,
                        diffEditor: null
                    };
                }
                if (editorCommon_1.isCommonDiffEditor(control)) {
                    return {
                        codeEditor: null,
                        diffEditor: control
                    };
                }
            }
        }
        return {
            codeEditor: null,
            diffEditor: null
        };
    }
    exports.getCodeOrDiffEditor = getCodeOrDiffEditor;
    /**
     * Uses `editor.getControl()` and returns either the code editor, or the modified editor of a diff editor or nothing.
     */
    function getCodeEditor(editor) {
        var r = getCodeOrDiffEditor(editor);
        return r.codeEditor || (r.diffEditor && r.diffEditor.getModifiedEditor()) || null;
    }
    exports.getCodeEditor = getCodeEditor;
});

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

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

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

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

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

















var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
define(__m[147/*vs/editor/common/services/editorWorkerServiceImpl*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/async*/,3/*vs/base/common/lifecycle*/,7/*vs/base/common/winjs.base*/,197/*vs/base/common/worker/simpleWorker*/,473/*vs/base/worker/defaultWorkerFactory*/,17/*vs/editor/common/modes*/,56/*vs/editor/common/services/modelService*/,226/*vs/editor/common/services/editorSimpleWorker*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/,146/*vs/editor/common/services/resourceConfiguration*/,88/*vs/editor/common/services/modeService*/]), function (require, exports, async_1, lifecycle_1, winjs_base_1, simpleWorker_1, defaultWorkerFactory_1, modes, modelService_1, editorSimpleWorker_1, languageConfigurationRegistry_1, resourceConfiguration_1, modeService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * 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.isTooLargeForTokenization()) {
            return false;
        }
        return true;
    }
    var EditorWorkerServiceImpl = (function (_super) {
        __extends(EditorWorkerServiceImpl, _super);
        function EditorWorkerServiceImpl(modelService, configurationService, modeService) {
            var _this = _super.call(this) || this;
            _this._modelService = modelService;
            _this._workerManager = _this._register(new WorkerManager(_this._modelService));
            // todo@joh make sure this happens only once
            _this._register(modes.LinkProviderRegistry.register('*', {
                provideLinks: function (model, token) {
                    if (!canSyncModel(_this._modelService, model.uri)) {
                        return winjs_base_1.TPromise.as([]); // File too large
                    }
                    return async_1.wireCancellationToken(token, _this._workerManager.withWorker().then(function (client) { return client.computeLinks(model.uri); }));
                }
            }));
            _this._register(modes.SuggestRegistry.register('*', new WordBasedCompletionItemProvider(_this._workerManager, configurationService, modeService, _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.canComputeDirtyDiff = function (original, modified) {
            return (canSyncModel(this._modelService, original) && canSyncModel(this._modelService, modified));
        };
        EditorWorkerServiceImpl.prototype.computeDirtyDiff = function (original, modified, ignoreTrimWhitespace) {
            return this._workerManager.withWorker().then(function (client) { return client.computeDirtyDiff(original, modified, ignoreTrimWhitespace); });
        };
        EditorWorkerServiceImpl.prototype.computeMoreMinimalEdits = function (resource, edits, ranges) {
            if (!Array.isArray(edits) || edits.length === 0) {
                return winjs_base_1.TPromise.as(edits);
            }
            else {
                if (!canSyncModel(this._modelService, resource)) {
                    return winjs_base_1.TPromise.as(edits); // File too large
                }
                return this._workerManager.withWorker().then(function (client) { return client.computeMoreMinimalEdits(resource, edits, ranges); });
            }
        };
        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 = __decorate([
            __param(0, modelService_1.IModelService),
            __param(1, resourceConfiguration_1.ITextResourceConfigurationService),
            __param(2, modeService_1.IModeService)
        ], EditorWorkerServiceImpl);
        return EditorWorkerServiceImpl;
    }(lifecycle_1.Disposable));
    exports.EditorWorkerServiceImpl = EditorWorkerServiceImpl;
    var WordBasedCompletionItemProvider = (function () {
        function WordBasedCompletionItemProvider(workerManager, configurationService, modeService, modelService) {
            this._workerManager = workerManager;
            this._configurationService = configurationService;
            this._modeService = modeService;
            this._modelService = modelService;
        }
        WordBasedCompletionItemProvider.prototype.provideCompletionItems = function (model, position) {
            var wordBasedSuggestions = this._configurationService.getConfiguration(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 = (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 winjs_base_1.TPromise.as(this._editorWorkerClient);
        };
        return WorkerManager;
    }(lifecycle_1.Disposable));
    var EditorModelManager = (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; i < resources.length; i++) {
                var resource = resources[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; i < toRemove.length; i++) {
                this._stopModelSync(toRemove[i]);
            }
        };
        EditorModelManager.prototype._beginModelSync = function (resource) {
            var _this = this;
            var model = this._modelService.getModel(resource);
            if (!model) {
                return;
            }
            if (model.isTooLargeForTokenization()) {
                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({
                dispose: 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 = (function () {
        function SynchronousWorkerClient(instance) {
            this._instance = instance;
            this._proxyObj = winjs_base_1.TPromise.as(this._instance);
        }
        SynchronousWorkerClient.prototype.dispose = function () {
            this._instance.dispose();
            this._instance = null;
            this._proxyObj = null;
        };
        SynchronousWorkerClient.prototype.getProxyObject = function () {
            return new async_1.ShallowCancelThenPromise(this._proxyObj);
        };
        return SynchronousWorkerClient;
    }());
    var EditorWorkerClient = (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());
                }
            }
            return this._worker;
        };
        EditorWorkerClient.prototype._getProxy = function () {
            var _this = this;
            return new async_1.ShallowCancelThenPromise(this._getOrCreateWorker().getProxyObject().then(null, function (err) {
                simpleWorker_1.logOnceWebWorkerWarning(err);
                _this._worker = new SynchronousWorkerClient(new editorSimpleWorker_1.EditorSimpleWorkerImpl());
                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.computeDirtyDiff = function (original, modified, ignoreTrimWhitespace) {
            return this._withSyncedResources([original, modified]).then(function (proxy) {
                return proxy.computeDirtyDiff(original.toString(), modified.toString(), ignoreTrimWhitespace);
            });
        };
        EditorWorkerClient.prototype.computeMoreMinimalEdits = function (resource, edits, ranges) {
            return this._withSyncedResources([resource]).then(function (proxy) {
                return proxy.computeMoreMinimalEdits(resource.toString(), edits, ranges);
            });
        };
        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 = (wordDefRegExp.global ? 'g' : '') + (wordDefRegExp.ignoreCase ? 'i' : '') + (wordDefRegExp.multiline ? 'm' : '');
                return proxy.textualSuggest(resource.toString(), position, 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 = (wordDefRegExp.global ? 'g' : '') + (wordDefRegExp.ignoreCase ? 'i' : '') + (wordDefRegExp.multiline ? 'm' : '');
                return proxy.navigateValueSet(resource.toString(), range, up, wordDef, wordDefFlags);
            });
        };
        return EditorWorkerClient;
    }(lifecycle_1.Disposable));
    exports.EditorWorkerClient = EditorWorkerClient;
});











define(__m[397/*vs/editor/common/services/webWorker*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/async*/,147/*vs/editor/common/services/editorWorkerServiceImpl*/]), function (require, exports, async_1, editorWorkerServiceImpl_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * 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 = (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 = new async_1.ShallowCancelThenPromise(this._getProxy().then(function (proxy) {
                    return proxy.loadForeignModule(_this._foreignModuleId, _this._foreignModuleCreateData).then(function (foreignMethods) {
                        _this._foreignModuleId = null;
                        _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; i < foreignMethods.length; i++) {
                            foreignProxy[foreignMethods[i]] = createProxyMethod(foreignMethods[i], 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));
});










define(__m[398/*vs/editor/contrib/smartSelect/common/tokenSelectionSupport*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,2/*vs/editor/common/core/range*/,56/*vs/editor/common/services/modelService*/,269/*vs/editor/contrib/smartSelect/common/tokenTree*/]), function (require, exports, winjs_base_1, range_1, modelService_1, tokenTree_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var TokenSelectionSupport = (function () {
        function TokenSelectionSupport(modelService) {
            this._modelService = modelService;
        }
        TokenSelectionSupport.prototype.getRangesToPosition = function (resource, position) {
            return winjs_base_1.TPromise.as(this.getRangesToPositionSync(resource, position));
        };
        TokenSelectionSupport.prototype.getRangesToPositionSync = function (resource, position) {
            var model = this._modelService.getModel(resource), entries = [];
            if (model) {
                this._doGetRangesToPosition(model, position).forEach(function (range) {
                    entries.push({
                        type: void 0,
                        range: range
                    });
                });
            }
            return entries;
        };
        TokenSelectionSupport.prototype._doGetRangesToPosition = function (model, position) {
            var tree = tokenTree_1.build(model), node, lastRange;
            node = tokenTree_1.find(tree, position);
            var ranges = [];
            while (node) {
                if (!lastRange || !range_1.Range.equalsRange(lastRange, node.range)) {
                    ranges.push(node.range);
                }
                lastRange = node.range;
                node = node.parent;
            }
            ranges = ranges.reverse();
            return ranges;
        };
        TokenSelectionSupport = __decorate([
            __param(0, modelService_1.IModelService)
        ], TokenSelectionSupport);
        return TokenSelectionSupport;
    }());
    exports.TokenSelectionSupport = TokenSelectionSupport;
});

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

define(__m[31/*vs/platform/commands/common/commands*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,29/*vs/base/common/types*/,16/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, winjs_base_1, types_1, instantiation_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ICommandService = instantiation_1.createDecorator('commandService');
    function isCommand(thing) {
        return typeof thing === 'object'
            && typeof thing.handler === 'function'
            && (!thing.description || typeof thing.description === 'object');
    }
    exports.CommandsRegistry = new (function () {
        function class_1() {
            this._commands = new Map();
        }
        class_1.prototype.registerCommand = function (id, commandOrDesc) {
            var _this = this;
            if (!commandOrDesc) {
                throw new Error("invalid command");
            }
            var command;
            if (!isCommand(commandOrDesc)) {
                // simple handler
                command = { handler: commandOrDesc };
            }
            else {
                var handler_1 = commandOrDesc.handler, description = commandOrDesc.description;
                if (description) {
                    // add argument validation if rich command metadata is provided
                    var constraints_1 = [];
                    for (var _i = 0, _a = description.args; _i < _a.length; _i++) {
                        var arg = _a[_i];
                        constraints_1.push(arg.constraint);
                    }
                    command = {
                        description: description,
                        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 handler_1.apply(void 0, [accessor].concat(args));
                        }
                    };
                }
                else {
                    // add as simple handler
                    command = { handler: handler_1 };
                }
            }
            // find a place to store the command
            var commandOrArray = this._commands.get(id);
            if (commandOrArray === void 0) {
                this._commands.set(id, command);
            }
            else if (Array.isArray(commandOrArray)) {
                commandOrArray.unshift(command);
            }
            else {
                this._commands.set(id, [command, commandOrArray]);
            }
            return {
                dispose: function () {
                    var commandOrArray = _this._commands.get(id);
                    if (Array.isArray(commandOrArray)) {
                        // remove from array, remove array
                        // if last element removed
                        var idx = commandOrArray.indexOf(command);
                        if (idx >= 0) {
                            commandOrArray.splice(idx, 1);
                            if (commandOrArray.length === 0) {
                                _this._commands.delete(id);
                            }
                        }
                    }
                    else if (isCommand(commandOrArray)) {
                        // remove from map
                        _this._commands.delete(id);
                    }
                }
            };
        };
        class_1.prototype.getCommand = function (id) {
            var commandOrArray = this._commands.get(id);
            if (Array.isArray(commandOrArray)) {
                return commandOrArray[0];
            }
            else {
                return commandOrArray;
            }
        };
        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;
    }());
    exports.NullCommandService = {
        _serviceBrand: undefined,
        onWillExecuteCommand: function () { return ({ dispose: function () { } }); },
        executeCommand: function () {
            return winjs_base_1.TPromise.as(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[401/*vs/editor/contrib/links/common/links*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,24/*vs/base/common/uri*/,7/*vs/base/common/winjs.base*/,2/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,18/*vs/base/common/async*/,31/*vs/platform/commands/common/commands*/,56/*vs/editor/common/services/modelService*/]), function (require, exports, errors_1, uri_1, winjs_base_1, range_1, modes_1, async_1, commands_1, modelService_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var Link = (function () {
        function Link(link, provider) {
            this._link = link;
            this._provider = provider;
        }
        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 () {
            var _this = this;
            if (this._link.url) {
                try {
                    return winjs_base_1.TPromise.as(uri_1.default.parse(this._link.url));
                }
                catch (e) {
                    return winjs_base_1.TPromise.wrapError(new Error('invalid'));
                }
            }
            if (typeof this._provider.resolveLink === 'function') {
                return async_1.asWinJsPromise(function (token) { return _this._provider.resolveLink(_this._link, token); }).then(function (value) {
                    _this._link = value || _this._link;
                    if (_this._link.url) {
                        // recurse
                        return _this.resolve();
                    }
                    return winjs_base_1.TPromise.wrapError(new Error('missing'));
                });
            }
            return winjs_base_1.TPromise.wrapError(new Error('missing'));
        };
        return Link;
    }());
    exports.Link = Link;
    function getLinks(model) {
        var links = [];
        // ask all providers for links in parallel
        var promises = modes_1.LinkProviderRegistry.ordered(model).reverse().map(function (provider) {
            return async_1.asWinJsPromise(function (token) { return provider.provideLinks(model, token); }).then(function (result) {
                if (Array.isArray(result)) {
                    var newLinks = result.map(function (link) { return new Link(link, provider); });
                    links = union(links, newLinks);
                }
            }, errors_1.onUnexpectedExternalError);
        });
        return winjs_base_1.TPromise.join(promises).then(function () {
            return links;
        });
    }
    exports.getLinks = getLinks;
    function union(oldLinks, newLinks) {
        // reunite oldLinks with newLinks and remove duplicates
        var result = [], oldIndex, oldLen, newIndex, newLen, oldLink, newLink, comparisonResult;
        for (oldIndex = 0, newIndex = 0, oldLen = oldLinks.length, newLen = newLinks.length; oldIndex < oldLen && newIndex < newLen;) {
            oldLink = oldLinks[oldIndex];
            newLink = newLinks[newIndex];
            if (range_1.Range.areIntersectingOrTouching(oldLink.range, newLink.range)) {
                // Remove the oldLink
                oldIndex++;
                continue;
            }
            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;
    }
    commands_1.CommandsRegistry.registerCommand('_executeLinkProvider', function (accessor) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        var uri = args[0];
        if (!(uri instanceof uri_1.default)) {
            return undefined;
        }
        var model = accessor.get(modelService_1.IModelService).getModel(uri);
        if (!model) {
            return undefined;
        }
        return getLinks(model);
    });
});




















define(__m[85/*vs/platform/actions/common/actions*/], __M([1/*require*/,0/*exports*/,53/*vs/base/common/actions*/,187/*vs/platform/instantiation/common/descriptors*/,16/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/commands/common/commands*/]), function (require, exports, actions_1, descriptors_1, instantiation_1, commands_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MenuId = (function () {
        function MenuId(_id) {
            this._id = _id;
        }
        Object.defineProperty(MenuId.prototype, "id", {
            get: function () {
                return this._id;
            },
            enumerable: true,
            configurable: true
        });
        MenuId.EditorTitle = new MenuId('1');
        MenuId.EditorTitleContext = new MenuId('2');
        MenuId.EditorContext = new MenuId('3');
        MenuId.ExplorerContext = new MenuId('4');
        MenuId.ProblemsPanelContext = new MenuId('5');
        MenuId.DebugVariablesContext = new MenuId('6');
        MenuId.DebugWatchContext = new MenuId('7');
        MenuId.DebugCallStackContext = new MenuId('8');
        MenuId.DebugBreakpointsContext = new MenuId('9');
        MenuId.DebugConsoleContext = new MenuId('10');
        MenuId.SCMTitle = new MenuId('11');
        MenuId.SCMResourceGroupContext = new MenuId('12');
        MenuId.SCMResourceContext = new MenuId('13');
        MenuId.CommandPalette = new MenuId('14');
        MenuId.ViewTitle = new MenuId('15');
        MenuId.ViewItemContext = new MenuId('16');
        return MenuId;
    }());
    exports.MenuId = MenuId;
    exports.IMenuService = instantiation_1.createDecorator('menuService');
    exports.MenuRegistry = new (function () {
        function class_1() {
            this._commands = Object.create(null);
            this._menuItems = Object.create(null);
        }
        class_1.prototype.addCommand = function (command) {
            var old = this._commands[command.id];
            this._commands[command.id] = command;
            return old !== void 0;
        };
        class_1.prototype.getCommand = function (id) {
            return this._commands[id];
        };
        class_1.prototype.appendMenuItem = function (_a, item) {
            var id = _a.id;
            var array = this._menuItems[id];
            if (!array) {
                this._menuItems[id] = array = [item];
            }
            else {
                array.push(item);
            }
            return {
                dispose: function () {
                    var idx = array.indexOf(item);
                    if (idx >= 0) {
                        array.splice(idx, 1);
                    }
                }
            };
        };
        class_1.prototype.getMenuItems = function (_a) {
            var id = _a.id;
            var result = this._menuItems[id] || [];
            if (id === MenuId.CommandPalette.id) {
                // 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();
            for (var _i = 0, result_1 = result; _i < result_1.length; _i++) {
                var _a = result_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 = (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 args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return (_a = this._commandService).executeCommand.apply(_a, [this.id].concat(args));
            var _a;
        };
        ExecuteCommandAction = __decorate([
            __param(2, commands_1.ICommandService)
        ], ExecuteCommandAction);
        return ExecuteCommandAction;
    }(actions_1.Action));
    exports.ExecuteCommandAction = ExecuteCommandAction;
    var MenuItemAction = (function (_super) {
        __extends(MenuItemAction, _super);
        function MenuItemAction(item, alt, options, 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 = item.iconClass;
            _this._enabled = true;
            _this._options = options || {};
            _this.item = item;
            _this.alt = alt ? new MenuItemAction(alt, undefined, _this._options, 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, commands_1.ICommandService)
        ], MenuItemAction);
        return MenuItemAction;
    }(ExecuteCommandAction));
    exports.MenuItemAction = MenuItemAction;
    var SyncActionDescriptor = (function () {
        function SyncActionDescriptor(ctor, id, label, keybindings, keybindingContext, keybindingWeight) {
            this._id = id;
            this._label = label;
            this._keybindings = keybindings;
            this._keybindingContext = keybindingContext;
            this._keybindingWeight = keybindingWeight;
            this._descriptor = descriptors_1.createSyncDescriptor(ctor, this._id, this._label);
        }
        Object.defineProperty(SyncActionDescriptor.prototype, "syncDescriptor", {
            get: function () {
                return this._descriptor;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SyncActionDescriptor.prototype, "id", {
            get: function () {
                return this._id;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SyncActionDescriptor.prototype, "label", {
            get: function () {
                return this._label;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SyncActionDescriptor.prototype, "keybindings", {
            get: function () {
                return this._keybindings;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SyncActionDescriptor.prototype, "keybindingContext", {
            get: function () {
                return this._keybindingContext;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SyncActionDescriptor.prototype, "keybindingWeight", {
            get: function () {
                return this._keybindingWeight;
            },
            enumerable: true,
            configurable: true
        });
        return SyncActionDescriptor;
    }());
    exports.SyncActionDescriptor = SyncActionDescriptor;
});

/*---------------------------------------------------------------------------------------------
 *  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/platform/configuration/common/configuration*/], __M([1/*require*/,0/*exports*/,33/*vs/base/common/arrays*/,29/*vs/base/common/types*/,26/*vs/base/common/objects*/,24/*vs/base/common/uri*/,80/*vs/base/common/map*/,16/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, arrays, types, objects, uri_1, map_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IConfigurationService = instantiation_1.createDecorator('configurationService');
    var ConfigurationSource;
    (function (ConfigurationSource) {
        ConfigurationSource[ConfigurationSource["Default"] = 1] = "Default";
        ConfigurationSource[ConfigurationSource["User"] = 2] = "User";
        ConfigurationSource[ConfigurationSource["Workspace"] = 3] = "Workspace";
    })(ConfigurationSource = exports.ConfigurationSource || (exports.ConfigurationSource = {}));
    /**
     * 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; i < path.length; i++) {
                if (typeof current !== 'object' || current === null) {
                    return undefined;
                }
                current = current[path[i]];
            }
            return current;
        }
        var path = settingPath.split('.');
        var result = accessSetting(config, path);
        return typeof result === 'undefined' ? defaultValue : result;
    }
    exports.getConfigurationValue = getConfigurationValue;
    function merge(base, add, overwrite) {
        Object.keys(add).forEach(function (key) {
            if (key in base) {
                if (types.isObject(base[key]) && types.isObject(add[key])) {
                    merge(base[key], add[key], overwrite);
                }
                else if (overwrite) {
                    base[key] = add[key];
                }
            }
            else {
                base[key] = add[key];
            }
        });
    }
    exports.merge = merge;
    var ConfigurationModel = (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;
        }
        Object.defineProperty(ConfigurationModel.prototype, "contents", {
            get: function () {
                return this._contents;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ConfigurationModel.prototype, "overrides", {
            get: function () {
                return this._overrides;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ConfigurationModel.prototype, "keys", {
            get: function () {
                return this._keys;
            },
            enumerable: true,
            configurable: true
        });
        ConfigurationModel.prototype.getContentsFor = function (section) {
            return objects.clone(this.contents[section]);
        };
        ConfigurationModel.prototype.override = function (identifier) {
            var result = new ConfigurationModel();
            var contents = objects.clone(this.contents);
            if (this._overrides) {
                for (var _i = 0, _a = this._overrides; _i < _a.length; _i++) {
                    var override = _a[_i];
                    if (override.identifiers.indexOf(identifier) !== -1) {
                        merge(contents, override.contents, true);
                    }
                }
            }
            result._contents = contents;
            return result;
        };
        ConfigurationModel.prototype.merge = function (other, overwrite) {
            if (overwrite === void 0) { overwrite = true; }
            var mergedModel = new ConfigurationModel();
            this.doMerge(mergedModel, this, overwrite);
            this.doMerge(mergedModel, other, overwrite);
            return mergedModel;
        };
        ConfigurationModel.prototype.doMerge = function (source, target, overwrite) {
            if (overwrite === void 0) { overwrite = true; }
            merge(source.contents, objects.clone(target.contents), overwrite);
            var overrides = objects.clone(source._overrides);
            var _loop_1 = function (override) {
                var sourceOverride = overrides.filter(function (o) { return arrays.equals(o.identifiers, override.identifiers); })[0];
                if (sourceOverride) {
                    merge(sourceOverride.contents, override.contents, overwrite);
                }
                else {
                    overrides.push(override);
                }
            };
            for (var _i = 0, _a = target._overrides; _i < _a.length; _i++) {
                var override = _a[_i];
                _loop_1(override);
            }
            source._overrides = overrides;
        };
        return ConfigurationModel;
    }());
    exports.ConfigurationModel = ConfigurationModel;
    var Configuration = (function () {
        function Configuration(_defaults, _user, _workspaceConfiguration, folders, _workspace) {
            if (_workspaceConfiguration === void 0) { _workspaceConfiguration = new ConfigurationModel(); }
            if (folders === void 0) { folders = new map_1.StrictResourceMap(); }
            this._defaults = _defaults;
            this._user = _user;
            this._workspaceConfiguration = _workspaceConfiguration;
            this.folders = folders;
            this._workspace = _workspace;
            this.merge();
        }
        Object.defineProperty(Configuration.prototype, "defaults", {
            get: function () {
                return this._defaults;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Configuration.prototype, "user", {
            get: function () {
                return this._user;
            },
            enumerable: true,
            configurable: true
        });
        Configuration.prototype.merge = function () {
            this._globalConfiguration = new ConfigurationModel().merge(this._defaults).merge(this._user);
            this._workspaceConsolidatedConfiguration = new ConfigurationModel().merge(this._globalConfiguration).merge(this._workspaceConfiguration);
            this._legacyWorkspaceConsolidatedConfiguration = null;
            this._foldersConsolidatedConfigurations = new map_1.StrictResourceMap();
            for (var _i = 0, _a = this.folders.keys(); _i < _a.length; _i++) {
                var folder = _a[_i];
                this.mergeFolder(folder);
            }
        };
        Configuration.prototype.mergeFolder = function (folder) {
            this._foldersConsolidatedConfigurations.set(folder, new ConfigurationModel().merge(this._workspaceConsolidatedConfiguration).merge(this.folders.get(folder)));
        };
        Configuration.prototype.getValue = function (section, overrides) {
            if (section === void 0) { section = ''; }
            if (overrides === void 0) { overrides = {}; }
            var configModel = this.getConsolidateConfigurationModel(overrides);
            return section ? configModel.getContentsFor(section) : configModel.contents;
        };
        Configuration.prototype.lookup = function (key, overrides) {
            if (overrides === void 0) { overrides = {}; }
            // make sure to clone the configuration so that the receiver does not tamper with the values
            var consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides);
            var folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource);
            return {
                default: objects.clone(getConfigurationValue(overrides.overrideIdentifier ? this._defaults.override(overrides.overrideIdentifier).contents : this._defaults.contents, key)),
                user: objects.clone(getConfigurationValue(overrides.overrideIdentifier ? this._user.override(overrides.overrideIdentifier).contents : this._user.contents, key)),
                workspace: objects.clone(this._workspace ? getConfigurationValue(overrides.overrideIdentifier ? this._workspaceConfiguration.override(overrides.overrideIdentifier).contents : this._workspaceConfiguration.contents, key) : void 0),
                folder: objects.clone(folderConfigurationModel ? getConfigurationValue(overrides.overrideIdentifier ? folderConfigurationModel.override(overrides.overrideIdentifier).contents : folderConfigurationModel.contents, key) : void 0),
                value: objects.clone(getConfigurationValue(consolidateConfigurationModel.contents, key))
            };
        };
        Configuration.prototype.lookupLegacy = function (key) {
            if (!this._legacyWorkspaceConsolidatedConfiguration) {
                this._legacyWorkspaceConsolidatedConfiguration = this._workspace ? new ConfigurationModel().merge(this._workspaceConfiguration).merge(this.folders.get(this._workspace.roots[0])) : null;
            }
            var consolidateConfigurationModel = this.getConsolidateConfigurationModel({});
            return {
                default: objects.clone(getConfigurationValue(this._defaults.contents, key)),
                user: objects.clone(getConfigurationValue(this._user.contents, key)),
                workspace: objects.clone(this._legacyWorkspaceConsolidatedConfiguration ? getConfigurationValue(this._legacyWorkspaceConsolidatedConfiguration.contents, key) : void 0),
                folder: void 0,
                value: objects.clone(getConfigurationValue(consolidateConfigurationModel.contents, key))
            };
        };
        Configuration.prototype.keys = function (overrides) {
            if (overrides === void 0) { overrides = {}; }
            var folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource);
            return {
                default: this._defaults.keys,
                user: this._user.keys,
                workspace: this._workspaceConfiguration.keys,
                folder: folderConfigurationModel ? folderConfigurationModel.keys : []
            };
        };
        Configuration.prototype.values = function () {
            var result = Object.create(null);
            var keyset = this.keys();
            var keys = keyset.workspace.concat(keyset.user, keyset.default).sort();
            var lastKey;
            for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
                var key = keys_1[_i];
                if (key !== lastKey) {
                    lastKey = key;
                    result[key] = this.lookup(key);
                }
            }
            return result;
        };
        Configuration.prototype.values2 = function () {
            var result = new Map();
            var keyset = this.keys();
            var keys = keyset.workspace.concat(keyset.user, keyset.default).sort();
            var lastKey;
            for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) {
                var key = keys_2[_i];
                if (key !== lastKey) {
                    lastKey = key;
                    result.set(key, this.lookup(key));
                }
            }
            return result;
        };
        Configuration.prototype.getConsolidateConfigurationModel = function (overrides) {
            var configurationModel = this.getConsolidatedConfigurationModelForResource(overrides);
            return overrides.overrideIdentifier ? configurationModel.override(overrides.overrideIdentifier) : configurationModel;
        };
        Configuration.prototype.getConsolidatedConfigurationModelForResource = function (_a) {
            var resource = _a.resource;
            if (!this._workspace) {
                return this._globalConfiguration;
            }
            if (!resource) {
                return this._workspaceConsolidatedConfiguration;
            }
            var root = this._workspace.getRoot(resource);
            if (!root) {
                return this._workspaceConsolidatedConfiguration;
            }
            return this._foldersConsolidatedConfigurations.get(root) || this._workspaceConsolidatedConfiguration;
        };
        Configuration.prototype.getFolderConfigurationModelForResource = function (resource) {
            if (!this._workspace || !resource) {
                return null;
            }
            var root = this._workspace.getRoot(resource);
            return root ? this.folders.get(root) : null;
        };
        Configuration.prototype.toData = function () {
            var _this = this;
            return {
                defaults: {
                    contents: this._defaults.contents,
                    overrides: this._defaults.overrides,
                    keys: this._defaults.keys
                },
                user: {
                    contents: this._user.contents,
                    overrides: this._user.overrides,
                    keys: this._user.keys
                },
                workspace: {
                    contents: this._workspaceConfiguration.contents,
                    overrides: this._workspaceConfiguration.overrides,
                    keys: this._workspaceConfiguration.keys
                },
                folders: this.folders.keys().reduce(function (result, folder) {
                    var _a = _this.folders.get(folder), contents = _a.contents, overrides = _a.overrides, keys = _a.keys;
                    result[folder.toString()] = { contents: contents, overrides: overrides, keys: keys };
                    return result;
                }, Object.create({}))
            };
        };
        Configuration.parse = function (data, workspace) {
            var defaultConfiguration = Configuration.parseConfigurationModel(data.defaults);
            var userConfiguration = Configuration.parseConfigurationModel(data.user);
            var workspaceConfiguration = Configuration.parseConfigurationModel(data.workspace);
            var folders = Object.keys(data.folders).reduce(function (result, key) {
                result.set(uri_1.default.parse(key), Configuration.parseConfigurationModel(data.folders[key]));
                return result;
            }, new map_1.StrictResourceMap());
            return new Configuration(defaultConfiguration, userConfiguration, workspaceConfiguration, folders, workspace);
        };
        Configuration.parseConfigurationModel = function (model) {
            return new ConfigurationModel(model.contents, model.keys, model.overrides);
        };
        return Configuration;
    }());
    exports.Configuration = Configuration;
});











define(__m[19/*vs/platform/contextkey/common/contextkey*/], __M([1/*require*/,0/*exports*/,16/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ContextKeyExprType;
    (function (ContextKeyExprType) {
        ContextKeyExprType[ContextKeyExprType["Defined"] = 1] = "Defined";
        ContextKeyExprType[ContextKeyExprType["Not"] = 2] = "Not";
        ContextKeyExprType[ContextKeyExprType["Equals"] = 3] = "Equals";
        ContextKeyExprType[ContextKeyExprType["NotEquals"] = 4] = "NotEquals";
        ContextKeyExprType[ContextKeyExprType["And"] = 5] = "And";
    })(ContextKeyExprType = exports.ContextKeyExprType || (exports.ContextKeyExprType = {}));
    var ContextKeyExpr = (function () {
        function ContextKeyExpr() {
        }
        ContextKeyExpr.has = function (key) {
            return new ContextKeyDefinedExpr(key);
        };
        ContextKeyExpr.equals = function (key, value) {
            return new ContextKeyEqualsExpr(key, value);
        };
        ContextKeyExpr.notEquals = function (key, value) {
            return new ContextKeyNotEqualsExpr(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) {
            var _this = this;
            if (!serialized) {
                return null;
            }
            var pieces = serialized.split('&&');
            var result = new ContextKeyAndExpr(pieces.map(function (p) { return _this._deserializeOne(p); }));
            return result.normalize();
        };
        ContextKeyExpr._deserializeOne = function (serializedOne) {
            serializedOne = serializedOne.trim();
            if (serializedOne.indexOf('!=') >= 0) {
                var pieces = serializedOne.split('!=');
                return new ContextKeyNotEqualsExpr(pieces[0].trim(), this._deserializeValue(pieces[1]));
            }
            if (serializedOne.indexOf('==') >= 0) {
                var pieces = serializedOne.split('==');
                return new ContextKeyEqualsExpr(pieces[0].trim(), this._deserializeValue(pieces[1]));
            }
            if (/^\!\s*/.test(serializedOne)) {
                return new ContextKeyNotExpr(serializedOne.substr(1).trim());
            }
            return new ContextKeyDefinedExpr(serializedOne);
        };
        ContextKeyExpr._deserializeValue = function (serializedValue) {
            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;
        };
        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 ContextKeyExprType.Defined:
                return a.cmp(b);
            case ContextKeyExprType.Not:
                return a.cmp(b);
            case ContextKeyExprType.Equals:
                return a.cmp(b);
            case ContextKeyExprType.NotEquals:
                return a.cmp(b);
            default:
                throw new Error('Unknown ContextKeyExpr!');
        }
    }
    var ContextKeyDefinedExpr = (function () {
        function ContextKeyDefinedExpr(key) {
            this.key = key;
        }
        ContextKeyDefinedExpr.prototype.getType = function () {
            return ContextKeyExprType.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.serialize = function () {
            return this.key;
        };
        ContextKeyDefinedExpr.prototype.keys = function () {
            return [this.key];
        };
        return ContextKeyDefinedExpr;
    }());
    exports.ContextKeyDefinedExpr = ContextKeyDefinedExpr;
    var ContextKeyEqualsExpr = (function () {
        function ContextKeyEqualsExpr(key, value) {
            this.key = key;
            this.value = value;
        }
        ContextKeyEqualsExpr.prototype.getType = function () {
            return ContextKeyExprType.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.serialize = function () {
            if (typeof this.value === 'boolean') {
                return this.normalize().serialize();
            }
            return this.key + ' == \'' + this.value + '\'';
        };
        ContextKeyEqualsExpr.prototype.keys = function () {
            return [this.key];
        };
        return ContextKeyEqualsExpr;
    }());
    exports.ContextKeyEqualsExpr = ContextKeyEqualsExpr;
    var ContextKeyNotEqualsExpr = (function () {
        function ContextKeyNotEqualsExpr(key, value) {
            this.key = key;
            this.value = value;
        }
        ContextKeyNotEqualsExpr.prototype.getType = function () {
            return ContextKeyExprType.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.serialize = function () {
            if (typeof this.value === 'boolean') {
                return this.normalize().serialize();
            }
            return this.key + ' != \'' + this.value + '\'';
        };
        ContextKeyNotEqualsExpr.prototype.keys = function () {
            return [this.key];
        };
        return ContextKeyNotEqualsExpr;
    }());
    exports.ContextKeyNotEqualsExpr = ContextKeyNotEqualsExpr;
    var ContextKeyNotExpr = (function () {
        function ContextKeyNotExpr(key) {
            this.key = key;
        }
        ContextKeyNotExpr.prototype.getType = function () {
            return ContextKeyExprType.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.serialize = function () {
            return '!' + this.key;
        };
        ContextKeyNotExpr.prototype.keys = function () {
            return [this.key];
        };
        return ContextKeyNotExpr;
    }());
    exports.ContextKeyNotExpr = ContextKeyNotExpr;
    var ContextKeyAndExpr = (function () {
        function ContextKeyAndExpr(expr) {
            this.expr = ContextKeyAndExpr._normalizeArr(expr);
        }
        ContextKeyAndExpr.prototype.getType = function () {
            return ContextKeyExprType.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 null;
            }
            if (this.expr.length === 1) {
                return this.expr[0];
            }
            return this;
        };
        ContextKeyAndExpr.prototype.serialize = function () {
            if (this.expr.length === 0) {
                return '';
            }
            if (this.expr.length === 1) {
                return this.normalize().serialize();
            }
            return this.expr.map(function (e) { return e.serialize(); }).join(' && ');
        };
        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 = (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);
        };
        RawContextKey.prototype.isEqualTo = function (value) {
            return ContextKeyExpr.equals(this.key, value);
        };
        return RawContextKey;
    }(ContextKeyDefinedExpr));
    exports.RawContextKey = RawContextKey;
    exports.IContextKeyService = instantiation_1.createDecorator('contextKeyService');
    exports.SET_CONTEXT_COMMAND_ID = 'setContext';
});

define(__m[21/*vs/editor/common/editorContextKeys*/], __M([1/*require*/,0/*exports*/,19/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var EditorContextKeys;
    (function (EditorContextKeys) {
        /**
         * A context key that is set when the editor's text has focus (cursor is blinking).
         */
        EditorContextKeys.textFocus = 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);
        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', undefined);
        // -- mode context keys
        EditorContextKeys.languageId = new contextkey_1.RawContextKey('editorLangId', undefined);
        EditorContextKeys.hasCompletionItemProvider = new contextkey_1.RawContextKey('editorHasCompletionItemProvider', undefined);
        EditorContextKeys.hasCodeActionsProvider = new contextkey_1.RawContextKey('editorHasCodeActionsProvider', undefined);
        EditorContextKeys.hasCodeLensProvider = new contextkey_1.RawContextKey('editorHasCodeLensProvider', undefined);
        EditorContextKeys.hasDefinitionProvider = new contextkey_1.RawContextKey('editorHasDefinitionProvider', undefined);
        EditorContextKeys.hasImplementationProvider = new contextkey_1.RawContextKey('editorHasImplementationProvider', undefined);
        EditorContextKeys.hasTypeDefinitionProvider = new contextkey_1.RawContextKey('editorHasTypeDefinitionProvider', undefined);
        EditorContextKeys.hasHoverProvider = new contextkey_1.RawContextKey('editorHasHoverProvider', undefined);
        EditorContextKeys.hasDocumentHighlightProvider = new contextkey_1.RawContextKey('editorHasDocumentHighlightProvider', undefined);
        EditorContextKeys.hasDocumentSymbolProvider = new contextkey_1.RawContextKey('editorHasDocumentSymbolProvider', undefined);
        EditorContextKeys.hasReferenceProvider = new contextkey_1.RawContextKey('editorHasReferenceProvider', undefined);
        EditorContextKeys.hasRenameProvider = new contextkey_1.RawContextKey('editorHasRenameProvider', undefined);
        EditorContextKeys.hasDocumentFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentFormattingProvider', undefined);
        EditorContextKeys.hasDocumentSelectionFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentSelectionFormattingProvider', undefined);
        EditorContextKeys.hasSignatureHelpProvider = new contextkey_1.RawContextKey('editorHasSignatureHelpProvider', undefined);
    })(EditorContextKeys = exports.EditorContextKeys || (exports.EditorContextKeys = {}));
    ;
});











define(__m[406/*vs/editor/common/modes/editorModeContext*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,17/*vs/editor/common/modes*/,21/*vs/editor/common/editorContextKeys*/,70/*vs/base/common/network*/]), function (require, exports, lifecycle_1, modes, editorContextKeys_1, network_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var EditorModeContext = (function (_super) {
        __extends(EditorModeContext, _super);
        function EditorModeContext(editor, contextKeyService) {
            var _this = _super.call(this) || this;
            _this._editor = editor;
            _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._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._hasDocumentFormattingProvider = editorContextKeys_1.EditorContextKeys.hasDocumentFormattingProvider.bindTo(contextKeyService);
            _this._hasDocumentSelectionFormattingProvider = editorContextKeys_1.EditorContextKeys.hasDocumentSelectionFormattingProvider.bindTo(contextKeyService);
            _this._hasSignatureHelpProvider = editorContextKeys_1.EditorContextKeys.hasSignatureHelpProvider.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.SuggestRegistry.onDidChange(update));
            _this._register(modes.CodeActionProviderRegistry.onDidChange(update));
            _this._register(modes.CodeLensProviderRegistry.onDidChange(update));
            _this._register(modes.DefinitionProviderRegistry.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 () {
            this._langId.reset();
            this._hasCompletionItemProvider.reset();
            this._hasCodeActionsProvider.reset();
            this._hasCodeLensProvider.reset();
            this._hasDefinitionProvider.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 model = this._editor.getModel();
            if (!model) {
                this.reset();
                return;
            }
            this._langId.set(model.getLanguageIdentifier().language);
            this._hasCompletionItemProvider.set(modes.SuggestRegistry.has(model));
            this._hasCodeActionsProvider.set(modes.CodeActionProviderRegistry.has(model));
            this._hasCodeLensProvider.set(modes.CodeLensProviderRegistry.has(model));
            this._hasDefinitionProvider.set(modes.DefinitionProviderRegistry.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._isInWalkThrough.set(model.uri.scheme === network_1.Schemas.walkThroughSnippet);
        };
        return EditorModeContext;
    }(lifecycle_1.Disposable));
    exports.EditorModeContext = EditorModeContext;
});

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









define(__m[407/*vs/platform/actions/common/menu*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/event*/,3/*vs/base/common/lifecycle*/,19/*vs/platform/contextkey/common/contextkey*/,85/*vs/platform/actions/common/actions*/,31/*vs/platform/commands/common/commands*/]), function (require, exports, event_1, lifecycle_1, contextkey_1, actions_1, commands_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var Menu = (function () {
        function Menu(_id, startupSignal, _commandService, _contextKeyService) {
            var _this = this;
            this._id = _id;
            this._commandService = _commandService;
            this._contextKeyService = _contextKeyService;
            this._menuGroups = [];
            this._disposables = [];
            this._onDidChange = new event_1.Emitter();
            startupSignal.then(function (_) {
                var menuItems = actions_1.MenuRegistry.getMenuItems(_id);
                var keysFilter = new Set();
                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, keysFilter);
                }
                // subscribe to context changes
                _this._disposables.push(_this._contextKeyService.onDidChangeContext(function (keys) {
                    if (!keys) {
                        return;
                    }
                    for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
                        var k = keys_1[_i];
                        if (keysFilter.has(k)) {
                            _this._onDidChange.fire();
                            return;
                        }
                    }
                }));
                _this._onDidChange.fire(_this);
            });
        }
        Menu.prototype.dispose = function () {
            this._disposables = lifecycle_1.dispose(this._disposables);
            this._onDidChange.dispose();
        };
        Object.defineProperty(Menu.prototype, "onDidChange", {
            get: function () {
                return this._onDidChange.event;
            },
            enumerable: true,
            configurable: true
        });
        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 = new actions_1.MenuItemAction(item.command, item.alt, options, this._commandService);
                        action.order = item.order; //TODO@Ben order is menu item property, not an action property
                        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(2, commands_1.ICommandService),
            __param(3, contextkey_1.IContextKeyService)
        ], Menu);
        return Menu;
    }());
    exports.Menu = Menu;
});











define(__m[69/*vs/platform/contextview/browser/contextView*/], __M([1/*require*/,0/*exports*/,53/*vs/base/common/actions*/,16/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, actions_1, instantiation_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IContextViewService = instantiation_1.createDecorator('contextViewService');
    exports.IContextMenuService = instantiation_1.createDecorator('contextMenuService');
    var ContextSubMenu = (function (_super) {
        __extends(ContextSubMenu, _super);
        function ContextSubMenu(label, entries) {
            var _this = _super.call(this, 'contextsubmenu', label, '', true) || this;
            _this.entries = entries;
            return _this;
        }
        return ContextSubMenu;
    }(actions_1.Action));
    exports.ContextSubMenu = ContextSubMenu;
});

define(__m[64/*vs/platform/editor/common/editor*/], __M([1/*require*/,0/*exports*/,16/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IEditorService = instantiation_1.createDecorator('editorService');
    /**
     * Possible locations for opening an editor.
     */
    var Position;
    (function (Position) {
        /** Opens the editor in the first position replacing the input currently showing */
        Position[Position["ONE"] = 0] = "ONE";
        /** Opens the editor in the second position replacing the input currently showing */
        Position[Position["TWO"] = 1] = "TWO";
        /** Opens the editor in the third most position replacing the input currently showing */
        Position[Position["THREE"] = 2] = "THREE";
    })(Position = exports.Position || (exports.Position = {}));
    exports.POSITIONS = [Position.ONE, Position.TWO, Position.THREE];
    var Direction;
    (function (Direction) {
        Direction[Direction["LEFT"] = 0] = "LEFT";
        Direction[Direction["RIGHT"] = 1] = "RIGHT";
    })(Direction = exports.Direction || (exports.Direction = {}));
    var Verbosity;
    (function (Verbosity) {
        Verbosity[Verbosity["SHORT"] = 0] = "SHORT";
        Verbosity[Verbosity["MEDIUM"] = 1] = "MEDIUM";
        Verbosity[Verbosity["LONG"] = 2] = "LONG";
    })(Verbosity = exports.Verbosity || (exports.Verbosity = {}));
});

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











define(__m[411/*vs/platform/files/common/files*/], __M([1/*require*/,0/*exports*/,45/*vs/base/common/paths*/,79/*vs/base/common/events*/,15/*vs/base/common/platform*/,16/*vs/platform/instantiation/common/instantiation*/,9/*vs/base/common/strings*/]), function (require, exports, paths, events, platform_1, instantiation_1, strings_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IFileService = instantiation_1.createDecorator('fileService');
    var FileOperation;
    (function (FileOperation) {
        FileOperation[FileOperation["CREATE"] = 0] = "CREATE";
        FileOperation[FileOperation["DELETE"] = 1] = "DELETE";
        FileOperation[FileOperation["MOVE"] = 2] = "MOVE";
        FileOperation[FileOperation["COPY"] = 3] = "COPY";
        FileOperation[FileOperation["IMPORT"] = 4] = "IMPORT";
    })(FileOperation = exports.FileOperation || (exports.FileOperation = {}));
    var FileOperationEvent = (function () {
        function FileOperationEvent(_resource, _operation, _target) {
            this._resource = _resource;
            this._operation = _operation;
            this._target = _target;
        }
        Object.defineProperty(FileOperationEvent.prototype, "resource", {
            get: function () {
                return this._resource;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FileOperationEvent.prototype, "target", {
            get: function () {
                return this._target;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FileOperationEvent.prototype, "operation", {
            get: function () {
                return this._operation;
            },
            enumerable: true,
            configurable: true
        });
        return FileOperationEvent;
    }());
    exports.FileOperationEvent = FileOperationEvent;
    /**
     * Possible changes that can occur to a file.
     */
    var FileChangeType;
    (function (FileChangeType) {
        FileChangeType[FileChangeType["UPDATED"] = 0] = "UPDATED";
        FileChangeType[FileChangeType["ADDED"] = 1] = "ADDED";
        FileChangeType[FileChangeType["DELETED"] = 2] = "DELETED";
    })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
    var FileChangesEvent = (function (_super) {
        __extends(FileChangesEvent, _super);
        function FileChangesEvent(changes) {
            var _this = _super.call(this) || this;
            _this._changes = changes;
            return _this;
        }
        Object.defineProperty(FileChangesEvent.prototype, "changes", {
            get: function () {
                return this._changes;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns true if this change event contains the provided file with the given change type. In case of
         * type DELETED, this method will also return true if a folder got deleted that is the parent of the
         * provided file path.
         */
        FileChangesEvent.prototype.contains = function (resource, type) {
            if (!resource) {
                return false;
            }
            return this._changes.some(function (change) {
                if (change.type !== type) {
                    return false;
                }
                // For deleted also return true when deleted folder is parent of target path
                if (type === FileChangeType.DELETED) {
                    return paths.isEqualOrParent(resource.fsPath, change.resource.fsPath, !platform_1.isLinux /* ignorecase */);
                }
                return paths.isEqual(resource.fsPath, change.resource.fsPath, !platform_1.isLinux /* ignorecase */);
            });
        };
        /**
         * Returns the changes that describe added files.
         */
        FileChangesEvent.prototype.getAdded = function () {
            return this.getOfType(FileChangeType.ADDED);
        };
        /**
         * Returns if this event contains added files.
         */
        FileChangesEvent.prototype.gotAdded = function () {
            return this.hasType(FileChangeType.ADDED);
        };
        /**
         * Returns the changes that describe deleted files.
         */
        FileChangesEvent.prototype.getDeleted = function () {
            return this.getOfType(FileChangeType.DELETED);
        };
        /**
         * Returns if this event contains deleted files.
         */
        FileChangesEvent.prototype.gotDeleted = function () {
            return this.hasType(FileChangeType.DELETED);
        };
        /**
         * Returns the changes that describe updated files.
         */
        FileChangesEvent.prototype.getUpdated = function () {
            return this.getOfType(FileChangeType.UPDATED);
        };
        /**
         * Returns if this event contains updated files.
         */
        FileChangesEvent.prototype.gotUpdated = function () {
            return this.hasType(FileChangeType.UPDATED);
        };
        FileChangesEvent.prototype.getOfType = function (type) {
            return this._changes.filter(function (change) { return change.type === type; });
        };
        FileChangesEvent.prototype.hasType = function (type) {
            return this._changes.some(function (change) {
                return change.type === type;
            });
        };
        return FileChangesEvent;
    }(events.Event));
    exports.FileChangesEvent = FileChangesEvent;
    function isParent(path, candidate, ignoreCase) {
        if (!path || !candidate || path === candidate) {
            return false;
        }
        if (candidate.length > path.length) {
            return false;
        }
        if (candidate.charAt(candidate.length - 1) !== paths.nativeSep) {
            candidate += paths.nativeSep;
        }
        if (ignoreCase) {
            return strings_1.beginsWithIgnoreCase(path, candidate);
        }
        return path.indexOf(candidate) === 0;
    }
    exports.isParent = isParent;
    function indexOf(path, candidate, ignoreCase) {
        if (candidate.length > path.length) {
            return -1;
        }
        if (path === candidate) {
            return 0;
        }
        if (ignoreCase) {
            path = path.toLowerCase();
            candidate = candidate.toLowerCase();
        }
        return path.indexOf(candidate);
    }
    exports.indexOf = indexOf;
    var FileOperationError = (function (_super) {
        __extends(FileOperationError, _super);
        function FileOperationError(message, fileOperationResult) {
            var _this = _super.call(this, message) || this;
            _this.fileOperationResult = fileOperationResult;
            return _this;
        }
        return FileOperationError;
    }(Error));
    exports.FileOperationError = FileOperationError;
    var FileOperationResult;
    (function (FileOperationResult) {
        FileOperationResult[FileOperationResult["FILE_IS_BINARY"] = 0] = "FILE_IS_BINARY";
        FileOperationResult[FileOperationResult["FILE_IS_DIRECTORY"] = 1] = "FILE_IS_DIRECTORY";
        FileOperationResult[FileOperationResult["FILE_NOT_FOUND"] = 2] = "FILE_NOT_FOUND";
        FileOperationResult[FileOperationResult["FILE_NOT_MODIFIED_SINCE"] = 3] = "FILE_NOT_MODIFIED_SINCE";
        FileOperationResult[FileOperationResult["FILE_MODIFIED_SINCE"] = 4] = "FILE_MODIFIED_SINCE";
        FileOperationResult[FileOperationResult["FILE_MOVE_CONFLICT"] = 5] = "FILE_MOVE_CONFLICT";
        FileOperationResult[FileOperationResult["FILE_READ_ONLY"] = 6] = "FILE_READ_ONLY";
        FileOperationResult[FileOperationResult["FILE_TOO_LARGE"] = 7] = "FILE_TOO_LARGE";
        FileOperationResult[FileOperationResult["FILE_INVALID_PATH"] = 8] = "FILE_INVALID_PATH";
    })(FileOperationResult = exports.FileOperationResult || (exports.FileOperationResult = {}));
    // See https://github.com/Microsoft/vscode/issues/30180
    var WIN32_MAX_FILE_SIZE = 300 * 1024 * 1024; // 300 MB
    var GENERAL_MAX_FILE_SIZE = 16 * 1024 * 1024 * 1024; // 16 GB
    exports.MAX_FILE_SIZE = (typeof process === 'object' ? (process.arch === 'ia32' ? WIN32_MAX_FILE_SIZE : GENERAL_MAX_FILE_SIZE) : WIN32_MAX_FILE_SIZE);
    exports.AutoSaveConfiguration = {
        OFF: 'off',
        AFTER_DELAY: 'afterDelay',
        ON_FOCUS_CHANGE: 'onFocusChange',
        ON_WINDOW_CHANGE: 'onWindowChange'
    };
    exports.HotExitConfiguration = {
        OFF: 'off',
        ON_EXIT: 'onExit',
        ON_EXIT_AND_WINDOW_CLOSE: 'onExitAndWindowClose'
    };
    exports.CONTENT_CHANGE_EVENT_BUFFER_DELAY = 1000;
    exports.SUPPORTED_ENCODINGS = {
        utf8: {
            labelLong: 'UTF-8',
            labelShort: 'UTF-8',
            order: 1,
            alias: 'utf8bom'
        },
        utf8bom: {
            labelLong: 'UTF-8 with BOM',
            labelShort: 'UTF-8 with BOM',
            encodeOnly: true,
            order: 2,
            alias: 'utf8'
        },
        utf16le: {
            labelLong: 'UTF-16 LE',
            labelShort: 'UTF-16 LE',
            order: 3
        },
        utf16be: {
            labelLong: 'UTF-16 BE',
            labelShort: 'UTF-16 BE',
            order: 4
        },
        windows1252: {
            labelLong: 'Western (Windows 1252)',
            labelShort: 'Windows 1252',
            order: 5
        },
        iso88591: {
            labelLong: 'Western (ISO 8859-1)',
            labelShort: 'ISO 8859-1',
            order: 6
        },
        iso88593: {
            labelLong: 'Western (ISO 8859-3)',
            labelShort: 'ISO 8859-3',
            order: 7
        },
        iso885915: {
            labelLong: 'Western (ISO 8859-15)',
            labelShort: 'ISO 8859-15',
            order: 8
        },
        macroman: {
            labelLong: 'Western (Mac Roman)',
            labelShort: 'Mac Roman',
            order: 9
        },
        cp437: {
            labelLong: 'DOS (CP 437)',
            labelShort: 'CP437',
            order: 10
        },
        windows1256: {
            labelLong: 'Arabic (Windows 1256)',
            labelShort: 'Windows 1256',
            order: 11
        },
        iso88596: {
            labelLong: 'Arabic (ISO 8859-6)',
            labelShort: 'ISO 8859-6',
            order: 12
        },
        windows1257: {
            labelLong: 'Baltic (Windows 1257)',
            labelShort: 'Windows 1257',
            order: 13
        },
        iso88594: {
            labelLong: 'Baltic (ISO 8859-4)',
            labelShort: 'ISO 8859-4',
            order: 14
        },
        iso885914: {
            labelLong: 'Celtic (ISO 8859-14)',
            labelShort: 'ISO 8859-14',
            order: 15
        },
        windows1250: {
            labelLong: 'Central European (Windows 1250)',
            labelShort: 'Windows 1250',
            order: 16
        },
        iso88592: {
            labelLong: 'Central European (ISO 8859-2)',
            labelShort: 'ISO 8859-2',
            order: 17
        },
        cp852: {
            labelLong: 'Central European (CP 852)',
            labelShort: 'CP 852',
            order: 18
        },
        windows1251: {
            labelLong: 'Cyrillic (Windows 1251)',
            labelShort: 'Windows 1251',
            order: 19
        },
        cp866: {
            labelLong: 'Cyrillic (CP 866)',
            labelShort: 'CP 866',
            order: 20
        },
        iso88595: {
            labelLong: 'Cyrillic (ISO 8859-5)',
            labelShort: 'ISO 8859-5',
            order: 21
        },
        koi8r: {
            labelLong: 'Cyrillic (KOI8-R)',
            labelShort: 'KOI8-R',
            order: 22
        },
        koi8u: {
            labelLong: 'Cyrillic (KOI8-U)',
            labelShort: 'KOI8-U',
            order: 23
        },
        iso885913: {
            labelLong: 'Estonian (ISO 8859-13)',
            labelShort: 'ISO 8859-13',
            order: 24
        },
        windows1253: {
            labelLong: 'Greek (Windows 1253)',
            labelShort: 'Windows 1253',
            order: 25
        },
        iso88597: {
            labelLong: 'Greek (ISO 8859-7)',
            labelShort: 'ISO 8859-7',
            order: 26
        },
        windows1255: {
            labelLong: 'Hebrew (Windows 1255)',
            labelShort: 'Windows 1255',
            order: 27
        },
        iso88598: {
            labelLong: 'Hebrew (ISO 8859-8)',
            labelShort: 'ISO 8859-8',
            order: 28
        },
        iso885910: {
            labelLong: 'Nordic (ISO 8859-10)',
            labelShort: 'ISO 8859-10',
            order: 29
        },
        iso885916: {
            labelLong: 'Romanian (ISO 8859-16)',
            labelShort: 'ISO 8859-16',
            order: 30
        },
        windows1254: {
            labelLong: 'Turkish (Windows 1254)',
            labelShort: 'Windows 1254',
            order: 31
        },
        iso88599: {
            labelLong: 'Turkish (ISO 8859-9)',
            labelShort: 'ISO 8859-9',
            order: 32
        },
        windows1258: {
            labelLong: 'Vietnamese (Windows 1258)',
            labelShort: 'Windows 1258',
            order: 33
        },
        gbk: {
            labelLong: 'Chinese (GBK)',
            labelShort: 'GBK',
            order: 34
        },
        gb18030: {
            labelLong: 'Chinese (GB18030)',
            labelShort: 'GB18030',
            order: 35
        },
        cp950: {
            labelLong: 'Traditional Chinese (Big5)',
            labelShort: 'Big5',
            order: 36
        },
        big5hkscs: {
            labelLong: 'Traditional Chinese (Big5-HKSCS)',
            labelShort: 'Big5-HKSCS',
            order: 37
        },
        shiftjis: {
            labelLong: 'Japanese (Shift JIS)',
            labelShort: 'Shift JIS',
            order: 38
        },
        eucjp: {
            labelLong: 'Japanese (EUC-JP)',
            labelShort: 'EUC-JP',
            order: 39
        },
        euckr: {
            labelLong: 'Korean (EUC-KR)',
            labelShort: 'EUC-KR',
            order: 40
        },
        windows874: {
            labelLong: 'Thai (Windows 874)',
            labelShort: 'Windows 874',
            order: 41
        },
        iso885911: {
            labelLong: 'Latin/Thai (ISO 8859-11)',
            labelShort: 'ISO 8859-11',
            order: 42
        },
        koi8ru: {
            labelLong: 'Cyrillic (KOI8-RU)',
            labelShort: 'KOI8-RU',
            order: 43
        },
        koi8t: {
            labelLong: 'Tajik (KOI8-T)',
            labelShort: 'KOI8-T',
            order: 44
        },
        gb2312: {
            labelLong: 'Simplified Chinese (GB 2312)',
            labelShort: 'GB 2312',
            order: 45
        }
    };
    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[84/*vs/platform/instantiation/common/serviceCollection*/], __M([1/*require*/,0/*exports*/]), 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 ServiceCollection = (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.forEach = function (callback) {
            this._entries.forEach(function (value, key) { return callback(key, value); });
        };
        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;
});

define(__m[413/*vs/platform/instantiation/common/instantiationService*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,10/*vs/base/common/errors*/,29/*vs/base/common/types*/,72/*vs/base/common/assert*/,428/*vs/base/common/graph*/,187/*vs/platform/instantiation/common/descriptors*/,16/*vs/platform/instantiation/common/instantiation*/,84/*vs/platform/instantiation/common/serviceCollection*/]), function (require, exports, winjs_base_1, errors_1, types_1, assert, graph_1, descriptors_1, instantiation_1, serviceCollection_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var InstantiationService = (function () {
        function InstantiationService(services, strict) {
            if (services === void 0) { services = new serviceCollection_1.ServiceCollection(); }
            if (strict === void 0) { strict = false; }
            this._services = services;
            this._strict = strict;
            this._services.set(instantiation_1.IInstantiationService, this);
        }
        InstantiationService.prototype.createChild = function (services) {
            var _this = this;
            this._services.forEach(function (id, thing) {
                if (services.has(id)) {
                    return;
                }
                // If we copy descriptors we might end up with
                // multiple instances of the same service
                if (thing instanceof descriptors_1.SyncDescriptor) {
                    thing = _this._createAndCacheServiceInstance(id, thing);
                }
                services.set(id, thing);
            });
            return new InstantiationService(services, this._strict);
        };
        InstantiationService.prototype.invokeFunction = function (signature) {
            var _this = this;
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            var accessor;
            try {
                accessor = {
                    get: function (id, isOptional) {
                        var result = _this._getOrCreateServiceInstance(id);
                        if (!result && isOptional !== instantiation_1.optional) {
                            throw new Error("[invokeFunction] unkown service '" + id + "'");
                        }
                        return result;
                    }
                };
                return signature.apply(undefined, [accessor].concat(args));
            }
            finally {
                accessor.get = function () {
                    throw errors_1.illegalState('service accessor is only valid during the invocation of its target method');
                };
            }
        };
        InstantiationService.prototype.createInstance = function (param) {
            var rest = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                rest[_i - 1] = arguments[_i];
            }
            if (param instanceof descriptors_1.AsyncDescriptor) {
                // async
                return this._createInstanceAsync(param, rest);
            }
            else if (param instanceof descriptors_1.SyncDescriptor) {
                // sync
                return this._createInstance(param, rest);
            }
            else {
                // sync, just ctor
                return this._createInstance(new descriptors_1.SyncDescriptor(param), rest);
            }
        };
        InstantiationService.prototype._createInstanceAsync = function (descriptor, args) {
            var _this = this;
            var canceledError;
            return new winjs_base_1.TPromise(function (c, e, p) {
                require([descriptor.moduleName], function (_module) {
                    if (canceledError) {
                        e(canceledError);
                    }
                    if (!_module) {
                        return e(errors_1.illegalArgument('module not found: ' + descriptor.moduleName));
                    }
                    var ctor;
                    if (!descriptor.ctorName) {
                        ctor = _module;
                    }
                    else {
                        ctor = _module[descriptor.ctorName];
                    }
                    if (typeof ctor !== 'function') {
                        return e(errors_1.illegalArgument('not a function: ' + descriptor.ctorName || descriptor.moduleName));
                    }
                    try {
                        args.unshift.apply(args, descriptor.staticArguments()); // instead of spread in ctor call
                        c(_this._createInstance(new descriptors_1.SyncDescriptor(ctor), args));
                    }
                    catch (error) {
                        return e(error);
                    }
                }, e);
            }, function () {
                canceledError = errors_1.canceled();
            });
        };
        InstantiationService.prototype._createInstance = function (desc, args) {
            // arguments given by createInstance-call and/or the descriptor
            var staticArgs = desc.staticArguments().concat(args);
            // arguments defined by service decorators
            var serviceDependencies = instantiation_1._util.getServiceDependencies(desc.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);
                if (!service && this._strict && !dependency.optional) {
                    throw new Error("[createInstance] " + desc.ctor.name + " depends on UNKNOWN service " + dependency.id + ".");
                }
                serviceArgs.push(service);
            }
            var firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : staticArgs.length;
            // check for argument mismatches, adjust static args if needed
            if (staticArgs.length !== firstServiceArgPos) {
                console.warn("[createInstance] First service dependency of " + desc.ctor.name + " at position " + (firstServiceArgPos + 1) + " conflicts with " + staticArgs.length + " static arguments");
                var delta = firstServiceArgPos - staticArgs.length;
                if (delta > 0) {
                    staticArgs = staticArgs.concat(new Array(delta));
                }
                else {
                    staticArgs = staticArgs.slice(0, firstServiceArgPos);
                }
            }
            // // check for missing args
            // for (let i = 0; i < serviceArgs.length; i++) {
            // 	if (!serviceArgs[i]) {
            // 		console.warn(`${desc.ctor.name} MISSES service dependency ${serviceDependencies[i].id}`, new Error().stack);
            // 	}
            // }
            // now create the instance
            var argArray = [desc.ctor];
            argArray.push.apply(argArray, staticArgs);
            argArray.push.apply(argArray, serviceArgs);
            var instance = types_1.create.apply(null, argArray);
            desc._validate(instance);
            return instance;
        };
        InstantiationService.prototype._getOrCreateServiceInstance = function (id) {
            var thing = this._services.get(id);
            if (thing instanceof descriptors_1.SyncDescriptor) {
                return this._createAndCacheServiceInstance(id, thing);
            }
            else {
                return thing;
            }
        };
        InstantiationService.prototype._createAndCacheServiceInstance = function (id, desc) {
            assert.ok(this._services.get(id) instanceof descriptors_1.SyncDescriptor);
            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 }];
            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 the 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._services.get(dependency.id);
                    if (!instanceOrDesc) {
                        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 };
                        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.length !== 0) {
                        throwCycleError();
                    }
                    break;
                }
                for (var _a = 0, roots_1 = roots; _a < roots_1.length; _a++) {
                    var root = roots_1[_a];
                    // create instance and overwrite the service collections
                    var instance = this._createInstance(root.data.desc, []);
                    this._services.set(root.data.id, instance);
                    graph.removeNode(root.data);
                }
            }
            return this._services.get(id);
        };
        return InstantiationService;
    }());
    exports.InstantiationService = InstantiationService;
});

define(__m[414/*vs/platform/keybinding/common/abstractKeybindingService*/], __M([1/*require*/,0/*exports*/,383/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/,3/*vs/base/common/lifecycle*/,36/*vs/base/common/severity*/,11/*vs/base/common/event*/]), function (require, exports, nls, lifecycle_1, severity_1, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var AbstractKeybindingService = (function () {
        function AbstractKeybindingService(contextKeyService, commandService, messageService, statusService) {
            this.toDispose = [];
            this._contextKeyService = contextKeyService;
            this._commandService = commandService;
            this._statusService = statusService;
            this._messageService = messageService;
            this._currentChord = null;
            this._currentChordStatusMessage = null;
            this._onDidUpdateKeybindings = new event_1.Emitter();
            this.toDispose.push(this._onDidUpdateKeybindings);
        }
        AbstractKeybindingService.prototype.dispose = function () {
            this.toDispose = lifecycle_1.dispose(this.toDispose);
        };
        Object.defineProperty(AbstractKeybindingService.prototype, "onDidUpdateKeybindings", {
            get: function () {
                return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : event_1.default.None; // Sinon stubbing walks properties on prototype
            },
            enumerable: true,
            configurable: true
        });
        AbstractKeybindingService.prototype.getDefaultKeybindingsContent = function () {
            return '';
        };
        AbstractKeybindingService.prototype.getDefaultKeybindings = function () {
            return this._getResolver().getDefaultKeybindings();
        };
        AbstractKeybindingService.prototype.getKeybindings = function () {
            return this._getResolver().getKeybindings();
        };
        AbstractKeybindingService.prototype.customKeybindingsCount = function () {
            return 0;
        };
        AbstractKeybindingService.prototype.lookupKeybindings = function (commandId) {
            return this._getResolver().lookupKeybindings(commandId).map(function (item) { return item.resolvedKeybinding; });
        };
        AbstractKeybindingService.prototype.lookupKeybinding = function (commandId) {
            var result = this._getResolver().lookupPrimaryKeybinding(commandId);
            if (!result) {
                return null;
            }
            return result.resolvedKeybinding;
        };
        AbstractKeybindingService.prototype.softDispatch = function (e, target) {
            var keybinding = this.resolveKeyboardEvent(e);
            if (keybinding.isChord()) {
                console.warn('Unexpected keyboard event mapped to a chord');
                return null;
            }
            var firstPart = keybinding.getDispatchParts()[0];
            if (firstPart === null) {
                // cannot be dispatched, probably only modifier keys
                return null;
            }
            var contextValue = this._contextKeyService.getContext(target);
            var currentChord = this._currentChord ? this._currentChord.keypress : null;
            return this._getResolver().resolve(contextValue, currentChord, firstPart);
        };
        AbstractKeybindingService.prototype._dispatch = function (e, target) {
            var _this = this;
            var shouldPreventDefault = false;
            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 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._currentChord = {
                    keypress: firstPart,
                    label: keypressLabel
                };
                if (this._statusService) {
                    this._currentChordStatusMessage = this._statusService.setStatusMessage(nls.localize(0, null, 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;
                }
            }
            if (this._currentChordStatusMessage) {
                this._currentChordStatusMessage.dispose();
                this._currentChordStatusMessage = null;
            }
            this._currentChord = null;
            if (resolveResult && resolveResult.commandId) {
                if (!resolveResult.bubble) {
                    shouldPreventDefault = true;
                }
                this._commandService.executeCommand(resolveResult.commandId, resolveResult.commandArgs || {}).done(undefined, function (err) {
                    _this._messageService.show(severity_1.default.Warning, err);
                });
            }
            return shouldPreventDefault;
        };
        return AbstractKeybindingService;
    }());
    exports.AbstractKeybindingService = AbstractKeybindingService;
});

define(__m[46/*vs/platform/keybinding/common/keybinding*/], __M([1/*require*/,0/*exports*/,16/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var KeybindingSource;
    (function (KeybindingSource) {
        KeybindingSource[KeybindingSource["Default"] = 1] = "Default";
        KeybindingSource[KeybindingSource["User"] = 2] = "User";
    })(KeybindingSource = exports.KeybindingSource || (exports.KeybindingSource = {}));
    exports.IKeybindingService = instantiation_1.createDecorator('keybindingService');
});

define(__m[159/*vs/platform/keybinding/common/keybindingResolver*/], __M([1/*require*/,0/*exports*/,33/*vs/base/common/arrays*/,31/*vs/platform/commands/common/commands*/]), function (require, exports, arrays_1, commands_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var KeybindingResolver = (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;
                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.keypressFirstPart === null) {
                    // unbound
                    continue;
                }
                this._addKeyPress(k.keypressFirstPart, k);
            }
        }
        KeybindingResolver._isTargetedForRemoval = function (defaultKb, keypressFirstPart, keypressChordPart, command, when) {
            if (defaultKb.command !== command) {
                return false;
            }
            if (keypressFirstPart && defaultKb.keypressFirstPart !== keypressFirstPart) {
                return false;
            }
            if (keypressChordPart && defaultKb.keypressChordPart !== 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, len = rawOverrides.length; i < len; i++) {
                var override = rawOverrides[i];
                if (!override.command || override.command.length === 0 || override.command.charAt(0) !== '-') {
                    overrides.push(override);
                    continue;
                }
                var command = override.command.substr(1);
                var keypressFirstPart = override.keypressFirstPart;
                var keypressChordPart = override.keypressChordPart;
                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.keypressChordPart !== null);
                var itemIsChord = (item.keypressChordPart !== null);
                if (conflictIsChord && itemIsChord && conflict.keypressChordPart !== item.keypressChordPart) {
                    // The conflict only shares the chord start with this command
                    continue;
                }
                if (KeybindingResolver.whenIsEntirelyIncluded(true, 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) {
            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 `a` is completely covered by `b`.
         * Returns true if `b` is a more relaxed `a`.
         * Return true if (`a` === true implies `b` === true).
         */
        KeybindingResolver.whenIsEntirelyIncluded = function (inNormalizedForm, a, b) {
            if (!inNormalizedForm) {
                a = a ? a.normalize() : null;
                b = b ? b.normalize() : null;
            }
            if (!b) {
                return true;
            }
            if (!a) {
                return false;
            }
            var aRulesArr = a.serialize().split(' && ');
            var bRulesArr = b.serialize().split(' && ');
            var aRules = Object.create(null);
            for (var i = 0, len = aRulesArr.length; i < len; i++) {
                aRules[aRulesArr[i]] = true;
            }
            for (var i = 0, len = bRulesArr.length; i < len; i++) {
                if (!aRules[bRulesArr[i]]) {
                    return false;
                }
            }
            return true;
        };
        KeybindingResolver.prototype.getDefaultBoundCommands = function () {
            return this._defaultBoundCommands;
        };
        KeybindingResolver.prototype.getDefaultKeybindings = function () {
            return this._defaultKeybindings;
        };
        KeybindingResolver.prototype.getKeybindings = function () {
            return this._keybindings;
        };
        KeybindingResolver.prototype.lookupKeybindings = function (commandId) {
            var items = this._lookupMap.get(commandId);
            if (typeof items === 'undefined' || items.length === 0) {
                return [];
            }
            // Reverse to get the most specific item first
            var result = [], resultLen = 0;
            for (var i = items.length - 1; i >= 0; i--) {
                result[resultLen++] = items[i];
            }
            return result;
        };
        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];
                    if (candidate.keypressChordPart === 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;
            }
            if (currentChord === null && result.keypressChordPart !== 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);
        };
        KeybindingResolver.getAllUnboundCommands = function (boundCommands) {
            var commands = commands_1.CommandsRegistry.getCommands();
            var unboundCommands = [];
            for (var id in commands) {
                if (id[0] === '_' || id.indexOf('vscode.') === 0) {
                    continue;
                }
                if (typeof commands[id].description === 'object'
                    && !arrays_1.isFalsyOrEmpty(commands[id].description.args)) {
                    continue;
                }
                if (boundCommands.get(id) === true) {
                    continue;
                }
                unboundCommands.push(id);
            }
            return unboundCommands;
        };
        return KeybindingResolver;
    }());
    exports.KeybindingResolver = KeybindingResolver;
});




















define(__m[417/*vs/platform/contextkey/browser/contextKeyService*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,31/*vs/platform/commands/common/commands*/,159/*vs/platform/keybinding/common/keybindingResolver*/,19/*vs/platform/contextkey/common/contextkey*/,62/*vs/platform/configuration/common/configuration*/,11/*vs/base/common/event*/]), function (require, exports, lifecycle_1, commands_1, keybindingResolver_1, contextkey_1, configuration_1, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';
    var Context = (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);
            return delete this._value[key];
        };
        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 ConfigAwareContextValuesContainer = (function (_super) {
        __extends(ConfigAwareContextValuesContainer, _super);
        function ConfigAwareContextValuesContainer(id, configurationService, emitter) {
            var _this = _super.call(this, id, null) || this;
            _this._emitter = emitter;
            _this._subscription = configurationService.onDidUpdateConfiguration(function (e) { return _this._updateConfigurationContext(configurationService.getConfiguration()); });
            _this._updateConfigurationContext(configurationService.getConfiguration());
            return _this;
        }
        ConfigAwareContextValuesContainer.prototype.dispose = function () {
            this._subscription.dispose();
        };
        ConfigAwareContextValuesContainer.prototype._updateConfigurationContext = function (config) {
            var _this = this;
            // remove old config.xyz values
            for (var key in this._value) {
                if (key.indexOf('config.') === 0) {
                    delete this._value[key];
                }
            }
            // add new value from config
            var walk = function (obj, keys) {
                for (var key in obj) {
                    if (Object.prototype.hasOwnProperty.call(obj, key)) {
                        keys.push(key);
                        var value = obj[key];
                        if (typeof value === 'boolean') {
                            var configKey = keys.join('.');
                            _this._value[configKey] = value;
                            _this._emitter.fire(configKey);
                        }
                        else if (typeof value === 'object') {
                            walk(value, keys);
                        }
                        keys.pop();
                    }
                }
            };
            walk(config, ['config']);
        };
        return ConfigAwareContextValuesContainer;
    }(Context));
    var ContextKey = (function () {
        function ContextKey(parent, key, defaultValue) {
            this._parent = parent;
            this._key = key;
            this._defaultValue = defaultValue;
            this.reset();
        }
        ContextKey.prototype.set = function (value) {
            this._parent.setContext(this._key, value);
        };
        ContextKey.prototype.reset = function () {
            if (typeof this._defaultValue === 'undefined') {
                this._parent.removeContext(this._key);
            }
            else {
                this._parent.setContext(this._key, this._defaultValue);
            }
        };
        ContextKey.prototype.get = function () {
            return this._parent.getContextKeyValue(this._key);
        };
        return ContextKey;
    }());
    var AbstractContextKeyService = (function () {
        function AbstractContextKeyService(myContextId) {
            this._myContextId = myContextId;
            this._onDidChangeContextKey = new event_1.Emitter();
        }
        AbstractContextKeyService.prototype.createKey = function (key, defaultValue) {
            return new ContextKey(this, key, defaultValue);
        };
        Object.defineProperty(AbstractContextKeyService.prototype, "onDidChangeContext", {
            get: function () {
                if (!this._onDidChangeContext) {
                    this._onDidChangeContext = event_1.debounceEvent(this._onDidChangeContextKey.event, function (prev, cur) {
                        if (!prev) {
                            prev = [cur];
                        }
                        else if (prev.indexOf(cur) < 0) {
                            prev.push(cur);
                        }
                        return prev;
                    }, 25);
                }
                return this._onDidChangeContext;
            },
            enumerable: true,
            configurable: true
        });
        AbstractContextKeyService.prototype.createScoped = function (domNode) {
            return new ScopedContextKeyService(this, this._onDidChangeContextKey, domNode);
        };
        AbstractContextKeyService.prototype.contextMatchesRules = function (rules) {
            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) {
            return this.getContextValuesContainer(this._myContextId).getValue(key);
        };
        AbstractContextKeyService.prototype.setContext = function (key, value) {
            if (this.getContextValuesContainer(this._myContextId).setValue(key, value)) {
                this._onDidChangeContextKey.fire(key);
            }
        };
        AbstractContextKeyService.prototype.removeContext = function (key) {
            if (this.getContextValuesContainer(this._myContextId).removeValue(key)) {
                this._onDidChangeContextKey.fire(key);
            }
        };
        AbstractContextKeyService.prototype.getContext = function (target) {
            return this.getContextValuesContainer(findContextAttr(target));
        };
        return AbstractContextKeyService;
    }());
    exports.AbstractContextKeyService = AbstractContextKeyService;
    var ContextKeyService = (function (_super) {
        __extends(ContextKeyService, _super);
        function ContextKeyService(configurationService) {
            var _this = _super.call(this, 0) || this;
            _this._toDispose = [];
            _this._lastContextId = 0;
            _this._contexts = Object.create(null);
            var myContext = new ConfigAwareContextValuesContainer(_this._myContextId, configurationService, _this._onDidChangeContextKey);
            _this._contexts[String(_this._myContextId)] = myContext;
            _this._toDispose.push(myContext);
            return _this;
            // Uncomment this to see the contexts continuously logged
            // let lastLoggedValue: string = 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._toDispose = lifecycle_1.dispose(this._toDispose);
        };
        ContextKeyService.prototype.getContextValuesContainer = function (contextId) {
            return this._contexts[String(contextId)];
        };
        ContextKeyService.prototype.createChildContext = function (parentContextId) {
            if (parentContextId === void 0) { parentContextId = this._myContextId; }
            var id = (++this._lastContextId);
            this._contexts[String(id)] = new Context(id, this.getContextValuesContainer(parentContextId));
            return id;
        };
        ContextKeyService.prototype.disposeContext = function (contextId) {
            delete this._contexts[String(contextId)];
        };
        ContextKeyService = __decorate([
            __param(0, configuration_1.IConfigurationService)
        ], ContextKeyService);
        return ContextKeyService;
    }(AbstractContextKeyService));
    exports.ContextKeyService = ContextKeyService;
    var ScopedContextKeyService = (function (_super) {
        __extends(ScopedContextKeyService, _super);
        function ScopedContextKeyService(parent, emitter, domNode) {
            var _this = _super.call(this, parent.createChildContext()) || this;
            _this._parent = parent;
            _this._onDidChangeContextKey = emitter;
            if (domNode) {
                _this._domNode = domNode;
                _this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(_this._myContextId));
            }
            return _this;
        }
        ScopedContextKeyService.prototype.dispose = function () {
            this._parent.disposeContext(this._myContextId);
            if (this._domNode) {
                this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR);
            }
        };
        Object.defineProperty(ScopedContextKeyService.prototype, "onDidChangeContext", {
            get: function () {
                return this._parent.onDidChangeContext;
            },
            enumerable: true,
            configurable: true
        });
        ScopedContextKeyService.prototype.getContextValuesContainer = function (contextId) {
            return this._parent.getContextValuesContainer(contextId);
        };
        ScopedContextKeyService.prototype.createChildContext = function (parentContextId) {
            if (parentContextId === void 0) { parentContextId = this._myContextId; }
            return this._parent.createChildContext(parentContextId);
        };
        ScopedContextKeyService.prototype.disposeContext = function (contextId) {
            this._parent.disposeContext(contextId);
        };
        return ScopedContextKeyService;
    }(AbstractContextKeyService));
    function findContextAttr(domNode) {
        while (domNode) {
            if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
                return parseInt(domNode.getAttribute(KEYBINDING_CONTEXT_ATTR), 10);
            }
            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);
    });
});

define(__m[418/*vs/platform/keybinding/common/resolvedKeybindingItem*/], __M([1/*require*/,0/*exports*/]), 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 ResolvedKeybindingItem = (function () {
        function ResolvedKeybindingItem(resolvedKeybinding, command, commandArgs, when, isDefault) {
            this.resolvedKeybinding = resolvedKeybinding;
            if (resolvedKeybinding) {
                var _a = resolvedKeybinding.getDispatchParts(), keypressFirstPart = _a[0], keypressChordPart = _a[1];
                this.keypressFirstPart = keypressFirstPart;
                this.keypressChordPart = keypressChordPart;
            }
            else {
                this.keypressFirstPart = null;
                this.keypressChordPart = null;
            }
            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;
});











define(__m[419/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/], __M([1/*require*/,0/*exports*/,40/*vs/base/common/keyCodes*/,155/*vs/base/common/keybindingLabels*/]), function (require, exports, keyCodes_1, keybindingLabels_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * Do not instantiate. Use KeybindingService to get a ResolvedKeybinding seeded with information about the current kb layout.
     */
    var USLayoutResolvedKeybinding = (function (_super) {
        __extends(USLayoutResolvedKeybinding, _super);
        function USLayoutResolvedKeybinding(actual, OS) {
            var _this = _super.call(this) || this;
            _this._os = OS;
            if (actual === null) {
                _this._firstPart = null;
                _this._chordPart = null;
            }
            else if (actual.type === 2 /* Chord */) {
                _this._firstPart = actual.firstPart;
                _this._chordPart = actual.chordPart;
            }
            else {
                _this._firstPart = actual;
                _this._chordPart = null;
            }
            return _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._getUILabelForKeybinding = function (keybinding) {
            if (!keybinding) {
                return null;
            }
            if (keybinding.isDuplicateModifierCase()) {
                return '';
            }
            return this._keyCodeToUILabel(keybinding.keyCode);
        };
        USLayoutResolvedKeybinding.prototype.getLabel = function () {
            var firstPart = this._getUILabelForKeybinding(this._firstPart);
            var chordPart = this._getUILabelForKeybinding(this._chordPart);
            return keybindingLabels_1.UILabelProvider.toLabel(this._firstPart, firstPart, this._chordPart, chordPart, this._os);
        };
        USLayoutResolvedKeybinding.prototype._getAriaLabelForKeybinding = function (keybinding) {
            if (!keybinding) {
                return null;
            }
            if (keybinding.isDuplicateModifierCase()) {
                return '';
            }
            return keyCodes_1.KeyCodeUtils.toString(keybinding.keyCode);
        };
        USLayoutResolvedKeybinding.prototype.getAriaLabel = function () {
            var firstPart = this._getAriaLabelForKeybinding(this._firstPart);
            var chordPart = this._getAriaLabelForKeybinding(this._chordPart);
            return keybindingLabels_1.AriaLabelProvider.toLabel(this._firstPart, firstPart, this._chordPart, chordPart, this._os);
        };
        USLayoutResolvedKeybinding.prototype._keyCodeToElectronAccelerator = function (keyCode) {
            if (keyCode >= 93 /* NUMPAD_0 */ && keyCode <= 108 /* NUMPAD_DIVIDE */) {
                // Electron cannot handle numpad keys
                return null;
            }
            switch (keyCode) {
                case 16 /* UpArrow */:
                    return 'Up';
                case 18 /* DownArrow */:
                    return 'Down';
                case 15 /* LeftArrow */:
                    return 'Left';
                case 17 /* RightArrow */:
                    return 'Right';
            }
            return keyCodes_1.KeyCodeUtils.toString(keyCode);
        };
        USLayoutResolvedKeybinding.prototype._getElectronAcceleratorLabelForKeybinding = function (keybinding) {
            if (!keybinding) {
                return null;
            }
            if (keybinding.isDuplicateModifierCase()) {
                return null;
            }
            return this._keyCodeToElectronAccelerator(keybinding.keyCode);
        };
        USLayoutResolvedKeybinding.prototype.getElectronAccelerator = function () {
            if (this._chordPart !== null) {
                // Electron cannot handle chords
                return null;
            }
            var firstPart = this._getElectronAcceleratorLabelForKeybinding(this._firstPart);
            return keybindingLabels_1.ElectronAcceleratorLabelProvider.toLabel(this._firstPart, firstPart, null, null, this._os);
        };
        USLayoutResolvedKeybinding.prototype._getUserSettingsLabelForKeybinding = function (keybinding) {
            if (!keybinding) {
                return null;
            }
            if (keybinding.isDuplicateModifierCase()) {
                return '';
            }
            return keyCodes_1.KeyCodeUtils.toUserSettingsUS(keybinding.keyCode);
        };
        USLayoutResolvedKeybinding.prototype.getUserSettingsLabel = function () {
            var firstPart = this._getUserSettingsLabelForKeybinding(this._firstPart);
            var chordPart = this._getUserSettingsLabelForKeybinding(this._chordPart);
            var result = keybindingLabels_1.UserSettingsLabelProvider.toLabel(this._firstPart, firstPart, this._chordPart, chordPart, this._os);
            return (result ? result.toLowerCase() : result);
        };
        USLayoutResolvedKeybinding.prototype.isWYSIWYG = function () {
            return true;
        };
        USLayoutResolvedKeybinding.prototype.isChord = function () {
            return (this._chordPart ? true : false);
        };
        USLayoutResolvedKeybinding.prototype.getParts = function () {
            return [
                this._toResolvedKeybindingPart(this._firstPart),
                this._toResolvedKeybindingPart(this._chordPart)
            ];
        };
        USLayoutResolvedKeybinding.prototype._toResolvedKeybindingPart = function (keybinding) {
            if (!keybinding) {
                return null;
            }
            return new keyCodes_1.ResolvedKeybindingPart(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, this._getUILabelForKeybinding(keybinding), this._getAriaLabelForKeybinding(keybinding));
        };
        USLayoutResolvedKeybinding.prototype.getDispatchParts = function () {
            var firstPart = this._firstPart ? USLayoutResolvedKeybinding.getDispatchStr(this._firstPart) : null;
            var chordPart = this._chordPart ? USLayoutResolvedKeybinding.getDispatchStr(this._chordPart) : null;
            return [firstPart, chordPart];
        };
        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;
    }(keyCodes_1.ResolvedKeybinding));
    exports.USLayoutResolvedKeybinding = USLayoutResolvedKeybinding;
});

define(__m[420/*vs/platform/lifecycle/common/lifecycle*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,11/*vs/base/common/event*/,16/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, winjs_base_1, event_1, instantiation_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ILifecycleService = instantiation_1.createDecorator('lifecycleService');
    var ShutdownReason;
    (function (ShutdownReason) {
        /** Window is closed */
        ShutdownReason[ShutdownReason["CLOSE"] = 1] = "CLOSE";
        /** Application is quit */
        ShutdownReason[ShutdownReason["QUIT"] = 2] = "QUIT";
        /** Window is reloaded */
        ShutdownReason[ShutdownReason["RELOAD"] = 3] = "RELOAD";
        /** Other configuration loaded into window */
        ShutdownReason[ShutdownReason["LOAD"] = 4] = "LOAD";
    })(ShutdownReason = exports.ShutdownReason || (exports.ShutdownReason = {}));
    var StartupKind;
    (function (StartupKind) {
        StartupKind[StartupKind["NewWindow"] = 1] = "NewWindow";
        StartupKind[StartupKind["ReloadedWindow"] = 3] = "ReloadedWindow";
        StartupKind[StartupKind["ReopenedWindow"] = 4] = "ReopenedWindow";
    })(StartupKind = exports.StartupKind || (exports.StartupKind = {}));
    var LifecyclePhase;
    (function (LifecyclePhase) {
        LifecyclePhase[LifecyclePhase["Starting"] = 1] = "Starting";
        LifecyclePhase[LifecyclePhase["Running"] = 2] = "Running";
        LifecyclePhase[LifecyclePhase["ShuttingDown"] = 3] = "ShuttingDown";
    })(LifecyclePhase = exports.LifecyclePhase || (exports.LifecyclePhase = {}));
    exports.NullLifecycleService = {
        _serviceBrand: null,
        phase: LifecyclePhase.Running,
        startupKind: StartupKind.NewWindow,
        onDidChangePhase: event_1.default.None,
        onWillShutdown: event_1.default.None,
        onShutdown: event_1.default.None
    };
    // Shared veto handling across main and renderer
    function handleVetos(vetos, onError) {
        if (vetos.length === 0) {
            return winjs_base_1.TPromise.as(false);
        }
        var promises = [];
        var lazyValue = false;
        for (var _i = 0, vetos_1 = vetos; _i < vetos_1.length; _i++) {
            var valueOrPromise = vetos_1[_i];
            // veto, done
            if (valueOrPromise === true) {
                return winjs_base_1.TPromise.as(true);
            }
            if (winjs_base_1.TPromise.is(valueOrPromise)) {
                promises.push(valueOrPromise.then(function (value) {
                    if (value) {
                        lazyValue = true; // veto, done
                    }
                }, function (err) {
                    onError(err); // error, treated like a veto, done
                    lazyValue = true;
                }));
            }
        }
        return winjs_base_1.TPromise.join(promises).then(function () { return lazyValue; });
    }
    exports.handleVetos = handleVetos;
});

define(__m[421/*vs/platform/markers/common/markerService*/], __M([1/*require*/,0/*exports*/,33/*vs/base/common/arrays*/,70/*vs/base/common/network*/,29/*vs/base/common/types*/,11/*vs/base/common/event*/,36/*vs/base/common/severity*/]), function (require, exports, arrays_1, network_1, types_1, event_1, severity_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var 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 = (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) {
            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 === severity_1.default.Error) {
                    result.errors += 1;
                }
                else if (severity === severity_1.default.Warning) {
                    result.warnings += 1;
                }
                else if (severity === severity_1.default.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 = (function () {
        function MarkerService() {
            this._onMarkerChanged = new event_1.Emitter();
            this._onMarkerChangedEvent = event_1.debounceEvent(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.getStatistics = function () {
            return this._stats;
        };
        MarkerService.prototype.remove = function (owner, resources) {
            if (!arrays_1.isFalsyOrEmpty(resources)) {
                for (var _i = 0, resources_2 = resources; _i < resources_2.length; _i++) {
                    var resource = resources_2[_i];
                    this.changeOne(owner, resource, undefined);
                }
            }
        };
        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;
            if (!message) {
                return undefined;
            }
            // santize data
            code = code || null;
            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
            };
        };
        MarkerService.prototype.changeAll = function (owner, data) {
            var changes = [];
            var map = this._byOwner[owner];
            // remove old marker
            if (map) {
                delete this._byOwner[owner];
                for (var resource in map) {
                    // remeber what we remove
                    var first = MapMap.get(this._byResource, resource, owner)[0];
                    if (first) {
                        changes.push(first.resource);
                    }
                    // actual remove
                    MapMap.remove(this._byResource, resource, owner);
                }
            }
            // add new markers
            if (!arrays_1.isFalsyOrEmpty(data)) {
                // group by resource
                var groups = Object.create(null);
                for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
                    var _a = data_1[_i], resource = _a.resource, markerData = _a.marker;
                    var marker = MarkerService._toMarker(owner, resource, markerData);
                    if (!marker) {
                        // filter bad markers
                        continue;
                    }
                    var array = groups[resource.toString()];
                    if (!array) {
                        groups[resource.toString()] = [marker];
                        changes.push(resource);
                    }
                    else {
                        array.push(marker);
                    }
                }
                // insert all
                for (var resource in groups) {
                    MapMap.set(this._byResource, resource, owner, groups[resource]);
                    MapMap.set(this._byOwner, owner, resource, groups[resource]);
                }
            }
            if (changes.length > 0) {
                this._onMarkerChanged.fire(changes);
            }
        };
        MarkerService.prototype.read = function (filter) {
            if (filter === void 0) { filter = Object.create(null); }
            var owner = filter.owner, resource = filter.resource, take = filter.take;
            if (!take || take < 0) {
                take = -1;
            }
            if (owner && resource) {
                // exactly one owner AND resource
                var result = MapMap.get(this._byResource, resource.toString(), owner);
                if (!result) {
                    return [];
                }
                else {
                    return result.slice(0, take > 0 ? take : undefined);
                }
            }
            else if (!owner && !resource) {
                // all
                var result = [];
                for (var key1 in this._byResource) {
                    for (var key2 in this._byResource[key1]) {
                        for (var _i = 0, _a = this._byResource[key1][key2]; _i < _a.length; _i++) {
                            var data = _a[_i];
                            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]
                    : this._byResource[resource.toString()];
                if (!map) {
                    return [];
                }
                var result = [];
                for (var key in map) {
                    for (var _b = 0, _c = map[key]; _b < _c.length; _b++) {
                        var data = _c[_b];
                        var newLen = result.push(data);
                        if (take > 0 && newLen === take) {
                            return result;
                        }
                    }
                }
                return result;
            }
        };
        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()] === void 0) {
                    MarkerService._dedupeMap[uri.toString()] = true;
                    last.push(uri);
                }
            }
            return last;
        };
        return MarkerService;
    }());
    exports.MarkerService = MarkerService;
});

define(__m[103/*vs/platform/markers/common/markers*/], __M([1/*require*/,0/*exports*/,36/*vs/base/common/severity*/,16/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, severity_1, instantiation_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var 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 !== void 0 && markerData.severity !== null) {
                result.push(severity_1.default.toString(markerData.severity));
            }
            else {
                result.push(emptyString);
            }
            if (markerData.message) {
                result.push(markerData.message.replace('¦', '\¦'));
            }
            else {
                result.push(emptyString);
            }
            if (markerData.startLineNumber !== void 0 && markerData.startLineNumber !== null) {
                result.push(markerData.startLineNumber.toString());
            }
            else {
                result.push(emptyString);
            }
            if (markerData.startColumn !== void 0 && markerData.startColumn !== null) {
                result.push(markerData.startColumn.toString());
            }
            else {
                result.push(emptyString);
            }
            if (markerData.endLineNumber !== void 0 && markerData.endLineNumber !== null) {
                result.push(markerData.endLineNumber.toString());
            }
            else {
                result.push(emptyString);
            }
            if (markerData.endColumn !== void 0 && 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');
});

define(__m[50/*vs/platform/message/common/message*/], __M([1/*require*/,0/*exports*/,384/*vs/nls!vs/platform/message/common/message*/,7/*vs/base/common/winjs.base*/,36/*vs/base/common/severity*/,16/*vs/platform/instantiation/common/instantiation*/,53/*vs/base/common/actions*/]), function (require, exports, nls, winjs_base_1, severity_1, instantiation_1, actions_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CloseAction = new actions_1.Action('close.message', nls.localize(0, null), null, true, function () { return winjs_base_1.TPromise.as(true); });
    exports.LaterAction = new actions_1.Action('later.message', nls.localize(1, null), null, true, function () { return winjs_base_1.TPromise.as(true); });
    exports.CancelAction = new actions_1.Action('cancel.message', nls.localize(2, null), null, true, function () { return winjs_base_1.TPromise.as(true); });
    exports.IMessageService = instantiation_1.createDecorator('messageService');
    exports.IChoiceService = instantiation_1.createDecorator('choiceService');
    exports.Severity = severity_1.default;
});

define(__m[71/*vs/platform/opener/common/opener*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,16/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, winjs_base_1, instantiation_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IOpenerService = instantiation_1.createDecorator('openerService');
    exports.NullOpenerService = Object.freeze({
        _serviceBrand: undefined,
        open: function () { return winjs_base_1.TPromise.as(undefined); }
    });
});











define(__m[425/*vs/editor/contrib/hover/browser/modesGlyphHover*/], __M([1/*require*/,0/*exports*/,195/*vs/editor/contrib/hover/browser/hoverOperation*/,196/*vs/editor/contrib/hover/browser/hoverWidgets*/,4/*vs/base/browser/dom*/,102/*vs/base/browser/htmlContentRenderer*/,71/*vs/platform/opener/common/opener*/,24/*vs/base/common/uri*/,10/*vs/base/common/errors*/,122/*vs/editor/common/modes/textToHtmlTokenizer*/]), function (require, exports, hoverOperation_1, hoverWidgets_1, dom_1, htmlContentRenderer_1, opener_1, uri_1, errors_1, textToHtmlTokenizer_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MarginComputer = (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 hasHoverContent = function (contents) {
                return contents && (!Array.isArray(contents) || contents.length > 0);
            };
            var toHoverMessage = function (contents) {
                return {
                    value: contents
                };
            };
            var lineDecorations = this._editor.getLineDecorations(this._lineNumber);
            var result = [];
            for (var i = 0, len = lineDecorations.length; i < len; i++) {
                var d = lineDecorations[i];
                if (!d.options.glyphMarginClassName) {
                    continue;
                }
                var hoverMessage = d.options.glyphMarginHoverMessage;
                if (!hasHoverContent(hoverMessage)) {
                    continue;
                }
                if (Array.isArray(hoverMessage)) {
                    result = result.concat(hoverMessage.map(toHoverMessage));
                }
                else {
                    result.push(toHoverMessage(hoverMessage));
                }
            }
            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 = (function (_super) {
        __extends(ModesGlyphHoverWidget, _super);
        function ModesGlyphHoverWidget(editor, openerService, modeService) {
            var _this = _super.call(this, ModesGlyphHoverWidget.ID, editor) || this;
            _this.openerService = openerService;
            _this.modeService = modeService;
            _this.openerService = openerService || opener_1.NullOpenerService;
            _this._lastLineNumber = -1;
            _this._computer = new MarginComputer(_this._editor);
            _this._hoverOperation = new hoverOperation_1.HoverOperation(_this._computer, function (result) { return _this._withResult(result); }, null, function (result) { return _this._withResult(result); });
            return _this;
        }
        ModesGlyphHoverWidget.prototype.dispose = function () {
            this._hoverOperation.cancel();
            _super.prototype.dispose.call(this);
        };
        ModesGlyphHoverWidget.prototype.onModelDecorationsChanged = function () {
            if (this.isVisible) {
                // The decorations have changed and the hover is visible,
                // we need to recompute the displayed text
                this._hoverOperation.cancel();
                this._computer.clearResult();
                this._hoverOperation.start();
            }
        };
        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();
        };
        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;
            var fragment = document.createDocumentFragment();
            messages.forEach(function (msg) {
                var renderedContents = htmlContentRenderer_1.renderMarkedString(msg.value, {
                    actionCallback: function (content) { return _this.openerService.open(uri_1.default.parse(content)).then(undefined, errors_1.onUnexpectedError); },
                    codeBlockRenderer: function (languageAlias, value) {
                        // In markdown, it is possible that we stumble upon language aliases (e.g. js instead of javascript)
                        var modeId = _this.modeService.getModeIdForLanguageName(languageAlias);
                        return _this.modeService.getOrCreateMode(modeId).then(function (_) {
                            return textToHtmlTokenizer_1.tokenizeToString(value, modeId);
                        });
                    }
                });
                fragment.appendChild(dom_1.$('div.hover-row', null, renderedContents));
            });
            this.updateContents(fragment);
            this.showAt(lineNumber);
        };
        ModesGlyphHoverWidget.ID = 'editor.contrib.modesGlyphHoverWidget';
        return ModesGlyphHoverWidget;
    }(hoverWidgets_1.GlyphHoverWidget));
    exports.ModesGlyphHoverWidget = ModesGlyphHoverWidget;
});

define(__m[163/*vs/platform/progress/common/progress*/], __M([1/*require*/,0/*exports*/,16/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IProgressService = instantiation_1.createDecorator('progressService');
    exports.emptyProgress = Object.freeze({ report: function () { } });
    var Progress = (function () {
        function Progress(callback) {
            this._callback = callback;
        }
        Object.defineProperty(Progress.prototype, "value", {
            get: function () {
                return this._value;
            },
            enumerable: true,
            configurable: true
        });
        Progress.prototype.report = function (item) {
            this._value = item;
            this._callback();
        };
        return Progress;
    }());
    exports.Progress = Progress;
    var ProgressLocation;
    (function (ProgressLocation) {
        ProgressLocation[ProgressLocation["Scm"] = 1] = "Scm";
        ProgressLocation[ProgressLocation["Window"] = 10] = "Window";
    })(ProgressLocation = exports.ProgressLocation || (exports.ProgressLocation = {}));
    exports.IProgressService2 = instantiation_1.createDecorator('progressService2');
});

define(__m[44/*vs/platform/registry/common/platform*/], __M([1/*require*/,0/*exports*/,29/*vs/base/common/types*/,72/*vs/base/common/assert*/]), function (require, exports, Types, Assert) {
    /*---------------------------------------------------------------------------------------------
     *  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 RegistryImpl = (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.knows = function (id) {
            return this.data.hasOwnProperty(id);
        };
        RegistryImpl.prototype.as = function (id) {
            return this.data[id] || null;
        };
        return RegistryImpl;
    }());
    exports.Registry = new RegistryImpl();
    /**
     * A base class for registries that leverage the instantiation service to create instances.
     */
    var BaseRegistry = (function () {
        function BaseRegistry() {
            this.toBeInstantiated = [];
            this.instances = [];
        }
        BaseRegistry.prototype.setInstantiationService = function (service) {
            this.instantiationService = service;
            while (this.toBeInstantiated.length > 0) {
                var entry = this.toBeInstantiated.shift();
                this.instantiate(entry);
            }
        };
        BaseRegistry.prototype.instantiate = function (ctor) {
            var instance = this.instantiationService.createInstance(ctor);
            this.instances.push(instance);
        };
        BaseRegistry.prototype._register = function (ctor) {
            if (this.instantiationService) {
                this.instantiate(ctor);
            }
            else {
                this.toBeInstantiated.push(ctor);
            }
        };
        BaseRegistry.prototype._getInstances = function () {
            return this.instances.slice(0);
        };
        BaseRegistry.prototype._setInstances = function (instances) {
            this.instances = instances;
        };
        return BaseRegistry;
    }());
    exports.BaseRegistry = BaseRegistry;
});

define(__m[30/*vs/editor/browser/editorBrowserExtensions*/], __M([1/*require*/,0/*exports*/,44/*vs/platform/registry/common/platform*/]), function (require, exports, platform_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function editorContribution(ctor) {
        EditorContributionRegistry.INSTANCE.registerEditorBrowserContribution(ctor);
    }
    exports.editorContribution = editorContribution;
    var EditorBrowserRegistry;
    (function (EditorBrowserRegistry) {
        function getEditorContributions() {
            return EditorContributionRegistry.INSTANCE.getEditorBrowserContributions();
        }
        EditorBrowserRegistry.getEditorContributions = getEditorContributions;
    })(EditorBrowserRegistry = exports.EditorBrowserRegistry || (exports.EditorBrowserRegistry = {}));
    var Extensions = {
        EditorContributions: 'editor.contributions'
    };
    var EditorContributionRegistry = (function () {
        function EditorContributionRegistry() {
            this.editorContributions = [];
        }
        EditorContributionRegistry.prototype.registerEditorBrowserContribution = function (ctor) {
            this.editorContributions.push(ctor);
        };
        EditorContributionRegistry.prototype.getEditorBrowserContributions = function () {
            return this.editorContributions.slice(0);
        };
        EditorContributionRegistry.INSTANCE = new EditorContributionRegistry();
        return EditorContributionRegistry;
    }());
    platform_1.Registry.add(Extensions.EditorContributions, EditorContributionRegistry.INSTANCE);
});

define(__m[126/*vs/editor/common/modes/modesRegistry*/], __M([1/*require*/,0/*exports*/,336/*vs/nls!vs/editor/common/modes/modesRegistry*/,11/*vs/base/common/event*/,44/*vs/platform/registry/common/platform*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/,17/*vs/editor/common/modes*/]), function (require, exports, nls, event_1, platform_1, languageConfigurationRegistry_1, modes_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    // Define extension point ids
    exports.Extensions = {
        ModesRegistry: 'editor.modesRegistry'
    };
    var EditorModesRegistry = (function () {
        function EditorModesRegistry() {
            this._onDidAddLanguages = new event_1.Emitter();
            this.onDidAddLanguages = this._onDidAddLanguages.event;
            this._languages = [];
        }
        // --- languages
        EditorModesRegistry.prototype.registerLanguage = function (def) {
            this._languages.push(def);
            this._onDidAddLanguages.fire([def]);
        };
        EditorModesRegistry.prototype.registerLanguages = function (def) {
            this._languages = this._languages.concat(def);
            this._onDidAddLanguages.fire(def);
        };
        EditorModesRegistry.prototype.getLanguages = function () {
            return this._languages.slice(0);
        };
        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: [
            ['(', ')'],
            ['[', ']'],
            ['{', '}'],
        ]
    });
});










define(__m[430/*vs/editor/common/services/modelServiceImpl*/], __M([1/*require*/,0/*exports*/,339/*vs/nls!vs/editor/common/services/modelServiceImpl*/,70/*vs/base/common/network*/,11/*vs/base/common/event*/,36/*vs/base/common/severity*/,7/*vs/base/common/winjs.base*/,103/*vs/platform/markers/common/markers*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,175/*vs/editor/common/model/model*/,15/*vs/base/common/platform*/,62/*vs/platform/configuration/common/configuration*/,49/*vs/editor/common/config/editorOptions*/,126/*vs/editor/common/modes/modesRegistry*/,101/*vs/editor/common/model/textSource*/,55/*vs/editor/common/model/textModelEvents*/,34/*vs/editor/common/model/textModelWithDecorations*/]), function (require, exports, nls, network, event_1, severity_1, winjs_base_1, markers_1, range_1, editorCommon, model_1, platform, configuration_1, editorOptions_1, modesRegistry_1, textSource_1, textModelEvents, textModelWithDecorations_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function MODEL_ID(resource) {
        return resource.toString();
    }
    var ModelData = (function () {
        function ModelData(model, eventsHandler) {
            var _this = this;
            this.model = model;
            this._markerDecorations = [];
            this._modelEventsListener = model.addBulkListener(function (events) { return eventsHandler(_this, events); });
        }
        ModelData.prototype.dispose = function () {
            this._markerDecorations = this.model.deltaDecorations(this._markerDecorations, []);
            this._modelEventsListener.dispose();
            this._modelEventsListener = null;
            this.model = null;
        };
        ModelData.prototype.getModelId = function () {
            return MODEL_ID(this.model.uri);
        };
        ModelData.prototype.acceptMarkerDecorations = function (newDecorations) {
            this._markerDecorations = this.model.deltaDecorations(this._markerDecorations, newDecorations);
        };
        return ModelData;
    }());
    var ModelMarkerHandler = (function () {
        function ModelMarkerHandler() {
        }
        ModelMarkerHandler.setMarkers = function (modelData, markerService) {
            var _this = this;
            // Limit to the first 500 errors/warnings
            var markers = markerService.read({ resource: modelData.model.uri, take: 500 });
            var newModelDecorations = markers.map(function (marker) {
                return {
                    range: _this._createDecorationRange(modelData.model, marker),
                    options: _this._createDecorationOption(marker)
                };
            });
            modelData.acceptMarkerDecorations(newModelDecorations);
        };
        ModelMarkerHandler._createDecorationRange = function (model, rawMarker) {
            var marker = model.validateRange(new range_1.Range(rawMarker.startLineNumber, rawMarker.startColumn, rawMarker.endLineNumber, rawMarker.endColumn));
            var ret = new range_1.Range(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn);
            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(marker.startLineNumber) ||
                        model.getLineMaxColumn(marker.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;
        };
        ModelMarkerHandler._createDecorationOption = function (marker) {
            var className;
            var color;
            var darkColor;
            var hcColor;
            switch (marker.severity) {
                case severity_1.default.Ignore:
                    // do something
                    break;
                case severity_1.default.Warning:
                case severity_1.default.Info:
                    className = textModelWithDecorations_1.ClassName.EditorWarningDecoration;
                    color = 'rgba(18,136,18,0.7)';
                    darkColor = 'rgba(18,136,18,0.7)';
                    hcColor = 'rgba(50,255,50,1)';
                    break;
                case severity_1.default.Error:
                default:
                    className = textModelWithDecorations_1.ClassName.EditorErrorDecoration;
                    color = 'rgba(255,18,18,0.7)';
                    darkColor = 'rgba(255,18,18,0.7)';
                    hcColor = 'rgba(255,50,50,1)';
                    break;
            }
            var hoverMessage = null;
            var message = marker.message, source = marker.source;
            if (typeof message === 'string') {
                message = message.trim();
                if (source) {
                    if (/\n/g.test(message)) {
                        message = nls.localize(0, null, source, message);
                    }
                    else {
                        message = nls.localize(1, null, source, message);
                    }
                }
                hoverMessage = [{ language: '_', value: message }];
            }
            return {
                stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
                className: className,
                hoverMessage: hoverMessage,
                showIfCollapsed: true,
                overviewRuler: {
                    color: color,
                    darkColor: darkColor,
                    hcColor: hcColor,
                    position: editorCommon.OverviewRulerLane.Right
                }
            };
        };
        return ModelMarkerHandler;
    }());
    var DEFAULT_EOL = (platform.isLinux || platform.isMacintosh) ? editorCommon.DefaultEndOfLine.LF : editorCommon.DefaultEndOfLine.CRLF;
    var ModelServiceImpl = (function () {
        function ModelServiceImpl(markerService, configurationService) {
            var _this = this;
            this._markerService = markerService;
            this._configurationService = configurationService;
            this._models = {};
            this._modelCreationOptionsByLanguage = Object.create(null);
            this._onModelAdded = new event_1.Emitter();
            this._onModelRemoved = new event_1.Emitter();
            this._onModelModeChanged = new event_1.Emitter();
            if (this._markerService) {
                this._markerServiceSubscription = this._markerService.onMarkerChanged(this._handleMarkerChange, this);
            }
            this._configurationServiceSubscription = this._configurationService.onDidUpdateConfiguration(function (e) { return _this._updateModelOptions(); });
            this._updateModelOptions();
        }
        ModelServiceImpl._readModelOptions = function (config) {
            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;
                }
            }
            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.files && config.files.eol; // TODO@Sandeep (https://github.com/Microsoft/vscode/issues/29119)
            if (eol === '\r\n') {
                newDefaultEOL = editorCommon.DefaultEndOfLine.CRLF;
            }
            else if (eol === '\n') {
                newDefaultEOL = editorCommon.DefaultEndOfLine.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));
            }
            return {
                tabSize: tabSize,
                insertSpaces: insertSpaces,
                detectIndentation: detectIndentation,
                defaultEOL: newDefaultEOL,
                trimAutoWhitespace: trimAutoWhitespace
            };
        };
        ModelServiceImpl.prototype.getCreationOptions = function (language) {
            var creationOptions = this._modelCreationOptionsByLanguage[language];
            if (!creationOptions) {
                creationOptions = ModelServiceImpl._readModelOptions(this._configurationService.getConfiguration(null, { overrideIdentifier: language }));
                this._modelCreationOptionsByLanguage[language] = creationOptions;
            }
            return creationOptions;
        };
        ModelServiceImpl.prototype._updateModelOptions = function () {
            var oldOptionsByLanguage = this._modelCreationOptionsByLanguage;
            this._modelCreationOptionsByLanguage = 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 oldOptions = oldOptionsByLanguage[language];
                var newOptions = this.getCreationOptions(language);
                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.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,
                    trimAutoWhitespace: newOptions.trimAutoWhitespace
                });
            }
        };
        ModelServiceImpl.prototype.dispose = function () {
            if (this._markerServiceSubscription) {
                this._markerServiceSubscription.dispose();
            }
            this._configurationServiceSubscription.dispose();
        };
        ModelServiceImpl.prototype._handleMarkerChange = function (changedResources) {
            var _this = this;
            changedResources.forEach(function (resource) {
                var modelId = MODEL_ID(resource);
                var modelData = _this._models[modelId];
                if (!modelData) {
                    return;
                }
                ModelMarkerHandler.setMarkers(modelData, _this._markerService);
            });
        };
        ModelServiceImpl.prototype._cleanUp = function (model) {
            var _this = this;
            // clean up markers for internal, transient models
            if (model.uri.scheme === network.Schemas.inMemory
                || model.uri.scheme === network.Schemas.internal
                || model.uri.scheme === network.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]); });
                }
            }
        };
        // --- begin IModelService
        ModelServiceImpl.prototype._createModelData = function (value, languageIdentifier, resource) {
            var _this = this;
            // create & save the model
            var options = this.getCreationOptions(languageIdentifier.language);
            var rawTextSource = (typeof value === 'string' ? textSource_1.RawTextSource.fromString(value) : value);
            var model = new model_1.Model(rawTextSource, 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 (modelData, events) { return _this._onModelEvents(modelData, events); });
            this._models[modelId] = modelData;
            return modelData;
        };
        ModelServiceImpl.prototype.updateModel = function (model, value) {
            var options = this.getCreationOptions(model.getLanguageIdentifier().language);
            var textSource = textSource_1.TextSource.create(value, options.defaultEOL);
            // Return early if the text is already set in that form
            if (model.equals(textSource)) {
                return;
            }
            // Otherwise update model
            model.setValueFromTextSource(textSource);
        };
        ModelServiceImpl.prototype.createModel = function (value, modeOrPromise, resource) {
            var modelData;
            if (!modeOrPromise || winjs_base_1.TPromise.is(modeOrPromise)) {
                modelData = this._createModelData(value, modesRegistry_1.PLAINTEXT_LANGUAGE_IDENTIFIER, resource);
                this.setMode(modelData.model, modeOrPromise);
            }
            else {
                modelData = this._createModelData(value, modeOrPromise.getLanguageIdentifier(), resource);
            }
            // handle markers (marker service => model)
            if (this._markerService) {
                ModelMarkerHandler.setMarkers(modelData, this._markerService);
            }
            this._onModelAdded.fire(modelData.model);
            return modelData.model;
        };
        ModelServiceImpl.prototype.setMode = function (model, modeOrPromise) {
            if (!modeOrPromise) {
                return;
            }
            if (winjs_base_1.TPromise.is(modeOrPromise)) {
                modeOrPromise.then(function (mode) {
                    if (!model.isDisposed()) {
                        model.setMode(mode.getLanguageIdentifier());
                    }
                });
            }
            else {
                model.setMode(modeOrPromise.getLanguageIdentifier());
            }
        };
        ModelServiceImpl.prototype.destroyModel = function (resource) {
            // We need to support that not all models get disposed through this service (i.e. model.dispose() should work!)
            var modelData = this._models[MODEL_ID(resource)];
            if (!modelData) {
                return;
            }
            modelData.model.dispose();
        };
        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;
        };
        Object.defineProperty(ModelServiceImpl.prototype, "onModelAdded", {
            get: function () {
                return this._onModelAdded ? this._onModelAdded.event : null;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ModelServiceImpl.prototype, "onModelRemoved", {
            get: function () {
                return this._onModelRemoved ? this._onModelRemoved.event : null;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ModelServiceImpl.prototype, "onModelModeChanged", {
            get: function () {
                return this._onModelModeChanged ? this._onModelModeChanged.event : null;
            },
            enumerable: true,
            configurable: true
        });
        // --- end IModelService
        ModelServiceImpl.prototype._onModelDisposing = function (model) {
            var modelId = MODEL_ID(model.uri);
            var modelData = this._models[modelId];
            delete this._models[modelId];
            modelData.dispose();
            this._cleanUp(model);
            this._onModelRemoved.fire(model);
        };
        ModelServiceImpl.prototype._onModelEvents = function (modelData, events) {
            // First look for dispose
            for (var i = 0, len = events.length; i < len; i++) {
                var e = events[i];
                if (e.type === textModelEvents.TextModelEventType.ModelDispose) {
                    this._onModelDisposing(modelData.model);
                    // no more processing since model got disposed
                    return;
                }
            }
            // Second, look for mode change
            for (var i = 0, len = events.length; i < len; i++) {
                var e = events[i];
                if (e.type === textModelEvents.TextModelEventType.ModelLanguageChanged) {
                    var model = modelData.model;
                    var oldModeId = e.data.oldLanguage;
                    var newModeId = model.getLanguageIdentifier().language;
                    var oldOptions = this.getCreationOptions(oldModeId);
                    var newOptions = this.getCreationOptions(newModeId);
                    ModelServiceImpl._setModelOptionsForModel(model, newOptions, oldOptions);
                    this._onModelModeChanged.fire({ model: model, oldModeId: oldModeId });
                }
            }
        };
        ModelServiceImpl = __decorate([
            __param(0, markers_1.IMarkerService),
            __param(1, configuration_1.IConfigurationService)
        ], ModelServiceImpl);
        return ModelServiceImpl;
    }());
    exports.ModelServiceImpl = ModelServiceImpl;
});

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






define(__m[431/*vs/editor/contrib/dnd/browser/dnd*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,15/*vs/base/common/platform*/,25/*vs/editor/browser/editorBrowser*/,30/*vs/editor/browser/editorBrowserExtensions*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,251/*vs/editor/contrib/dnd/common/dragAndDropCommand*/,34/*vs/editor/common/model/textModelWithDecorations*/,325/*vs/css!vs/editor/contrib/dnd/browser/dnd*/]), function (require, exports, lifecycle_1, platform_1, editorBrowser_1, editorBrowserExtensions_1, position_1, range_1, selection_1, dragAndDropCommand_1, textModelWithDecorations_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var DragAndDropController = (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._dndDecorationIds = [];
            this._mouseDown = false;
            this._modiferPressed = false;
            this._dragSelection = null;
        }
        DragAndDropController_1 = DragAndDropController;
        DragAndDropController.get = function (editor) {
            return editor.getContribution(DragAndDropController_1.ID);
        };
        DragAndDropController.prototype.onEditorKeyDown = function (e) {
            if (!this._editor.getConfiguration().dragAndDrop) {
                return;
            }
            if (e[DragAndDropController_1.TRIGGER_MODIFIER]) {
                this._modiferPressed = true;
            }
            if (this._mouseDown && e[DragAndDropController_1.TRIGGER_MODIFIER]) {
                this._editor.updateOptions({
                    mouseStyle: 'copy'
                });
            }
        };
        DragAndDropController.prototype.onEditorKeyUp = function (e) {
            if (!this._editor.getConfiguration().dragAndDrop) {
                return;
            }
            if (e[DragAndDropController_1.TRIGGER_MODIFIER]) {
                this._modiferPressed = false;
            }
            if (this._mouseDown && e.keyCode === DragAndDropController_1.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 possibleSelections = this._editor.getSelections().filter(function (selection) { return selection.containsPosition(target.position); });
                if (possibleSelections.length === 1) {
                    this._dragSelection = possibleSelections[0];
                }
                else {
                    return;
                }
            }
            if (mouseEvent.event[DragAndDropController_1.TRIGGER_MODIFIER]) {
                this._editor.updateOptions({
                    mouseStyle: 'copy'
                });
            }
            else {
                this._editor.updateOptions({
                    mouseStyle: 'default'
                });
            }
            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 = 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;
                        }
                    });
                    this._editor.setSelections(newSelections);
                }
                else if (!this._dragSelection.containsPosition(newCursorPosition_1) ||
                    ((mouseEvent.event[DragAndDropController_1.TRIGGER_MODIFIER] ||
                        this._modiferPressed) && (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_1.ID, new dragAndDropCommand_1.DragAndDropCommand(this._dragSelection, newCursorPosition_1, mouseEvent.event[DragAndDropController_1.TRIGGER_MODIFIER] || this._modiferPressed));
                    this._editor.pushUndoStop();
                }
            }
            this._editor.updateOptions({
                mouseStyle: 'text'
            });
            this._removeDecoration();
            this._dragSelection = null;
            this._mouseDown = false;
        };
        DragAndDropController.prototype.showAt = function (position) {
            var _this = this;
            this._editor.changeDecorations(function (changeAccessor) {
                var newDecorations = [];
                newDecorations.push({
                    range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column),
                    options: DragAndDropController_1._DECORATION_OPTIONS
                });
                _this._dndDecorationIds = changeAccessor.deltaDecorations(_this._dndDecorationIds, newDecorations);
            });
            this._editor.revealPosition(position);
        };
        DragAndDropController.prototype._removeDecoration = function () {
            var _this = this;
            this._editor.changeDecorations(function (changeAccessor) {
                changeAccessor.deltaDecorations(_this._dndDecorationIds, []);
            });
        };
        DragAndDropController.prototype._hitContent = function (target) {
            return target.type === editorBrowser_1.MouseTargetType.CONTENT_TEXT ||
                target.type === editorBrowser_1.MouseTargetType.CONTENT_EMPTY;
        };
        DragAndDropController.prototype._hitMargin = function (target) {
            return target.type === editorBrowser_1.MouseTargetType.GUTTER_GLYPH_MARGIN ||
                target.type === editorBrowser_1.MouseTargetType.GUTTER_LINE_NUMBERS ||
                target.type === editorBrowser_1.MouseTargetType.GUTTER_LINE_DECORATIONS;
        };
        DragAndDropController.prototype.getId = function () {
            return DragAndDropController_1.ID;
        };
        DragAndDropController.prototype.dispose = function () {
            this._removeDecoration();
            this._dragSelection = null;
            this._mouseDown = false;
            this._modiferPressed = false;
            this._toUnhook = lifecycle_1.dispose(this._toUnhook);
        };
        DragAndDropController.ID = 'editor.contrib.dragAndDrop';
        DragAndDropController.TRIGGER_MODIFIER = platform_1.isMacintosh ? 'altKey' : 'ctrlKey';
        DragAndDropController.TRIGGER_KEY_VALUE = platform_1.isMacintosh ? 6 /* Alt */ : 5 /* Ctrl */;
        DragAndDropController._DECORATION_OPTIONS = textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'dnd-target'
        });
        DragAndDropController = DragAndDropController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution
        ], DragAndDropController);
        return DragAndDropController;
        var DragAndDropController_1;
    }());
    exports.DragAndDropController = 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[432/*vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,28/*vs/base/browser/browser*/,4/*vs/base/browser/dom*/,25/*vs/editor/browser/editorBrowser*/,30/*vs/editor/browser/editorBrowserExtensions*/,402/*vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/]), function (require, exports, lifecycle_1, browser, dom, editorBrowser_1, editorBrowserExtensions_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var IPadShowKeyboard = (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_1 = IPadShowKeyboard;
        IPadShowKeyboard.prototype.update = function () {
            var hasWidget = (!!this.widget);
            var shouldHaveWidget = (!this.editor.getConfiguration().readOnly);
            if (!hasWidget && shouldHaveWidget) {
                this.widget = new ShowKeyboardWidget(this.editor);
            }
            else if (hasWidget && !shouldHaveWidget) {
                this.widget.dispose();
                this.widget = null;
            }
        };
        IPadShowKeyboard.prototype.getId = function () {
            return IPadShowKeyboard_1.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';
        IPadShowKeyboard = IPadShowKeyboard_1 = __decorate([
            editorBrowserExtensions_1.editorContribution
        ], IPadShowKeyboard);
        return IPadShowKeyboard;
        var IPadShowKeyboard_1;
    }());
    exports.IPadShowKeyboard = IPadShowKeyboard;
    var ShowKeyboardWidget = (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: editorBrowser_1.OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER
            };
        };
        ShowKeyboardWidget.ID = 'editor.contrib.ShowKeyboardWidget';
        return ShowKeyboardWidget;
    }());
});

define(__m[433/*vs/platform/jsonschemas/common/jsonContributionRegistry*/], __M([1/*require*/,0/*exports*/,44/*vs/platform/registry/common/platform*/,38/*vs/base/common/eventEmitter*/]), function (require, exports, platform, eventEmitter_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.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 = (function () {
        function JSONContributionRegistry() {
            this.schemasById = {};
            this.eventEmitter = new eventEmitter_1.EventEmitter();
        }
        JSONContributionRegistry.prototype.addRegistryChangedListener = function (callback) {
            return this.eventEmitter.addListener('registryChanged', callback);
        };
        JSONContributionRegistry.prototype.registerSchema = function (uri, unresolvedSchemaContent) {
            this.schemasById[normalizeId(uri)] = unresolvedSchemaContent;
            this.eventEmitter.emit('registryChanged', {});
        };
        JSONContributionRegistry.prototype.getSchemaContributions = function () {
            return {
                schemas: this.schemasById,
            };
        };
        return JSONContributionRegistry;
    }());
    var jsonContributionRegistry = new JSONContributionRegistry();
    platform.Registry.add(exports.Extensions.JSONContribution, jsonContributionRegistry);
});

define(__m[127/*vs/platform/configuration/common/configurationRegistry*/], __M([1/*require*/,0/*exports*/,382/*vs/nls!vs/platform/configuration/common/configurationRegistry*/,11/*vs/base/common/event*/,44/*vs/platform/registry/common/platform*/,29/*vs/base/common/types*/,9/*vs/base/common/strings*/,433/*vs/platform/jsonschemas/common/jsonContributionRegistry*/]), function (require, exports, nls, event_1, platform_1, types, strings, jsonContributionRegistry_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Extensions = {
        Configuration: 'base.contributions.configuration'
    };
    var ConfigurationScope;
    (function (ConfigurationScope) {
        ConfigurationScope[ConfigurationScope["WINDOW"] = 1] = "WINDOW";
        ConfigurationScope[ConfigurationScope["RESOURCE"] = 2] = "RESOURCE";
    })(ConfigurationScope = exports.ConfigurationScope || (exports.ConfigurationScope = {}));
    exports.schemaId = 'vscode://schemas/settings';
    exports.editorConfigurationSchemaId = 'vscode://schemas/settings/editor';
    exports.resourceConfigurationSchemaId = 'vscode://schemas/settings/resource';
    var contributionRegistry = platform_1.Registry.as(jsonContributionRegistry_1.Extensions.JSONContribution);
    var ConfigurationRegistry = (function () {
        function ConfigurationRegistry() {
            this.overrideIdentifiers = [];
            this.configurationContributors = [];
            this.configurationSchema = { properties: {}, patternProperties: {}, additionalProperties: false, errorMessage: 'Unknown configuration setting' };
            this.editorConfigurationSchema = { properties: {}, patternProperties: {}, additionalProperties: false, errorMessage: 'Unknown editor configuration setting' };
            this.resourceConfigurationSchema = { properties: {}, patternProperties: {}, additionalProperties: false, errorMessage: 'Not a resource configuration setting' };
            this._onDidRegisterConfiguration = new event_1.Emitter();
            this.configurationProperties = {};
            this.computeOverridePropertyPattern();
            contributionRegistry.registerSchema(exports.schemaId, this.configurationSchema);
            contributionRegistry.registerSchema(exports.editorConfigurationSchemaId, this.editorConfigurationSchema);
            contributionRegistry.registerSchema(exports.resourceConfigurationSchemaId, this.resourceConfigurationSchema);
        }
        Object.defineProperty(ConfigurationRegistry.prototype, "onDidRegisterConfiguration", {
            get: function () {
                return this._onDidRegisterConfiguration.event;
            },
            enumerable: true,
            configurable: true
        });
        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; }
            configurations.forEach(function (configuration) {
                _this.validateAndRegisterProperties(configuration, validate); // fills in defaults
                _this.configurationContributors.push(configuration);
                _this.registerJSONConfiguration(configuration);
                _this.updateSchemaForOverrideSettingsConfiguration(configuration);
            });
            this._onDidRegisterConfiguration.fire(this);
        };
        ConfigurationRegistry.prototype.registerOverrideIdentifiers = function (overrideIdentifiers) {
            (_a = this.overrideIdentifiers).push.apply(_a, overrideIdentifiers);
            this.updateOverridePropertyPatternKey();
            var _a;
        };
        ConfigurationRegistry.prototype.registerDefaultConfigurations = function (defaultConfigurations) {
            var configurationNode = {
                id: 'defaultOverrides',
                title: nls.localize(0, null),
                properties: {}
            };
            for (var _i = 0, defaultConfigurations_1 = defaultConfigurations; _i < defaultConfigurations_1.length; _i++) {
                var defaultConfiguration = defaultConfigurations_1[_i];
                for (var key in defaultConfiguration.defaults) {
                    var defaultValue = defaultConfiguration.defaults[key];
                    if (exports.OVERRIDE_PROPERTY_PATTERN.test(key) && typeof defaultValue === 'object') {
                        configurationNode.properties[key] = {
                            type: 'object',
                            default: defaultValue,
                            description: nls.localize(1, null, key),
                            $ref: exports.editorConfigurationSchemaId
                        };
                    }
                }
            }
            if (Object.keys(configurationNode.properties).length) {
                this.registerConfiguration(configurationNode, false);
            }
        };
        ConfigurationRegistry.prototype.validateAndRegisterProperties = function (configuration, validate, scope, overridable) {
            if (validate === void 0) { validate = true; }
            if (scope === void 0) { scope = ConfigurationScope.WINDOW; }
            if (overridable === void 0) { overridable = false; }
            scope = configuration.scope !== void 0 && configuration.scope !== null ? configuration.scope : scope;
            overridable = configuration.overridable || overridable;
            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 (property.scope === void 0) {
                        property.scope = scope;
                    }
                    // add to properties map
                    this.configurationProperties[key] = properties[key];
                }
            }
            var subNodes = configuration.allOf;
            if (subNodes) {
                for (var _i = 0, subNodes_1 = subNodes; _i < subNodes_1.length; _i++) {
                    var node = subNodes_1[_i];
                    this.validateAndRegisterProperties(node, validate, scope, overridable);
                }
            }
        };
        ConfigurationRegistry.prototype.validateProperty = function (property) {
            return !exports.OVERRIDE_PROPERTY_PATTERN.test(property) && this.getConfigurationProperties()[property] !== void 0;
        };
        ConfigurationRegistry.prototype.getConfigurations = function () {
            return this.configurationContributors;
        };
        ConfigurationRegistry.prototype.getConfigurationProperties = function () {
            return this.configurationProperties;
        };
        ConfigurationRegistry.prototype.registerJSONConfiguration = function (configuration) {
            var configurationSchema = this.configurationSchema;
            function register(configuration) {
                var properties = configuration.properties;
                if (properties) {
                    for (var key in properties) {
                        configurationSchema.properties[key] = properties[key];
                    }
                }
                var subNodes = configuration.allOf;
                if (subNodes) {
                    subNodes.forEach(register);
                }
            }
            ;
            register(configuration);
            contributionRegistry.registerSchema(exports.schemaId, configurationSchema);
        };
        ConfigurationRegistry.prototype.updateSchemaForOverrideSettingsConfiguration = function (configuration) {
            if (configuration.id !== SETTINGS_OVERRRIDE_NODE_ID) {
                this.update(configuration);
                contributionRegistry.registerSchema(exports.editorConfigurationSchemaId, this.editorConfigurationSchema);
                contributionRegistry.registerSchema(exports.resourceConfigurationSchemaId, this.resourceConfigurationSchema);
            }
        };
        ConfigurationRegistry.prototype.updateOverridePropertyPatternKey = function () {
            var patternProperties = this.configurationSchema.patternProperties[this.overridePropertyPattern];
            if (!patternProperties) {
                patternProperties = {
                    type: 'object',
                    description: nls.localize(2, null),
                    errorMessage: 'Unknown Identifier. Use language identifiers',
                    $ref: exports.editorConfigurationSchemaId
                };
            }
            delete this.configurationSchema.patternProperties[this.overridePropertyPattern];
            this.computeOverridePropertyPattern();
            this.configurationSchema.patternProperties[this.overridePropertyPattern] = patternProperties;
            contributionRegistry.registerSchema(exports.schemaId, this.configurationSchema);
        };
        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];
                    }
                    switch (properties[key].scope) {
                        case ConfigurationScope.RESOURCE:
                            this.resourceConfigurationSchema.properties[key] = this.getConfigurationProperties()[key];
                            break;
                    }
                }
            }
            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;
        }
    }
    var configurationRegistry = new ConfigurationRegistry();
    platform_1.Registry.add(exports.Extensions.Configuration, configurationRegistry);
    function validateProperty(property) {
        if (exports.OVERRIDE_PROPERTY_PATTERN.test(property)) {
            return nls.localize(3, null, property);
        }
        if (configurationRegistry.getConfigurationProperties()[property] !== void 0) {
            return nls.localize(4, null, property);
        }
        return null;
    }
    exports.validateProperty = validateProperty;
});











define(__m[168/*vs/editor/common/config/commonEditorConfig*/], __M([1/*require*/,0/*exports*/,304/*vs/nls!vs/editor/common/config/commonEditorConfig*/,11/*vs/base/common/event*/,3/*vs/base/common/lifecycle*/,26/*vs/base/common/objects*/,15/*vs/base/common/platform*/,127/*vs/platform/configuration/common/configurationRegistry*/,44/*vs/platform/registry/common/platform*/,132/*vs/editor/common/config/fontInfo*/,135/*vs/editor/common/config/editorZoom*/,49/*vs/editor/common/config/editorOptions*/]), function (require, exports, nls, event_1, lifecycle_1, objects, platform, configurationRegistry_1, platform_1, fontInfo_1, editorZoom_1, editorOptions) {
    /*---------------------------------------------------------------------------------------------
     *  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 EDITOR_DEFAULTS = editorOptions.EDITOR_DEFAULTS;
    var EDITOR_FONT_DEFAULTS = editorOptions.EDITOR_FONT_DEFAULTS;
    var EDITOR_MODEL_DEFAULTS = editorOptions.EDITOR_MODEL_DEFAULTS;
    exports.TabFocus = new (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 CommonEditorConfiguration = (function (_super) {
        __extends(CommonEditorConfiguration, _super);
        function CommonEditorConfiguration(options) {
            var _this = _super.call(this) || this;
            _this._onDidChange = _this._register(new event_1.Emitter());
            _this.onDidChange = _this._onDidChange.event;
            // 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._validatedOptions = editorOptions.EditorOptionsValidator.validate(_this._rawOptions, EDITOR_DEFAULTS);
            _this.editor = null;
            _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.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);
            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.prototype.updateOptions = function (newOptions) {
            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': configurationRegistry_1.ConfigurationScope.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'],
                'default': 'on',
                'description': nls.localize(6, null)
            },
            'editor.rulers': {
                'type': 'array',
                'items': {
                    'type': 'number'
                },
                'default': EDITOR_DEFAULTS.viewInfo.rulers,
                'description': nls.localize(7, null)
            },
            'editor.wordSeparators': {
                'type': 'string',
                'default': EDITOR_DEFAULTS.wordSeparators,
                'description': nls.localize(8, null)
            },
            'editor.tabSize': {
                'type': 'number',
                'default': EDITOR_MODEL_DEFAULTS.tabSize,
                'minimum': 1,
                'description': nls.localize(9, null),
                'errorMessage': nls.localize(10, null)
            },
            'editor.insertSpaces': {
                'type': 'boolean',
                'default': EDITOR_MODEL_DEFAULTS.insertSpaces,
                'description': nls.localize(11, null),
                'errorMessage': nls.localize(12, null)
            },
            'editor.detectIndentation': {
                'type': 'boolean',
                'default': EDITOR_MODEL_DEFAULTS.detectIndentation,
                'description': nls.localize(13, null)
            },
            'editor.roundedSelection': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.viewInfo.roundedSelection,
                'description': nls.localize(14, null)
            },
            'editor.scrollBeyondLastLine': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.viewInfo.scrollBeyondLastLine,
                'description': nls.localize(15, null)
            },
            'editor.minimap.enabled': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.viewInfo.minimap.enabled,
                'description': nls.localize(16, null)
            },
            'editor.minimap.showSlider': {
                'type': 'string',
                'enum': ['always', 'mouseover'],
                'default': EDITOR_DEFAULTS.viewInfo.minimap.showSlider,
                'description': nls.localize(17, null)
            },
            'editor.minimap.renderCharacters': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.viewInfo.minimap.renderCharacters,
                'description': nls.localize(18, null)
            },
            'editor.minimap.maxColumn': {
                'type': 'number',
                'default': EDITOR_DEFAULTS.viewInfo.minimap.maxColumn,
                'description': nls.localize(19, null)
            },
            'editor.find.seedSearchStringFromSelection': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.find.seedSearchStringFromSelection,
                'description': nls.localize(20, null)
            },
            'editor.find.autoFindInSelection': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.find.autoFindInSelection,
                'description': nls.localize(21, null)
            },
            'editor.wordWrap': {
                'type': 'string',
                'enum': ['off', 'on', 'wordWrapColumn', 'bounded'],
                'enumDescriptions': [
                    nls.localize(22, null),
                    nls.localize(23, null),
                    nls.localize(24, null),





                    nls.localize(25, null),






                ],
                'default': EDITOR_DEFAULTS.wordWrap,
                'description': nls.localize(26, null)






            },
            'editor.wordWrapColumn': {
                'type': 'integer',
                'default': EDITOR_DEFAULTS.wordWrapColumn,
                'minimum': 1,
                'description': nls.localize(27, null)






            },
            'editor.wrappingIndent': {
                'type': 'string',
                'enum': ['none', 'same', 'indent'],
                'default': 'same',
                'description': nls.localize(28, null)
            },
            'editor.mouseWheelScrollSensitivity': {
                'type': 'number',
                'default': EDITOR_DEFAULTS.viewInfo.scrollbar.mouseWheelScrollSensitivity,
                'description': nls.localize(29, null)
            },
            'editor.multiCursorModifier': {
                'type': 'string',
                'enum': ['ctrlCmd', 'alt'],
                'enumDescriptions': [
                    nls.localize(30, null),
                    nls.localize(31, null)
                ],
                'default': 'alt',
                'description': nls.localize(32, null)






            },
            'editor.quickSuggestions': {
                'anyOf': [
                    {
                        type: 'boolean',
                    },
                    {
                        type: 'object',
                        properties: {
                            strings: {
                                type: 'boolean',
                                default: false,
                                description: nls.localize(33, null)
                            },
                            comments: {
                                type: 'boolean',
                                default: false,
                                description: nls.localize(34, null)
                            },
                            other: {
                                type: 'boolean',
                                default: true,
                                description: nls.localize(35, null)
                            },
                        }
                    }
                ],
                'default': EDITOR_DEFAULTS.contribInfo.quickSuggestions,
                'description': nls.localize(36, null)
            },
            'editor.quickSuggestionsDelay': {
                'type': 'integer',
                'default': EDITOR_DEFAULTS.contribInfo.quickSuggestionsDelay,
                'minimum': 0,
                'description': nls.localize(37, null)
            },
            'editor.parameterHints': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.parameterHints,
                'description': nls.localize(38, null)
            },
            'editor.autoClosingBrackets': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.autoClosingBrackets,
                'description': nls.localize(39, null)
            },
            'editor.formatOnType': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.formatOnType,
                'description': nls.localize(40, null)
            },
            'editor.formatOnPaste': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.formatOnPaste,
                'description': nls.localize(41, null)
            },
            'editor.autoIndent': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.autoIndent,
                'description': nls.localize(42, null)
            },
            'editor.suggestOnTriggerCharacters': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.suggestOnTriggerCharacters,
                'description': nls.localize(43, null)
            },
            'editor.acceptSuggestionOnEnter': {
                'type': 'string',
                'enum': ['on', 'smart', 'off'],
                'default': EDITOR_DEFAULTS.contribInfo.acceptSuggestionOnEnter,
                'description': nls.localize(44, null)
            },
            'editor.acceptSuggestionOnCommitCharacter': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.acceptSuggestionOnCommitCharacter,
                'description': nls.localize(45, null)
            },
            'editor.snippetSuggestions': {
                'type': 'string',
                'enum': ['top', 'bottom', 'inline', 'none'],
                'enumDescriptions': [
                    nls.localize(46, null),
                    nls.localize(47, null),
                    nls.localize(48, null),
                    nls.localize(49, null),
                ],
                'default': EDITOR_DEFAULTS.contribInfo.snippetSuggestions,
                'description': nls.localize(50, null)
            },
            'editor.emptySelectionClipboard': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.emptySelectionClipboard,
                'description': nls.localize(51, null)
            },
            'editor.wordBasedSuggestions': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.wordBasedSuggestions,
                'description': nls.localize(52, null)
            },
            'editor.suggestFontSize': {
                'type': 'integer',
                'default': 0,
                'minimum': 0,
                'description': nls.localize(53, null)
            },
            'editor.suggestLineHeight': {
                'type': 'integer',
                'default': 0,
                'minimum': 0,
                'description': nls.localize(54, null)
            },
            'editor.selectionHighlight': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.selectionHighlight,
                'description': nls.localize(55, null)
            },
            'editor.occurrencesHighlight': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.occurrencesHighlight,
                'description': nls.localize(56, null)
            },
            'editor.overviewRulerLanes': {
                'type': 'integer',
                'default': 3,
                'description': nls.localize(57, null)
            },
            'editor.overviewRulerBorder': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.viewInfo.overviewRulerBorder,
                'description': nls.localize(58, null)
            },
            'editor.cursorBlinking': {
                'type': 'string',
                'enum': ['blink', 'smooth', 'phase', 'expand', 'solid'],
                'default': editorOptions.blinkingStyleToString(EDITOR_DEFAULTS.viewInfo.cursorBlinking),
                'description': nls.localize(59, null)
            },
            'editor.mouseWheelZoom': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.viewInfo.mouseWheelZoom,
                'description': nls.localize(60, 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(61, null)
            },
            'editor.fontLigatures': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.viewInfo.fontLigatures,
                'description': nls.localize(62, null)
            },
            'editor.hideCursorInOverviewRuler': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.viewInfo.hideCursorInOverviewRuler,
                'description': nls.localize(63, null)
            },
            'editor.renderWhitespace': {
                'type': 'string',
                'enum': ['none', 'boundary', 'all'],
                default: EDITOR_DEFAULTS.viewInfo.renderWhitespace,
                description: nls.localize(64, null)
            },
            'editor.renderControlCharacters': {
                'type': 'boolean',
                default: EDITOR_DEFAULTS.viewInfo.renderControlCharacters,
                description: nls.localize(65, null)
            },
            'editor.renderIndentGuides': {
                'type': 'boolean',
                default: EDITOR_DEFAULTS.viewInfo.renderIndentGuides,
                description: nls.localize(66, null)
            },
            'editor.renderLineHighlight': {
                'type': 'string',
                'enum': ['none', 'gutter', 'line', 'all'],
                default: EDITOR_DEFAULTS.viewInfo.renderLineHighlight,
                description: nls.localize(67, null)
            },
            'editor.codeLens': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.codeLens,
                'description': nls.localize(68, null)
            },
            'editor.folding': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.folding,
                'description': nls.localize(69, null)
            },
            'editor.showFoldingControls': {
                'type': 'string',
                'enum': ['always', 'mouseover'],
                'default': EDITOR_DEFAULTS.contribInfo.showFoldingControls,
                'description': nls.localize(70, null)
            },
            'editor.matchBrackets': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.matchBrackets,
                'description': nls.localize(71, null)
            },
            'editor.glyphMargin': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.viewInfo.glyphMargin,
                'description': nls.localize(72, null)
            },
            'editor.useTabStops': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.useTabStops,
                'description': nls.localize(73, null)
            },
            'editor.trimAutoWhitespace': {
                'type': 'boolean',
                'default': EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
                'description': nls.localize(74, null)
            },
            'editor.stablePeek': {
                'type': 'boolean',
                'default': false,
                'description': nls.localize(75, null)
            },
            'editor.dragAndDrop': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.dragAndDrop,
                'description': nls.localize(76, null)
            },
            'editor.accessibilitySupport': {
                'type': 'string',
                'enum': ['auto', 'on', 'off'],
                'enumDescriptions': [
                    nls.localize(77, null),
                    nls.localize(78, null),
                    nls.localize(79, null),
                ],
                'default': EDITOR_DEFAULTS.accessibilitySupport,
                'description': nls.localize(80, null)
            },
            'editor.links': {
                'type': 'boolean',
                'default': EDITOR_DEFAULTS.contribInfo.links,
                'description': nls.localize(81, null)
            },
            'diffEditor.renderSideBySide': {
                'type': 'boolean',
                'default': true,
                'description': nls.localize(82, null)
            },
            'diffEditor.ignoreTrimWhitespace': {
                'type': 'boolean',
                'default': true,
                'description': nls.localize(83, null)
            },
            'diffEditor.renderIndicators': {
                'type': 'boolean',
                'default': true,
                'description': nls.localize(84, null)
            }
        }
    };
    if (platform.isLinux) {
        editorConfiguration['properties']['editor.selectionClipboard'] = {
            'type': 'boolean',
            'default': EDITOR_DEFAULTS.contribInfo.selectionClipboard,
            'description': nls.localize(85, null)
        };
    }
    configurationRegistry.registerConfiguration(editorConfiguration);
});

define(__m[436/*vs/editor/common/services/languagesRegistry*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,166/*vs/base/common/mime*/,9/*vs/base/common/strings*/,44/*vs/platform/registry/common/platform*/,126/*vs/editor/common/modes/modesRegistry*/,17/*vs/editor/common/modes*/,68/*vs/editor/common/modes/nullMode*/,127/*vs/platform/configuration/common/configurationRegistry*/]), function (require, exports, errors_1, mime, strings, platform_1, modesRegistry_1, modes_1, nullMode_1, configurationRegistry_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var LanguagesRegistry = (function () {
        function LanguagesRegistry(useModesRegistry) {
            if (useModesRegistry === void 0) { useModesRegistry = true; }
            var _this = this;
            this._nextLanguageId = 1;
            this._languages = {};
            this._mimeTypesMap = {};
            this._nameMap = {};
            this._lowercaseNameMap = {};
            this._languageIds = [];
            if (useModesRegistry) {
                this._registerLanguages(modesRegistry_1.ModesRegistry.getLanguages());
                modesRegistry_1.ModesRegistry.onDidAddLanguages(function (m) { return _this._registerLanguages(m); });
            }
        }
        LanguagesRegistry.prototype._registerLanguages = function (desc) {
            var _this = this;
            if (desc.length === 0) {
                return;
            }
            for (var i = 0; i < desc.length; i++) {
                this._registerLanguage(desc[i]);
            }
            // 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; }));
        };
        LanguagesRegistry.prototype._registerLanguage = function (lang) {
            var langId = lang.id;
            var resolvedLanguage = null;
            if (hasOwnProperty.call(this._languages, langId)) {
                resolvedLanguage = this._languages[langId];
            }
            else {
                var languageId = this._nextLanguageId++;
                resolvedLanguage = {
                    identifier: new modes_1.LanguageIdentifier(langId, languageId),
                    name: null,
                    mimetypes: [],
                    aliases: [],
                    extensions: [],
                    filenames: [],
                    configurationFiles: []
                };
                this._languageIds[languageId] = langId;
                this._languages[langId] = resolvedLanguage;
            }
            LanguagesRegistry._mergeLanguage(resolvedLanguage, lang);
        };
        LanguagesRegistry._mergeLanguage = function (resolvedLanguage, lang) {
            var langId = lang.id;
            var primaryMime = null;
            if (typeof lang.mimetypes !== 'undefined' && Array.isArray(lang.mimetypes)) {
                for (var i = 0; i < lang.mimetypes.length; i++) {
                    if (!primaryMime) {
                        primaryMime = lang.mimetypes[i];
                    }
                    resolvedLanguage.mimetypes.push(lang.mimetypes[i]);
                }
            }
            if (!primaryMime) {
                primaryMime = "text/x-" + langId;
                resolvedLanguage.mimetypes.push(primaryMime);
            }
            if (Array.isArray(lang.extensions)) {
                for (var _i = 0, _a = lang.extensions; _i < _a.length; _i++) {
                    var extension = _a[_i];
                    mime.registerTextMime({ id: langId, mime: primaryMime, extension: extension });
                    resolvedLanguage.extensions.push(extension);
                }
            }
            if (Array.isArray(lang.filenames)) {
                for (var _b = 0, _c = lang.filenames; _b < _c.length; _b++) {
                    var filename = _c[_b];
                    mime.registerTextMime({ id: langId, mime: primaryMime, filename: filename });
                    resolvedLanguage.filenames.push(filename);
                }
            }
            if (Array.isArray(lang.filenamePatterns)) {
                for (var _d = 0, _e = lang.filenamePatterns; _d < _e.length; _d++) {
                    var filenamePattern = _e[_d];
                    mime.registerTextMime({ id: langId, mime: primaryMime, filepattern: filenamePattern });
                }
            }
            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 });
                    }
                }
                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 i = 0; i < langAliases.length; i++) {
                    if (!langAliases[i] || langAliases[i].length === 0) {
                        continue;
                    }
                    resolvedLanguage.aliases.push(langAliases[i]);
                }
            }
            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 (typeof lang.configuration === 'string') {
                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.getRegisteredModes = function () {
            return Object.keys(this._languages);
        };
        LanguagesRegistry.prototype.getRegisteredLanguageNames = function () {
            return Object.keys(this._nameMap);
        };
        LanguagesRegistry.prototype.getLanguageName = function (modeId) {
            if (!hasOwnProperty.call(this._languages, modeId)) {
                return null;
            }
            return this._languages[modeId].name;
        };
        LanguagesRegistry.prototype.getModeIdForLanguageNameLowercase = function (languageNameLower) {
            if (!hasOwnProperty.call(this._lowercaseNameMap, languageNameLower)) {
                return null;
            }
            return this._lowercaseNameMap[languageNameLower].language;
        };
        LanguagesRegistry.prototype.getConfigurationFiles = function (modeId) {
            if (!hasOwnProperty.call(this._languages, modeId)) {
                return [];
            }
            return this._languages[modeId].configurationFiles || [];
        };
        LanguagesRegistry.prototype.getMimeForMode = function (modeId) {
            if (!hasOwnProperty.call(this._languages, modeId)) {
                return null;
            }
            var language = this._languages[modeId];
            return (language.mimetypes[0] || null);
        };
        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._languageIds[_modeId];
                if (!modeId) {
                    return null;
                }
            }
            if (!hasOwnProperty.call(this._languages, modeId)) {
                return null;
            }
            return this._languages[modeId].identifier;
        };
        LanguagesRegistry.prototype.getModeIdsFromLanguageName = function (languageName) {
            if (!languageName) {
                return [];
            }
            if (hasOwnProperty.call(this._nameMap, languageName)) {
                return [this._nameMap[languageName].language];
            }
            return [];
        };
        LanguagesRegistry.prototype.getModeIdsFromFilenameOrFirstLine = function (filename, firstLine) {
            if (!filename && !firstLine) {
                return [];
            }
            var mimeTypes = mime.guessMimeTypes(filename, firstLine);
            return this.extractModeIds(mimeTypes.join(','));
        };
        LanguagesRegistry.prototype.getExtensions = function (languageName) {
            if (!hasOwnProperty.call(this._nameMap, languageName)) {
                return [];
            }
            var languageId = this._nameMap[languageName];
            return this._languages[languageId.language].extensions;
        };
        LanguagesRegistry.prototype.getFilenames = function (languageName) {
            if (!hasOwnProperty.call(this._nameMap, languageName)) {
                return [];
            }
            var languageId = this._nameMap[languageName];
            return this._languages[languageId.language].filenames;
        };
        return LanguagesRegistry;
    }());
    exports.LanguagesRegistry = LanguagesRegistry;
});

define(__m[437/*vs/editor/common/services/modeServiceImpl*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,11/*vs/base/common/event*/,7/*vs/base/common/winjs.base*/,511/*vs/editor/common/modes/abstractMode*/,436/*vs/editor/common/services/languagesRegistry*/]), function (require, exports, errors_1, event_1, winjs_base_1, abstractMode_1, languagesRegistry_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ModeServiceImpl = (function () {
        function ModeServiceImpl() {
            this._onDidCreateMode = new event_1.Emitter();
            this.onDidCreateMode = this._onDidCreateMode.event;
            this._instantiatedModes = {};
            this._registry = new languagesRegistry_1.LanguagesRegistry();
        }
        ModeServiceImpl.prototype._onReady = function () {
            return winjs_base_1.TPromise.as(true);
        };
        ModeServiceImpl.prototype.isRegisteredMode = function (mimetypeOrModeId) {
            return this._registry.isRegisteredMode(mimetypeOrModeId);
        };
        ModeServiceImpl.prototype.getRegisteredModes = function () {
            return this._registry.getRegisteredModes();
        };
        ModeServiceImpl.prototype.getRegisteredLanguageNames = function () {
            return this._registry.getRegisteredLanguageNames();
        };
        ModeServiceImpl.prototype.getExtensions = function (alias) {
            return this._registry.getExtensions(alias);
        };
        ModeServiceImpl.prototype.getFilenames = function (alias) {
            return this._registry.getFilenames(alias);
        };
        ModeServiceImpl.prototype.getMimeForMode = function (modeId) {
            return this._registry.getMimeForMode(modeId);
        };
        ModeServiceImpl.prototype.getLanguageName = function (modeId) {
            return this._registry.getLanguageName(modeId);
        };
        ModeServiceImpl.prototype.getModeIdForLanguageName = function (alias) {
            return this._registry.getModeIdForLanguageNameLowercase(alias);
        };
        ModeServiceImpl.prototype.getModeIdByFilenameOrFirstLine = function (filename, firstLine) {
            var modeIds = this._registry.getModeIdsFromFilenameOrFirstLine(filename, 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);
        };
        ModeServiceImpl.prototype.getConfigurationFiles = function (modeId) {
            return this._registry.getConfigurationFiles(modeId);
        };
        // --- instantiation
        ModeServiceImpl.prototype.lookup = function (commaSeparatedMimetypesOrCommaSeparatedIds) {
            var r = [];
            var modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds);
            for (var i = 0; i < modeIds.length; i++) {
                var modeId = modeIds[i];
                r.push({
                    modeId: modeId,
                    isInstantiated: this._instantiatedModes.hasOwnProperty(modeId)
                });
            }
            return r;
        };
        ModeServiceImpl.prototype.getMode = function (commaSeparatedMimetypesOrCommaSeparatedIds) {
            var modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds);
            var isPlainText = false;
            for (var i = 0; i < modeIds.length; i++) {
                if (this._instantiatedModes.hasOwnProperty(modeIds[i])) {
                    return this._instantiatedModes[modeIds[i]];
                }
                isPlainText = isPlainText || (modeIds[i] === 'plaintext');
            }
            if (isPlainText) {
                // Try to do it synchronously
                var r = null;
                this.getOrCreateMode(commaSeparatedMimetypesOrCommaSeparatedIds).then(function (mode) {
                    r = mode;
                }).done(null, errors_1.onUnexpectedError);
                return r;
            }
            return null;
        };
        ModeServiceImpl.prototype.getOrCreateMode = function (commaSeparatedMimetypesOrCommaSeparatedIds) {
            var _this = this;
            return this._onReady().then(function () {
                var modeId = _this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds);
                // Fall back to plain text if no mode was found
                return _this._getOrCreateMode(modeId || 'plaintext');
            });
        };
        ModeServiceImpl.prototype.getOrCreateModeByLanguageName = function (languageName) {
            var _this = this;
            return this._onReady().then(function () {
                var modeId = _this._getModeIdByLanguageName(languageName);
                // Fall back to plain text if no mode was found
                return _this._getOrCreateMode(modeId || 'plaintext');
            });
        };
        ModeServiceImpl.prototype._getModeIdByLanguageName = function (languageName) {
            var modeIds = this._registry.getModeIdsFromLanguageName(languageName);
            if (modeIds.length > 0) {
                return modeIds[0];
            }
            return null;
        };
        ModeServiceImpl.prototype.getOrCreateModeByFilenameOrFirstLine = function (filename, firstLine) {
            var _this = this;
            return this._onReady().then(function () {
                var modeId = _this.getModeIdByFilenameOrFirstLine(filename, firstLine);
                // Fall back to plain text if no mode was found
                return _this._getOrCreateMode(modeId || 'plaintext');
            });
        };
        ModeServiceImpl.prototype._getOrCreateMode = function (modeId) {
            if (!this._instantiatedModes.hasOwnProperty(modeId)) {
                var languageIdentifier = this.getLanguageIdentifier(modeId);
                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[438/*vs/platform/configuration/common/model*/], __M([1/*require*/,0/*exports*/,44/*vs/platform/registry/common/platform*/,442/*vs/base/common/json*/,127/*vs/platform/configuration/common/configurationRegistry*/,62/*vs/platform/configuration/common/configuration*/]), function (require, exports, platform_1, json, configurationRegistry_1, configuration_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    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 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));
        }
    }
    function getConfigurationKeys() {
        var properties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties();
        return Object.keys(properties);
    }
    exports.getConfigurationKeys = getConfigurationKeys;
    var DefaultConfigurationModel = (function (_super) {
        __extends(DefaultConfigurationModel, _super);
        function DefaultConfigurationModel() {
            var _this = _super.call(this, getDefaultValues()) || this;
            _this._keys = getConfigurationKeys();
            _this._overrides = Object.keys(_this._contents)
                .filter(function (key) { return configurationRegistry_1.OVERRIDE_PROPERTY_PATTERN.test(key); })
                .map(function (key) {
                return {
                    identifiers: [overrideIdentifierFromKey(key).trim()],
                    contents: toValuesTree(_this._contents[key], function (message) { return console.error("Conflict in default settings file: " + message); })
                };
            });
            return _this;
        }
        Object.defineProperty(DefaultConfigurationModel.prototype, "keys", {
            get: function () {
                return this._keys;
            },
            enumerable: true,
            configurable: true
        });
        return DefaultConfigurationModel;
    }(configuration_1.ConfigurationModel));
    exports.DefaultConfigurationModel = DefaultConfigurationModel;
    var CustomConfigurationModel = (function (_super) {
        __extends(CustomConfigurationModel, _super);
        function CustomConfigurationModel(content, name) {
            if (content === void 0) { content = ''; }
            if (name === void 0) { name = ''; }
            var _this = _super.call(this) || this;
            _this.name = name;
            _this._parseErrors = [];
            if (content) {
                _this.update(content);
            }
            return _this;
        }
        Object.defineProperty(CustomConfigurationModel.prototype, "errors", {
            get: function () {
                return this._parseErrors;
            },
            enumerable: true,
            configurable: true
        });
        CustomConfigurationModel.prototype.update = function (content) {
            var _this = this;
            var parsed = {};
            var overrides = [];
            var currentProperty = null;
            var currentParent = [];
            var previousParents = [];
            var parseErrors = [];
            function onValue(value) {
                if (Array.isArray(currentParent)) {
                    currentParent.push(value);
                }
                else if (currentProperty) {
                    currentParent[currentProperty] = value;
                }
                if (configurationRegistry_1.OVERRIDE_PROPERTY_PATTERN.test(currentProperty)) {
                    onOverrideSettingsValue(currentProperty, value);
                }
            }
            function onOverrideSettingsValue(property, value) {
                overrides.push({
                    identifiers: [overrideIdentifierFromKey(property).trim()],
                    raw: value,
                    contents: null
                });
            }
            var visitor = {
                onObjectBegin: function () {
                    var object = {};
                    onValue(object);
                    previousParents.push(currentParent);
                    currentParent = object;
                    currentProperty = null;
                },
                onObjectProperty: function (name) {
                    currentProperty = name;
                },
                onObjectEnd: function () {
                    currentParent = previousParents.pop();
                },
                onArrayBegin: function () {
                    var array = [];
                    onValue(array);
                    previousParents.push(currentParent);
                    currentParent = array;
                    currentProperty = null;
                },
                onArrayEnd: function () {
                    currentParent = previousParents.pop();
                },
                onLiteralValue: onValue,
                onError: function (error) {
                    parseErrors.push({ error: error });
                }
            };
            if (content) {
                try {
                    json.visit(content, visitor);
                    parsed = currentParent[0] || {};
                }
                catch (e) {
                    console.error("Error while parsing settings file " + this.name + ": " + e);
                    this._parseErrors = [e];
                }
            }
            this.processRaw(parsed);
            var configurationProperties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties();
            this._overrides = overrides.map(function (override) {
                // Filter unknown and non-overridable properties
                var raw = {};
                for (var key in override.raw) {
                    if (configurationProperties[key] && configurationProperties[key].overridable) {
                        raw[key] = override.raw[key];
                    }
                }
                return {
                    identifiers: override.identifiers,
                    contents: toValuesTree(raw, function (message) { return console.error("Conflict in settings file " + _this.name + ": " + message); })
                };
            });
        };
        CustomConfigurationModel.prototype.processRaw = function (raw) {
            var _this = this;
            this._contents = toValuesTree(raw, function (message) { return console.error("Conflict in settings file " + _this.name + ": " + message); });
            this._keys = Object.keys(raw);
        };
        return CustomConfigurationModel;
    }(configuration_1.ConfigurationModel));
    exports.CustomConfigurationModel = CustomConfigurationModel;
    function overrideIdentifierFromKey(key) {
        return key.substring(1, key.length - 1);
    }
    exports.overrideIdentifierFromKey = overrideIdentifierFromKey;
    function keyFromOverrideIdentifier(overrideIdentifier) {
        return "[" + overrideIdentifier + "]";
    }
    exports.keyFromOverrideIdentifier = keyFromOverrideIdentifier;
});

define(__m[105/*vs/platform/keybinding/common/keybindingsRegistry*/], __M([1/*require*/,0/*exports*/,40/*vs/base/common/keyCodes*/,15/*vs/base/common/platform*/,31/*vs/platform/commands/common/commands*/,44/*vs/platform/registry/common/platform*/]), function (require, exports, keyCodes_1, platform_1, commands_1, platform_2) {
    /*---------------------------------------------------------------------------------------------
     *  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 KeybindingsRegistryImpl = (function () {
        function KeybindingsRegistryImpl() {
            this.WEIGHT = {
                editorCore: function (importance) {
                    if (importance === void 0) { importance = 0; }
                    return 0 + importance;
                },
                editorContrib: function (importance) {
                    if (importance === void 0) { importance = 0; }
                    return 100 + importance;
                },
                workbenchContrib: function (importance) {
                    if (importance === void 0) { importance = 0; }
                    return 200 + importance;
                },
                builtinExtension: function (importance) {
                    if (importance === void 0) { importance = 0; }
                    return 300 + importance;
                },
                externalExtension: function (importance) {
                    if (importance === void 0) { importance = 0; }
                    return 400 + importance;
                }
            };
            this._keybindings = [];
        }
        /**
         * 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;
        };
        /**
         * Take current platform into account and reduce to primary & secondary.
         */
        KeybindingsRegistryImpl.bindToCurrentPlatform2 = 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 _this = this;
            var actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule);
            if (actualKb && actualKb.primary) {
                this.registerDefaultKeybinding(keyCodes_1.createKeybinding(actualKb.primary, platform_1.OS), rule.id, rule.weight, 0, rule.when);
            }
            if (actualKb && Array.isArray(actualKb.secondary)) {
                actualKb.secondary.forEach(function (k, i) { return _this.registerDefaultKeybinding(keyCodes_1.createKeybinding(k, platform_1.OS), rule.id, rule.weight, -i - 1, rule.when); });
            }
        };
        KeybindingsRegistryImpl.prototype.registerKeybindingRule2 = function (rule) {
            var actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform2(rule);
            if (actualKb && actualKb.primary) {
                this.registerDefaultKeybinding(actualKb.primary, rule.id, rule.weight, 0, rule.when);
            }
        };
        KeybindingsRegistryImpl.prototype.registerCommandAndKeybindingRule = function (desc) {
            this.registerKeybindingRule(desc);
            commands_1.CommandsRegistry.registerCommand(desc.id, 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, weight1, weight2, when) {
            if (platform_1.OS === 1 /* Windows */) {
                if (keybinding.type === 2 /* Chord */) {
                    this._assertNoCtrlAlt(keybinding.firstPart, commandId);
                }
                else {
                    this._assertNoCtrlAlt(keybinding, commandId);
                }
            }
            this._keybindings.push({
                keybinding: keybinding,
                command: commandId,
                commandArgs: null,
                when: when,
                weight1: weight1,
                weight2: weight2
            });
        };
        KeybindingsRegistryImpl.prototype.getDefaultKeybindings = function () {
            var result = this._keybindings.slice(0);
            result.sort(sorter);
            return result;
        };
        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;
    }
});











define(__m[129/*vs/editor/standalone/browser/simpleServices*/], __M([1/*require*/,0/*exports*/,70/*vs/base/common/network*/,36/*vs/base/common/severity*/,24/*vs/base/common/uri*/,7/*vs/base/common/winjs.base*/,62/*vs/platform/configuration/common/configuration*/,31/*vs/platform/commands/common/commands*/,414/*vs/platform/keybinding/common/abstractKeybindingService*/,419/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/,159/*vs/platform/keybinding/common/keybindingResolver*/,46/*vs/platform/keybinding/common/keybinding*/,20/*vs/editor/common/editorCommon*/,11/*vs/base/common/event*/,438/*vs/platform/configuration/common/model*/,3/*vs/base/common/lifecycle*/,4/*vs/base/browser/dom*/,65/*vs/base/browser/keyboardEvent*/,105/*vs/platform/keybinding/common/keybindingsRegistry*/,407/*vs/platform/actions/common/menu*/,40/*vs/base/common/keyCodes*/,418/*vs/platform/keybinding/common/resolvedKeybindingItem*/,15/*vs/base/common/platform*/]), function (require, exports, network_1, severity_1, uri_1, winjs_base_1, configuration_1, commands_1, abstractKeybindingService_1, usLayoutResolvedKeybinding_1, keybindingResolver_1, keybinding_1, editorCommon, event_1, model_1, lifecycle_1, dom, keyboardEvent_1, keybindingsRegistry_1, menu_1, keyCodes_1, resolvedKeybindingItem_1, platform_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var SimpleEditor = (function () {
        function SimpleEditor(editor) {
            this._widget = editor;
        }
        SimpleEditor.prototype.getId = function () { return 'editor'; };
        SimpleEditor.prototype.getControl = function () { return this._widget; };
        SimpleEditor.prototype.getSelection = function () { return this._widget.getSelection(); };
        SimpleEditor.prototype.focus = function () { this._widget.focus(); };
        SimpleEditor.prototype.isVisible = function () { return true; };
        SimpleEditor.prototype.withTypedEditor = function (codeEditorCallback, diffEditorCallback) {
            if (editorCommon.isCommonCodeEditor(this._widget)) {
                // Single Editor
                return codeEditorCallback(this._widget);
            }
            else {
                // Diff Editor
                return diffEditorCallback(this._widget);
            }
        };
        return SimpleEditor;
    }());
    exports.SimpleEditor = SimpleEditor;
    var SimpleModel = (function () {
        function SimpleModel(model) {
            this.model = model;
            this._onDispose = new event_1.Emitter();
        }
        Object.defineProperty(SimpleModel.prototype, "onDispose", {
            get: function () {
                return this._onDispose.event;
            },
            enumerable: true,
            configurable: true
        });
        SimpleModel.prototype.load = function () {
            return winjs_base_1.TPromise.as(this);
        };
        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;
    var SimpleEditorService = (function () {
        function SimpleEditorService() {
            this.openEditorDelegate = null;
        }
        SimpleEditorService.prototype.setEditor = function (editor) {
            this.editor = new SimpleEditor(editor);
        };
        SimpleEditorService.prototype.setOpenEditorDelegate = function (openEditorDelegate) {
            this.openEditorDelegate = openEditorDelegate;
        };
        SimpleEditorService.prototype.openEditor = function (typedData, sideBySide) {
            var _this = this;
            return winjs_base_1.TPromise.as(this.editor.withTypedEditor(function (editor) { return _this.doOpenEditor(editor, typedData); }, function (diffEditor) { return (_this.doOpenEditor(diffEditor.getOriginalEditor(), typedData) ||
                _this.doOpenEditor(diffEditor.getModifiedEditor(), typedData)); }));
        };
        SimpleEditorService.prototype.doOpenEditor = function (editor, data) {
            var model = this.findModel(editor, data);
            if (!model) {
                if (data.resource) {
                    if (this.openEditorDelegate) {
                        this.openEditorDelegate(data.resource.toString());
                        return null;
                    }
                    else {
                        var schema = data.resource.scheme;
                        if (schema === network_1.Schemas.http || schema === network_1.Schemas.https) {
                            // This is a fully qualified http or https URL
                            window.open(data.resource.toString());
                            return this.editor;
                        }
                    }
                }
                return null;
            }
            var selection = data.options.selection;
            if (selection) {
                if (typeof selection.endLineNumber === 'number' && typeof selection.endColumn === 'number') {
                    editor.setSelection(selection);
                    editor.revealRangeInCenter(selection);
                }
                else {
                    var pos = {
                        lineNumber: selection.startLineNumber,
                        column: selection.startColumn
                    };
                    editor.setPosition(pos);
                    editor.revealPositionInCenter(pos);
                }
            }
            return this.editor;
        };
        SimpleEditorService.prototype.findModel = function (editor, data) {
            var model = editor.getModel();
            if (model.uri.toString() !== data.resource.toString()) {
                return null;
            }
            return model;
        };
        return SimpleEditorService;
    }());
    exports.SimpleEditorService = SimpleEditorService;
    var SimpleEditorModelResolverService = (function () {
        function SimpleEditorModelResolverService() {
        }
        SimpleEditorModelResolverService.prototype.setEditor = function (editor) {
            this.editor = new SimpleEditor(editor);
        };
        SimpleEditorModelResolverService.prototype.createModelReference = function (resource) {
            var _this = this;
            var model;
            model = this.editor.withTypedEditor(function (editor) { return _this.findModel(editor, resource); }, function (diffEditor) { return _this.findModel(diffEditor.getOriginalEditor(), resource) || _this.findModel(diffEditor.getModifiedEditor(), resource); });
            if (!model) {
                return winjs_base_1.TPromise.as(new lifecycle_1.ImmortalReference(null));
            }
            return winjs_base_1.TPromise.as(new lifecycle_1.ImmortalReference(new SimpleModel(model)));
        };
        SimpleEditorModelResolverService.prototype.registerTextModelContentProvider = function (scheme, provider) {
            return {
                dispose: function () { }
            };
        };
        SimpleEditorModelResolverService.prototype.findModel = function (editor, resource) {
            var model = editor.getModel();
            if (model.uri.toString() !== resource.toString()) {
                return null;
            }
            return model;
        };
        return SimpleEditorModelResolverService;
    }());
    exports.SimpleEditorModelResolverService = SimpleEditorModelResolverService;
    var SimpleProgressService = (function () {
        function SimpleProgressService() {
        }
        SimpleProgressService.prototype.show = function () {
            return SimpleProgressService.NULL_PROGRESS_RUNNER;
        };
        SimpleProgressService.prototype.showWhile = function (promise, delay) {
            return null;
        };
        SimpleProgressService.NULL_PROGRESS_RUNNER = {
            done: function () { },
            total: function () { },
            worked: function () { }
        };
        return SimpleProgressService;
    }());
    exports.SimpleProgressService = SimpleProgressService;
    var SimpleMessageService = (function () {
        function SimpleMessageService() {
        }
        SimpleMessageService.prototype.show = function (sev, message) {
            switch (sev) {
                case severity_1.default.Error:
                    console.error(message);
                    break;
                case severity_1.default.Warning:
                    console.warn(message);
                    break;
                default:
                    console.log(message);
                    break;
            }
            return SimpleMessageService.Empty;
        };
        SimpleMessageService.prototype.hideAll = function () {
            // No-op
        };
        SimpleMessageService.prototype.confirm = function (confirmation) {
            var messageText = confirmation.message;
            if (confirmation.detail) {
                messageText = messageText + '\n\n' + confirmation.detail;
            }
            return window.confirm(messageText);
        };
        SimpleMessageService.Empty = function () { };
        return SimpleMessageService;
    }());
    exports.SimpleMessageService = SimpleMessageService;
    var StandaloneCommandService = (function () {
        function StandaloneCommandService(instantiationService) {
            this._onWillExecuteCommand = new event_1.Emitter();
            this.onWillExecuteCommand = this._onWillExecuteCommand.event;
            this._instantiationService = instantiationService;
            this._dynamicCommands = Object.create(null);
        }
        StandaloneCommandService.prototype.addCommand = function (id, command) {
            var _this = this;
            this._dynamicCommands[id] = command;
            return {
                dispose: 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 winjs_base_1.TPromise.wrapError(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 winjs_base_1.TPromise.as(result);
            }
            catch (err) {
                return winjs_base_1.TPromise.wrapError(err);
            }
        };
        return StandaloneCommandService;
    }());
    exports.StandaloneCommandService = StandaloneCommandService;
    var StandaloneKeybindingService = (function (_super) {
        __extends(StandaloneKeybindingService, _super);
        function StandaloneKeybindingService(contextKeyService, commandService, messageService, domNode) {
            var _this = _super.call(this, contextKeyService, commandService, messageService) || this;
            _this._cachedResolver = null;
            _this._dynamicKeybindings = [];
            _this.toDispose.push(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 toDispose = [];
            this._dynamicKeybindings.push({
                keybinding: keyCodes_1.createKeybinding(keybinding, platform_1.OS),
                command: commandId,
                when: when,
                weight1: 1000,
                weight2: 0
            });
            toDispose.push({
                dispose: 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: keybinding_1.KeybindingSource.Default });
                            return;
                        }
                    }
                }
            });
            var commandService = this._commandService;
            if (commandService instanceof StandaloneCommandService) {
                toDispose.push(commandService.addCommand(commandId, {
                    handler: handler
                }));
            }
            else {
                throw new Error('Unknown command service!');
            }
            this.updateResolver({ source: keybinding_1.KeybindingSource.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._toNormalizedKeybindingItems = function (items, isDefault) {
            var result = [], resultLen = 0;
            for (var i = 0, len = items.length; i < len; i++) {
                var item = items[i];
                var when = (item.when ? item.when.normalize() : null);
                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 j = 0; j < resolvedKeybindings.length; j++) {
                        result[resultLen++] = new resolvedKeybindingItem_1.ResolvedKeybindingItem(resolvedKeybindings[j], 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);
            return new usLayoutResolvedKeybinding_1.USLayoutResolvedKeybinding(keybinding, platform_1.OS);
        };
        StandaloneKeybindingService.prototype.resolveUserBinding = function (userBinding) {
            return [];
        };
        return StandaloneKeybindingService;
    }(abstractKeybindingService_1.AbstractKeybindingService));
    exports.StandaloneKeybindingService = StandaloneKeybindingService;
    var SimpleConfigurationService = (function () {
        function SimpleConfigurationService() {
            this._onDidUpdateConfiguration = new event_1.Emitter();
            this.onDidUpdateConfiguration = this._onDidUpdateConfiguration.event;
            this._configuration = new configuration_1.Configuration(new model_1.DefaultConfigurationModel(), new configuration_1.ConfigurationModel());
        }
        SimpleConfigurationService.prototype.configuration = function () {
            return this._configuration;
        };
        SimpleConfigurationService.prototype.reloadConfiguration = function (section) {
            return winjs_base_1.TPromise.as(this.getConfiguration(section));
        };
        SimpleConfigurationService.prototype.getConfiguration = function (section, options) {
            return this.configuration().getValue(section, options);
        };
        SimpleConfigurationService.prototype.lookup = function (key, options) {
            return this.configuration().lookup(key, options);
        };
        SimpleConfigurationService.prototype.keys = function () {
            return this.configuration().keys();
        };
        SimpleConfigurationService.prototype.values = function () {
            return this._configuration.values();
        };
        SimpleConfigurationService.prototype.getConfigurationData = function () {
            return this.configuration().toData();
        };
        return SimpleConfigurationService;
    }());
    exports.SimpleConfigurationService = SimpleConfigurationService;
    var SimpleResourceConfigurationService = (function () {
        function SimpleResourceConfigurationService(configurationService) {
            var _this = this;
            this.configurationService = configurationService;
            this._onDidUpdateConfigurationEmitter = new event_1.Emitter();
            this.configurationService.onDidUpdateConfiguration(function () {
                _this._onDidUpdateConfigurationEmitter.fire();
            });
        }
        SimpleResourceConfigurationService.prototype.getConfiguration = function () {
            return this.configurationService.getConfiguration();
        };
        return SimpleResourceConfigurationService;
    }());
    exports.SimpleResourceConfigurationService = SimpleResourceConfigurationService;
    var SimpleMenuService = (function () {
        function SimpleMenuService(commandService) {
            this._commandService = commandService;
        }
        SimpleMenuService.prototype.createMenu = function (id, contextKeyService) {
            return new menu_1.Menu(id, winjs_base_1.TPromise.as(true), this._commandService, contextKeyService);
        };
        return SimpleMenuService;
    }());
    exports.SimpleMenuService = SimpleMenuService;
    var StandaloneTelemetryService = (function () {
        function StandaloneTelemetryService() {
            this.isOptedIn = false;
        }
        StandaloneTelemetryService.prototype.publicLog = function (eventName, data) {
            return winjs_base_1.TPromise.as(null);
        };
        StandaloneTelemetryService.prototype.getTelemetryInfo = function () {
            return null;
        };
        return StandaloneTelemetryService;
    }());
    exports.StandaloneTelemetryService = StandaloneTelemetryService;
    var SimpleWorkspaceContextService = (function () {
        function SimpleWorkspaceContextService() {
            this._onDidChangeWorkspaceName = new event_1.Emitter();
            this.onDidChangeWorkspaceName = this._onDidChangeWorkspaceName.event;
            this._onDidChangeWorkspaceRoots = new event_1.Emitter();
            this.onDidChangeWorkspaceRoots = this._onDidChangeWorkspaceRoots.event;
            this.legacyWorkspace = { resource: uri_1.default.from({ scheme: SimpleWorkspaceContextService.SCHEME, authority: 'model', path: '/' }) };
            this.workspace = { id: '4064f6ec-cb38-4ad0-af64-ee6467e63c82', roots: [this.legacyWorkspace.resource], name: this.legacyWorkspace.resource.fsPath };
        }
        SimpleWorkspaceContextService.prototype.getLegacyWorkspace = function () {
            return this.legacyWorkspace;
        };
        SimpleWorkspaceContextService.prototype.getWorkspace = function () {
            return this.workspace;
        };
        SimpleWorkspaceContextService.prototype.saveWorkspace = function () {
            return winjs_base_1.TPromise.as(null);
        };
        SimpleWorkspaceContextService.prototype.getRoot = function (resource) {
            return resource && resource.scheme === SimpleWorkspaceContextService.SCHEME ? this.workspace.roots[0] : void 0;
        };
        SimpleWorkspaceContextService.prototype.hasWorkspace = function () {
            return true;
        };
        SimpleWorkspaceContextService.prototype.hasFolderWorkspace = function () {
            return true;
        };
        SimpleWorkspaceContextService.prototype.hasMultiFolderWorkspace = function () {
            return false;
        };
        SimpleWorkspaceContextService.prototype.isInsideWorkspace = function (resource) {
            return resource && resource.scheme === SimpleWorkspaceContextService.SCHEME;
        };
        SimpleWorkspaceContextService.prototype.toResource = function (workspaceRelativePath) {
            return uri_1.default.file(workspaceRelativePath);
        };
        return SimpleWorkspaceContextService;
    }());
    exports.SimpleWorkspaceContextService = SimpleWorkspaceContextService;
});

define(__m[76/*vs/platform/storage/common/storage*/], __M([1/*require*/,0/*exports*/,16/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ID = 'storageService';
    exports.IStorageService = instantiation_1.createDecorator(exports.ID);
    var StorageScope;
    (function (StorageScope) {
        /**
         * The stored data will be scoped to all workspaces of this domain.
         */
        StorageScope[StorageScope["GLOBAL"] = 0] = "GLOBAL";
        /**
         * The stored data will be scoped to the current workspace.
         */
        StorageScope[StorageScope["WORKSPACE"] = 1] = "WORKSPACE";
    })(StorageScope = exports.StorageScope || (exports.StorageScope = {}));
    exports.NullStorageService = {
        _serviceBrand: undefined,
        store: function () { return undefined; },
        swap: function () { return undefined; },
        remove: function () { return undefined; },
        get: function (a, b, defaultValue) { return defaultValue; },
        getInteger: function (a, b, defaultValue) { return defaultValue; },
        getBoolean: function (a, b, defaultValue) { return defaultValue; }
    };
});











define(__m[66/*vs/editor/browser/config/configuration*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/event*/,3/*vs/base/common/lifecycle*/,15/*vs/base/common/platform*/,28/*vs/base/browser/browser*/,168/*vs/editor/common/config/commonEditorConfig*/,132/*vs/editor/common/config/fontInfo*/,412/*vs/editor/browser/config/elementSizeObserver*/,410/*vs/editor/browser/config/charWidthReader*/,76/*vs/platform/storage/common/storage*/]), function (require, exports, event_1, lifecycle_1, platform, browser, commonEditorConfig_1, fontInfo_1, elementSizeObserver_1, charWidthReader_1, storage_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CSSBasedConfigurationCache = (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.getKeys = function () {
            var _this = this;
            return Object.keys(this._keys).map(function (id) { return _this._keys[id]; });
        };
        CSSBasedConfigurationCache.prototype.getValues = function () {
            var _this = this;
            return Object.keys(this._keys).map(function (id) { return _this._values[id]; });
        };
        return CSSBasedConfigurationCache;
    }());
    function readFontInfo(bareFontInfo) {
        return CSSBasedConfiguration.INSTANCE.readConfiguration(bareFontInfo);
    }
    exports.readFontInfo = readFontInfo;
    function restoreFontInfo(storageService) {
        var strStoredFontInfo = storageService.get('editorFontInfo', storage_1.StorageScope.GLOBAL);
        if (typeof strStoredFontInfo !== 'string') {
            return;
        }
        var storedFontInfo = null;
        try {
            storedFontInfo = JSON.parse(strStoredFontInfo);
        }
        catch (err) {
            return;
        }
        if (!Array.isArray(storedFontInfo)) {
            return;
        }
        CSSBasedConfiguration.INSTANCE.restoreFontInfo(storedFontInfo);
    }
    exports.restoreFontInfo = restoreFontInfo;
    function saveFontInfo(storageService) {
        var knownFontInfo = CSSBasedConfiguration.INSTANCE.saveFontInfo();
        storageService.store('editorFontInfo', JSON.stringify(knownFontInfo), storage_1.StorageScope.GLOBAL);
    }
    exports.saveFontInfo = saveFontInfo;
    var CSSBasedConfiguration = (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._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.saveFontInfo = function () {
            // Only save trusted font info (that has been measured in this running instance)
            return this._cache.getValues().filter(function (item) { return item.isTrusted; });
        };
        CSSBasedConfiguration.prototype.restoreFontInfo = function (savedFontInfo) {
            // Take all the saved font info and insert them in the cache without the trusted flag.
            // The reason for this is that a font might have been installed on the OS in the meantime.
            for (var i = 0, len = savedFontInfo.length; i < len; i++) {
                var fontInfo = new fontInfo_1.FontInfo(savedFontInfo[i], false);
                this._writeToCache(fontInfo, fontInfo);
            }
        };
        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),
                        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
            this.createRequest('→', 0 /* Regular */, all, monospace);
            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;
                }
            }
            // 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,
                spaceWidth: space.width,
                maxDigitWidth: maxDigitWidth
            }, canTrustBrowserZoomLevel);
        };
        CSSBasedConfiguration.INSTANCE = new CSSBasedConfiguration();
        return CSSBasedConfiguration;
    }(lifecycle_1.Disposable));
    var Configuration = (function (_super) {
        __extends(Configuration, _super);
        function Configuration(options, referenceDomElement) {
            if (referenceDomElement === void 0) { referenceDomElement = null; }
            var _this = _super.call(this, options) || this;
            _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(browser.onDidChangeAccessibilitySupport(function () { return _this._recomputeOptions(); }));
            _this._recomputeOptions();
            return _this;
        }
        Configuration.applyFontInfoSlow = function (domNode, fontInfo) {
            domNode.style.fontFamily = fontInfo.fontFamily;
            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.fontFamily);
            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.isIE) {
                extra += 'ie ';
            }
            else if (browser.isFirefox) {
                extra += 'ff ';
            }
            else if (browser.isEdge) {
                extra += 'edge ';
            }
            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,
                pixelRatio: browser.getPixelRatio(),
                zoomLevel: browser.getZoomLevel(),
                accessibilitySupport: browser.getAccessibilitySupport()
            };
        };
        Configuration.prototype.readConfiguration = function (bareFontInfo) {
            return CSSBasedConfiguration.INSTANCE.readConfiguration(bareFontInfo);
        };
        return Configuration;
    }(commonEditorConfig_1.CommonEditorConfiguration));
    exports.Configuration = Configuration;
});











define(__m[443/*vs/editor/browser/view/viewOverlays*/], __M([1/*require*/,0/*exports*/,27/*vs/base/browser/fastDomNode*/,112/*vs/editor/browser/view/viewLayer*/,66/*vs/editor/browser/config/configuration*/,35/*vs/editor/browser/view/viewPart*/]), function (require, exports, fastDomNode_1, viewLayer_1, configuration_1, viewPart_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ViewOverlays = (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 = null;
        };
        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();
            }
            return null;
        };
        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 = (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) {
            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 null;
            }
            this._renderedContent = result;
            return "<div style=\"position:absolute;top:" + deltaTop + "px;width:100%;height:" + this._lineHeight + "px;\">" + result + "</div>";
        };
        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 = (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 = (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;
});

define(__m[444/*vs/editor/browser/viewParts/viewCursors/viewCursor*/], __M([1/*require*/,0/*exports*/,27/*vs/base/browser/fastDomNode*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,49/*vs/editor/common/config/editorOptions*/,66/*vs/editor/browser/config/configuration*/,4/*vs/base/browser/dom*/]), function (require, exports, fastDomNode_1, position_1, range_1, editorOptions_1, configuration_1, dom) {
    /*---------------------------------------------------------------------------------------------
     *  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 ViewCursorRenderData = (function () {
        function ViewCursorRenderData(top, left, width, textContent) {
            this.top = top;
            this.left = left;
            this.width = width;
            this.textContent = textContent;
        }
        return ViewCursorRenderData;
    }());
    var ViewCursor = (function () {
        function ViewCursor(context, isSecondary) {
            this._context = context;
            this._isSecondary = isSecondary;
            this._cursorStyle = this._context.configuration.editor.viewInfo.cursorStyle;
            this._lineHeight = this._context.configuration.editor.lineHeight;
            this._typicalHalfwidthCharacterWidth = this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth;
            this._isVisible = true;
            // Create the dom node
            this._domNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
            if (this._isSecondary) {
                this._domNode.setClassName('cursor secondary');
            }
            else {
                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._isInEditableRange = true;
            this._lastRenderedContent = '';
            this._renderData = null;
        }
        ViewCursor.prototype.getDomNode = function () {
            return this._domNode;
        };
        ViewCursor.prototype.getIsInEditableRange = function () {
            return this._isInEditableRange;
        };
        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.viewInfo) {
                this._cursorStyle = this._context.configuration.editor.viewInfo.cursorStyle;
            }
            if (e.fontInfo) {
                configuration_1.Configuration.applyFontInfo(this._domNode, this._context.configuration.editor.fontInfo);
                this._typicalHalfwidthCharacterWidth = this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth;
            }
            return true;
        };
        ViewCursor.prototype.onCursorPositionChanged = function (position, isInEditableRange) {
            this.updatePosition(position);
            this._isInEditableRange = isInEditableRange;
            return true;
        };
        ViewCursor.prototype._prepareRender = function (ctx) {
            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(2);
                }
                else {
                    width_1 = dom.computeScreenAwareSize(1);
                }
                var top_1 = ctx.getVerticalOffsetForLineNumber(this._position.lineNumber) - ctx.bigNumbersDelta;
                return new ViewCursorRenderData(top_1, visibleRange.left, width_1, '');
            }
            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;
            var textContent = '';
            if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Block) {
                var lineContent = this._context.model.getLineContent(this._position.lineNumber);
                textContent = lineContent.charAt(this._position.column - 1);
            }
            var top = ctx.getVerticalOffsetForLineNumber(this._position.lineNumber) - ctx.bigNumbersDelta;
            return new ViewCursorRenderData(top, range.left, width, textContent);
        };
        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.setDisplay('block');
            this._domNode.setTop(this._renderData.top);
            this._domNode.setLeft(this._renderData.left);
            this._domNode.setWidth(this._renderData.width);
            this._domNode.setLineHeight(this._lineHeight);
            this._domNode.setHeight(this._lineHeight);
            return {
                domNode: this._domNode.domNode,
                position: this._position,
                contentLeft: this._renderData.left,
                height: this._lineHeight,
                width: 2
            };
        };
        ViewCursor.prototype.updatePosition = function (newPosition) {
            this._position = newPosition;
        };
        return ViewCursor;
    }());
    exports.ViewCursor = ViewCursor;
});

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



















define(__m[13/*vs/editor/common/editorCommonExtensions*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,24/*vs/base/common/uri*/,31/*vs/platform/commands/common/commands*/,105/*vs/platform/keybinding/common/keybindingsRegistry*/,44/*vs/platform/registry/common/platform*/,58/*vs/platform/telemetry/common/telemetry*/,12/*vs/editor/common/core/position*/,56/*vs/editor/common/services/modelService*/,85/*vs/platform/actions/common/actions*/,64/*vs/platform/editor/common/editor*/,19/*vs/platform/contextkey/common/contextkey*/,42/*vs/editor/common/services/codeEditorService*/]), function (require, exports, errors_1, uri_1, commands_1, keybindingsRegistry_1, platform_1, telemetry_1, position_1, modelService_1, actions_1, editor_1, contextkey_1, codeEditorService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var Command = (function () {
        function Command(opts) {
            this.id = opts.id;
            this.precondition = opts.precondition;
            this._kbOpts = opts.kbOpts;
            this._description = opts.description;
        }
        Command.prototype.toCommandAndKeybindingRule = function (defaultWeight) {
            var _this = this;
            var kbOpts = this._kbOpts || { primary: 0 };
            var kbWhen = kbOpts.kbExpr;
            if (this.precondition) {
                if (kbWhen) {
                    kbWhen = contextkey_1.ContextKeyExpr.and(kbWhen, this.precondition);
                }
                else {
                    kbWhen = this.precondition;
                }
            }
            var weight = (typeof kbOpts.weight === 'number' ? kbOpts.weight : defaultWeight);
            return {
                id: this.id,
                handler: function (accessor, args) { return _this.runCommand(accessor, args); },
                weight: weight,
                when: kbWhen,
                primary: kbOpts.primary,
                secondary: kbOpts.secondary,
                win: kbOpts.win,
                linux: kbOpts.linux,
                mac: kbOpts.mac,
                description: this._description
            };
        };
        return Command;
    }());
    exports.Command = Command;
    // ----- Editor Command & Editor Contribution Command
    function findFocusedEditor(accessor) {
        return accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
    }
    function getWorkbenchActiveEditor(accessor) {
        var editorService = accessor.get(editor_1.IEditorService);
        var activeEditor = editorService.getActiveEditor && editorService.getActiveEditor();
        return codeEditorService_1.getCodeEditor(activeEditor);
    }
    var EditorCommand = (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 (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));
                    }
                };
                return EditorControllerCommandImpl;
            }(EditorCommand));
        };
        EditorCommand.prototype.runCommand = function (accessor, args) {
            var _this = this;
            // Find the editor with text focus
            var editor = findFocusedEditor(accessor);
            if (!editor) {
                // Fallback to use what the workbench considers the active editor
                editor = getWorkbenchActiveEditor(accessor);
            }
            if (!editor) {
                // well, at least we tried...
                return;
            }
            return editor.invokeWithinContext(function (editorAccessor) {
                var kbService = editorAccessor.get(contextkey_1.IContextKeyService);
                if (!kbService.contextMatchesRules(_this.precondition)) {
                    // precondition does not hold
                    return;
                }
                return _this.runEditorCommand(editorAccessor, editor, args);
            });
        };
        return EditorCommand;
    }(Command));
    exports.EditorCommand = EditorCommand;
    var EditorAction = (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.toMenuItem = function () {
            if (!this.menuOpts) {
                return null;
            }
            return {
                command: {
                    id: this.id,
                    title: this.label
                },
                when: this.precondition,
                group: this.menuOpts.group,
                order: this.menuOpts.order
            };
        };
        EditorAction.prototype.runEditorCommand = function (accessor, editor, args) {
            this.reportTelemetry(accessor, editor);
            return this.run(accessor, editor, args || {});
        };
        EditorAction.prototype.reportTelemetry = function (accessor, editor) {
            accessor.get(telemetry_1.ITelemetryService).publicLog('editorActionInvoked', __assign({ name: this.label, id: this.id }, editor.getTelemetryData()));
        };
        return EditorAction;
    }(EditorCommand));
    exports.EditorAction = EditorAction;
    // --- Registration of commands and actions
    function editorAction(ctor) {
        CommonEditorRegistry.registerEditorAction(new ctor());
    }
    exports.editorAction = editorAction;
    function editorCommand(ctor) {
        registerEditorCommand(new ctor());
    }
    exports.editorCommand = editorCommand;
    function registerEditorCommand(editorCommand) {
        CommonEditorRegistry.registerEditorCommand(editorCommand);
        return editorCommand;
    }
    exports.registerEditorCommand = registerEditorCommand;
    function commonEditorContribution(ctor) {
        EditorContributionRegistry.INSTANCE.registerEditorContribution(ctor);
    }
    exports.commonEditorContribution = commonEditorContribution;
    var CommonEditorRegistry;
    (function (CommonEditorRegistry) {
        // --- Editor Actions
        function registerEditorAction(editorAction) {
            EditorContributionRegistry.INSTANCE.registerEditorAction(editorAction);
        }
        CommonEditorRegistry.registerEditorAction = registerEditorAction;
        function getEditorActions() {
            return EditorContributionRegistry.INSTANCE.getEditorActions();
        }
        CommonEditorRegistry.getEditorActions = getEditorActions;
        function getEditorCommand(commandId) {
            return EditorContributionRegistry.INSTANCE.getEditorCommand(commandId);
        }
        CommonEditorRegistry.getEditorCommand = getEditorCommand;
        // --- Editor Contributions
        function getEditorContributions() {
            return EditorContributionRegistry.INSTANCE.getEditorContributions();
        }
        CommonEditorRegistry.getEditorContributions = getEditorContributions;
        // --- Editor Commands
        function commandWeight(importance) {
            if (importance === void 0) { importance = 0; }
            return keybindingsRegistry_1.KeybindingsRegistry.WEIGHT.editorContrib(importance);
        }
        CommonEditorRegistry.commandWeight = commandWeight;
        function registerEditorCommand(editorCommand) {
            EditorContributionRegistry.INSTANCE.registerEditorCommand(editorCommand);
        }
        CommonEditorRegistry.registerEditorCommand = registerEditorCommand;
        function registerLanguageCommand(id, handler) {
            commands_1.CommandsRegistry.registerCommand(id, function (accessor, args) { return handler(accessor, args || {}); });
        }
        CommonEditorRegistry.registerLanguageCommand = registerLanguageCommand;
        function registerDefaultLanguageCommand(id, handler) {
            registerLanguageCommand(id, function (accessor, args) {
                var resource = args.resource, position = args.position;
                if (!(resource instanceof uri_1.default)) {
                    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) {
                    throw errors_1.illegalArgument('Can not find open model for ' + resource);
                }
                var editorPosition = position_1.Position.lift(position);
                return handler(model, editorPosition, args);
            });
        }
        CommonEditorRegistry.registerDefaultLanguageCommand = registerDefaultLanguageCommand;
    })(CommonEditorRegistry = exports.CommonEditorRegistry || (exports.CommonEditorRegistry = {}));
    // Editor extension points
    var Extensions = {
        EditorCommonContributions: 'editor.commonContributions'
    };
    var EditorContributionRegistry = (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) {
            var menuItem = action.toMenuItem();
            if (menuItem) {
                actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.EditorContext, menuItem);
            }
            keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule(action.toCommandAndKeybindingRule(keybindingsRegistry_1.KeybindingsRegistry.WEIGHT.editorContrib()));
            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) {
            keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule(editorCommand.toCommandAndKeybindingRule(keybindingsRegistry_1.KeybindingsRegistry.WEIGHT.editorContrib()));
            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);
});











define(__m[447/*vs/editor/common/commonCodeEditor*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,11/*vs/base/common/event*/,3/*vs/base/common/lifecycle*/,7/*vs/base/common/winjs.base*/,84/*vs/platform/instantiation/common/serviceCollection*/,19/*vs/platform/contextkey/common/contextkey*/,321/*vs/editor/common/controller/cursor*/,39/*vs/editor/common/controller/cursorCommon*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,20/*vs/editor/common/editorCommon*/,330/*vs/editor/common/viewModel/viewModelImpl*/,488/*vs/base/common/hash*/,406/*vs/editor/common/modes/editorModeContext*/,55/*vs/editor/common/model/textModelEvents*/,21/*vs/editor/common/editorContextKeys*/,13/*vs/editor/common/editorCommonExtensions*/]), function (require, exports, errors_1, event_1, lifecycle_1, winjs_base_1, serviceCollection_1, contextkey_1, cursor_1, cursorCommon_1, position_1, range_1, selection_1, editorCommon, viewModelImpl_1, hash_1, editorModeContext_1, textModelEvents_1, editorContextKeys_1, editorCommonExtensions_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var EDITOR_ID = 0;
    var CommonCodeEditor = (function (_super) {
        __extends(CommonCodeEditor, _super);
        function CommonCodeEditor(domElement, options, instantiationService, contextKeyService) {
            var _this = _super.call(this) || this;
            _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._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._onDidLayoutChange = _this._register(new event_1.Emitter());
            _this.onDidLayoutChange = _this._onDidLayoutChange.event;
            _this._onDidFocusEditorText = _this._register(new event_1.Emitter());
            _this.onDidFocusEditorText = _this._onDidFocusEditorText.event;
            _this._onDidBlurEditorText = _this._register(new event_1.Emitter());
            _this.onDidBlurEditorText = _this._onDidBlurEditorText.event;
            _this._onDidFocusEditor = _this._register(new event_1.Emitter());
            _this.onDidFocusEditor = _this._onDidFocusEditor.event;
            _this._onDidBlurEditor = _this._register(new event_1.Emitter());
            _this.onDidBlurEditor = _this._onDidBlurEditor.event;
            _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._onDidPaste = _this._register(new event_1.Emitter());
            _this.onDidPaste = _this._onDidPaste.event;
            _this.domElement = domElement;
            _this.id = (++EDITOR_ID);
            _this._decorationTypeKeysToIds = {};
            _this._decorationTypeSubtypes = {};
            options = options || {};
            _this._configuration = _this._register(_this._createConfiguration(options));
            _this._register(_this._configuration.onDidChange(function (e) {
                _this._onDidChangeConfiguration.fire(e);
                if (e.layoutInfo) {
                    _this._onDidLayoutChange.fire(_this._configuration.editor.layoutInfo);
                }
            }));
            _this._contextKeyService = _this._register(contextKeyService.createScoped(_this.domElement));
            _this._register(new EditorContextKeysManager(_this, _this._contextKeyService));
            _this._register(new editorModeContext_1.EditorModeContext(_this, _this._contextKeyService));
            _this._instantiationService = instantiationService.createChild(new serviceCollection_1.ServiceCollection([contextkey_1.IContextKeyService, _this._contextKeyService]));
            _this._attachModel(null);
            _this._contributions = {};
            _this._actions = {};
            return _this;
        }
        CommonCodeEditor.prototype.getId = function () {
            return this.getEditorType() + ':' + this.id;
        };
        CommonCodeEditor.prototype.getEditorType = function () {
            return editorCommon.EditorType.ICodeEditor;
        };
        CommonCodeEditor.prototype.destroy = function () {
            this.dispose();
        };
        CommonCodeEditor.prototype.dispose = function () {
            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._contributions = {};
            // editor actions don't need to be disposed
            this._actions = {};
            this._postDetachModelCleanup(this._detachModel());
            this._onDidDispose.fire();
            _super.prototype.dispose.call(this);
        };
        CommonCodeEditor.prototype.invokeWithinContext = function (fn) {
            return this._instantiationService.invokeFunction(fn);
        };
        CommonCodeEditor.prototype.updateOptions = function (newOptions) {
            this._configuration.updateOptions(newOptions);
        };
        CommonCodeEditor.prototype.getConfiguration = function () {
            return this._configuration.editor;
        };
        CommonCodeEditor.prototype.getRawConfiguration = function () {
            return this._configuration.getRawOptions();
        };
        CommonCodeEditor.prototype.getValue = function (options) {
            if (options === void 0) { options = null; }
            if (this.model) {
                var preserveBOM = (options && options.preserveBOM) ? true : false;
                var eolPreference = editorCommon.EndOfLinePreference.TextDefined;
                if (options && options.lineEnding && options.lineEnding === '\n') {
                    eolPreference = editorCommon.EndOfLinePreference.LF;
                }
                else if (options && options.lineEnding && options.lineEnding === '\r\n') {
                    eolPreference = editorCommon.EndOfLinePreference.CRLF;
                }
                return this.model.getValue(eolPreference, preserveBOM);
            }
            return '';
        };
        CommonCodeEditor.prototype.setValue = function (newValue) {
            if (this.model) {
                this.model.setValue(newValue);
            }
        };
        CommonCodeEditor.prototype.getModel = function () {
            return this.model;
        };
        CommonCodeEditor.prototype.setModel = function (model) {
            if (model === void 0) { model = null; }
            if (this.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._onDidChangeModel.fire(e);
            this._postDetachModelCleanup(detachedModel);
        };
        CommonCodeEditor.prototype.getCenteredRangeInViewport = function () {
            if (!this.hasView) {
                return null;
            }
            return this.viewModel.getCenteredRangeInViewport();
        };
        CommonCodeEditor.prototype.getVisibleColumnFromPosition = function (rawPosition) {
            if (!this.model) {
                return rawPosition.column;
            }
            var position = this.model.validatePosition(rawPosition);
            var tabSize = this.model.getOptions().tabSize;
            return cursorCommon_1.CursorColumns.visibleColumnFromColumn(this.model.getLineContent(position.lineNumber), position.column, tabSize) + 1;
        };
        CommonCodeEditor.prototype.getPosition = function () {
            if (!this.cursor) {
                return null;
            }
            return this.cursor.getPosition().clone();
        };
        CommonCodeEditor.prototype.setPosition = function (position, reveal, revealVerticalInCenter, revealHorizontal) {
            if (reveal === void 0) { reveal = false; }
            if (revealVerticalInCenter === void 0) { revealVerticalInCenter = false; }
            if (revealHorizontal === void 0) { revealHorizontal = false; }
            if (!this.cursor) {
                return;
            }
            if (!position_1.Position.isIPosition(position)) {
                throw new Error('Invalid arguments');
            }
            this.cursor.setSelections('api', [{
                    selectionStartLineNumber: position.lineNumber,
                    selectionStartColumn: position.column,
                    positionLineNumber: position.lineNumber,
                    positionColumn: position.column
                }]);
            if (reveal) {
                this.revealPosition(position, revealVerticalInCenter, revealHorizontal);
            }
        };
        CommonCodeEditor.prototype._sendRevealRange = function (modelRange, verticalType, revealHorizontal) {
            if (!this.model || !this.cursor) {
                return;
            }
            if (!range_1.Range.isIRange(modelRange)) {
                throw new Error('Invalid arguments');
            }
            var validatedModelRange = this.model.validateRange(modelRange);
            var viewRange = this.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange);
            this.cursor.emitCursorRevealRange(viewRange, verticalType, revealHorizontal);
        };
        CommonCodeEditor.prototype.revealLine = function (lineNumber) {
            this._revealLine(lineNumber, 0 /* Simple */);
        };
        CommonCodeEditor.prototype.revealLineInCenter = function (lineNumber) {
            this._revealLine(lineNumber, 1 /* Center */);
        };
        CommonCodeEditor.prototype.revealLineInCenterIfOutsideViewport = function (lineNumber) {
            this._revealLine(lineNumber, 2 /* CenterIfOutsideViewport */);
        };
        CommonCodeEditor.prototype._revealLine = function (lineNumber, revealType) {
            if (typeof lineNumber !== 'number') {
                throw new Error('Invalid arguments');
            }
            this._sendRevealRange(new range_1.Range(lineNumber, 1, lineNumber, 1), revealType, false);
        };
        CommonCodeEditor.prototype.revealPosition = function (position, revealVerticalInCenter, revealHorizontal) {
            if (revealVerticalInCenter === void 0) { revealVerticalInCenter = false; }
            if (revealHorizontal === void 0) { revealHorizontal = false; }
            this._revealPosition(position, revealVerticalInCenter ? 1 /* Center */ : 0 /* Simple */, revealHorizontal);
        };
        CommonCodeEditor.prototype.revealPositionInCenter = function (position) {
            this._revealPosition(position, 1 /* Center */, true);
        };
        CommonCodeEditor.prototype.revealPositionInCenterIfOutsideViewport = function (position) {
            this._revealPosition(position, 2 /* CenterIfOutsideViewport */, true);
        };
        CommonCodeEditor.prototype._revealPosition = function (position, verticalType, revealHorizontal) {
            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);
        };
        CommonCodeEditor.prototype.getSelection = function () {
            if (!this.cursor) {
                return null;
            }
            return this.cursor.getSelection().clone();
        };
        CommonCodeEditor.prototype.getSelections = function () {
            if (!this.cursor) {
                return null;
            }
            var selections = this.cursor.getSelections();
            var result = [];
            for (var i = 0, len = selections.length; i < len; i++) {
                result[i] = selections[i].clone();
            }
            return result;
        };
        CommonCodeEditor.prototype.setSelection = function (something, reveal, revealVerticalInCenter, revealHorizontal) {
            if (reveal === void 0) { reveal = false; }
            if (revealVerticalInCenter === void 0) { revealVerticalInCenter = false; }
            if (revealHorizontal === void 0) { revealHorizontal = false; }
            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, reveal, revealVerticalInCenter, revealHorizontal);
            }
            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, reveal, revealVerticalInCenter, revealHorizontal);
            }
        };
        CommonCodeEditor.prototype._setSelectionImpl = function (sel, reveal, revealVerticalInCenter, revealHorizontal) {
            if (!this.cursor) {
                return;
            }
            var selection = new selection_1.Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
            this.cursor.setSelections('api', [selection]);
            if (reveal) {
                this.revealRange(selection, revealVerticalInCenter, revealHorizontal);
            }
        };
        CommonCodeEditor.prototype.revealLines = function (startLineNumber, endLineNumber) {
            this._revealLines(startLineNumber, endLineNumber, 0 /* Simple */);
        };
        CommonCodeEditor.prototype.revealLinesInCenter = function (startLineNumber, endLineNumber) {
            this._revealLines(startLineNumber, endLineNumber, 1 /* Center */);
        };
        CommonCodeEditor.prototype.revealLinesInCenterIfOutsideViewport = function (startLineNumber, endLineNumber) {
            this._revealLines(startLineNumber, endLineNumber, 2 /* CenterIfOutsideViewport */);
        };
        CommonCodeEditor.prototype._revealLines = function (startLineNumber, endLineNumber, verticalType) {
            if (typeof startLineNumber !== 'number' || typeof endLineNumber !== 'number') {
                throw new Error('Invalid arguments');
            }
            this._sendRevealRange(new range_1.Range(startLineNumber, 1, endLineNumber, 1), verticalType, false);
        };
        CommonCodeEditor.prototype.revealRange = function (range, revealVerticalInCenter, revealHorizontal) {
            if (revealVerticalInCenter === void 0) { revealVerticalInCenter = false; }
            if (revealHorizontal === void 0) { revealHorizontal = true; }
            this._revealRange(range, revealVerticalInCenter ? 1 /* Center */ : 0 /* Simple */, revealHorizontal);
        };
        CommonCodeEditor.prototype.revealRangeInCenter = function (range) {
            this._revealRange(range, 1 /* Center */, true);
        };
        CommonCodeEditor.prototype.revealRangeInCenterIfOutsideViewport = function (range) {
            this._revealRange(range, 2 /* CenterIfOutsideViewport */, true);
        };
        CommonCodeEditor.prototype.revealRangeAtTop = function (range) {
            this._revealRange(range, 3 /* Top */, true);
        };
        CommonCodeEditor.prototype._revealRange = function (range, verticalType, revealHorizontal) {
            if (!range_1.Range.isIRange(range)) {
                throw new Error('Invalid arguments');
            }
            this._sendRevealRange(range_1.Range.lift(range), verticalType, revealHorizontal);
        };
        CommonCodeEditor.prototype.setSelections = function (ranges) {
            if (!this.cursor) {
                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.cursor.setSelections('api', ranges);
        };
        CommonCodeEditor.prototype.getScrollWidth = function () {
            if (!this.hasView) {
                return -1;
            }
            return this.viewModel.viewLayout.getScrollWidth();
        };
        CommonCodeEditor.prototype.getScrollLeft = function () {
            if (!this.hasView) {
                return -1;
            }
            return this.viewModel.viewLayout.getScrollLeft();
        };
        CommonCodeEditor.prototype.getScrollHeight = function () {
            if (!this.hasView) {
                return -1;
            }
            return this.viewModel.viewLayout.getScrollHeight();
        };
        CommonCodeEditor.prototype.getScrollTop = function () {
            if (!this.hasView) {
                return -1;
            }
            return this.viewModel.viewLayout.getScrollTop();
        };
        CommonCodeEditor.prototype.setScrollLeft = function (newScrollLeft) {
            if (!this.hasView) {
                return;
            }
            if (typeof newScrollLeft !== 'number') {
                throw new Error('Invalid arguments');
            }
            this.viewModel.viewLayout.setScrollPosition({
                scrollLeft: newScrollLeft
            });
        };
        CommonCodeEditor.prototype.setScrollTop = function (newScrollTop) {
            if (!this.hasView) {
                return;
            }
            if (typeof newScrollTop !== 'number') {
                throw new Error('Invalid arguments');
            }
            this.viewModel.viewLayout.setScrollPosition({
                scrollTop: newScrollTop
            });
        };
        CommonCodeEditor.prototype.setScrollPosition = function (position) {
            if (!this.hasView) {
                return;
            }
            this.viewModel.viewLayout.setScrollPosition(position);
        };
        CommonCodeEditor.prototype.saveViewState = function () {
            if (!this.cursor || !this.hasView) {
                return null;
            }
            var 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.saveViewState === 'function') {
                    contributionsState[id] = contribution.saveViewState();
                }
            }
            var cursorState = this.cursor.saveState();
            var viewState = this.viewModel.viewLayout.saveState();
            return {
                cursorState: cursorState,
                viewState: viewState,
                contributionsState: contributionsState
            };
        };
        CommonCodeEditor.prototype.restoreViewState = function (s) {
            if (!this.cursor || !this.hasView) {
                return;
            }
            if (s && s.cursorState && s.viewState) {
                var codeEditorState = s;
                var cursorState = codeEditorState.cursorState;
                if (Array.isArray(cursorState)) {
                    this.cursor.restoreState(cursorState);
                }
                else {
                    // Backwards compatibility
                    this.cursor.restoreState([cursorState]);
                }
                this.viewModel.viewLayout.restoreState(codeEditorState.viewState);
                var contributionsState = s.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]);
                    }
                }
            }
        };
        CommonCodeEditor.prototype.onVisible = function () {
        };
        CommonCodeEditor.prototype.onHide = function () {
        };
        CommonCodeEditor.prototype.getContribution = function (id) {
            return (this._contributions[id] || null);
        };
        CommonCodeEditor.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;
        };
        CommonCodeEditor.prototype.getSupportedActions = function () {
            var result = this.getActions();
            result = result.filter(function (action) { return action.isSupported(); });
            return result;
        };
        CommonCodeEditor.prototype.getAction = function (id) {
            return this._actions[id] || null;
        };
        CommonCodeEditor.prototype.trigger = function (source, handlerId, payload) {
            payload = payload || {};
            // Special case for typing
            if (handlerId === editorCommon.Handler.Type) {
                if (!this.cursor || typeof payload.text !== 'string' || payload.text.length === 0) {
                    // nothing to do
                    return;
                }
                if (source === 'keyboard') {
                    this._onWillType.fire(payload.text);
                }
                this.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.cursor || typeof payload.text !== 'string' || payload.text.length === 0) {
                    // nothing to do
                    return;
                }
                var startPosition = this.cursor.getSelection().getStartPosition();
                this.cursor.trigger(source, handlerId, payload);
                var endPosition = this.cursor.getSelection().getStartPosition();
                if (source === 'keyboard') {
                    this._onDidPaste.fire(new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column));
                }
                return;
            }
            var action = this.getAction(handlerId);
            if (action) {
                winjs_base_1.TPromise.as(action.run()).done(null, errors_1.onUnexpectedError);
                return;
            }
            if (!this.cursor) {
                return;
            }
            var command = editorCommonExtensions_1.CommonEditorRegistry.getEditorCommand(handlerId);
            if (command) {
                payload = payload || {};
                payload.source = source;
                winjs_base_1.TPromise.as(command.runEditorCommand(null, this, payload)).done(null, errors_1.onUnexpectedError);
                return;
            }
            this.cursor.trigger(source, handlerId, payload);
        };
        CommonCodeEditor.prototype._getCursors = function () {
            return this.cursor;
        };
        CommonCodeEditor.prototype._getCursorConfiguration = function () {
            return this.cursor.context.config;
        };
        CommonCodeEditor.prototype.pushUndoStop = function () {
            if (!this.model) {
                return false;
            }
            if (this._configuration.editor.readOnly) {
                // read only editor => sorry!
                return false;
            }
            this.model.pushStackElement();
            return true;
        };
        CommonCodeEditor.prototype.executeEdits = function (source, edits, endCursorState) {
            var _this = this;
            if (!this.cursor) {
                // no view, no cursor
                return false;
            }
            if (this._configuration.editor.readOnly) {
                // read only editor => sorry!
                return false;
            }
            this.model.pushEditOperations(this.cursor.getSelections(), edits, function () {
                return endCursorState ? endCursorState : _this.cursor.getSelections();
            });
            if (endCursorState) {
                this.cursor.setSelections(source, endCursorState);
            }
            return true;
        };
        CommonCodeEditor.prototype.executeCommand = function (source, command) {
            if (!this.cursor) {
                return;
            }
            this.cursor.trigger(source, editorCommon.Handler.ExecuteCommand, command);
        };
        CommonCodeEditor.prototype.executeCommands = function (source, commands) {
            if (!this.cursor) {
                return;
            }
            this.cursor.trigger(source, editorCommon.Handler.ExecuteCommands, commands);
        };
        CommonCodeEditor.prototype.changeDecorations = function (callback) {
            if (!this.model) {
                //			console.warn('Cannot change decorations on editor that is not attached to a model');
                // callback will not be called
                return null;
            }
            return this.model.changeDecorations(callback, this.id);
        };
        CommonCodeEditor.prototype.getLineDecorations = function (lineNumber) {
            if (!this.model) {
                return null;
            }
            return this.model.getLineDecorations(lineNumber, this.id, this._configuration.editor.readOnly);
        };
        CommonCodeEditor.prototype.deltaDecorations = function (oldDecorations, newDecorations) {
            if (!this.model) {
                return [];
            }
            if (oldDecorations.length === 0 && newDecorations.length === 0) {
                return oldDecorations;
            }
            return this.model.deltaDecorations(oldDecorations, newDecorations, this.id);
        };
        CommonCodeEditor.prototype.setDecorations = function (decorationTypeKey, decorationOptions) {
            var newDecorationsSubTypes = {};
            var oldDecorationsSubTypes = this._decorationTypeSubtypes[decorationTypeKey] || {};
            this._decorationTypeSubtypes[decorationTypeKey] = newDecorationsSubTypes;
            var newModelDecorations = [];
            for (var _i = 0, decorationOptions_1 = decorationOptions; _i < decorationOptions_1.length; _i++) {
                var decorationOption = decorationOptions_1[_i];
                var typeKey = decorationTypeKey;
                if (decorationOption.renderOptions) {
                    // identify custom reder options by a hash code over all keys and values
                    // For custom render options register a decoration type if necessary
                    var subType = hash_1.hash(decorationOption.renderOptions).toString(16);
                    // The fact that `decorationTypeKey` appears in the typeKey has no influence
                    // it is just a mechanism to get predictable and unique keys (repeatable for the same options and unique across clients)
                    typeKey = decorationTypeKey + '-' + subType;
                    if (!oldDecorationsSubTypes[subType] && !newDecorationsSubTypes[subType]) {
                        // decoration type did not exist before, register new one
                        this._registerDecorationType(typeKey, decorationOption.renderOptions, decorationTypeKey);
                    }
                    newDecorationsSubTypes[subType] = true;
                }
                var opts = this._resolveDecorationOptions(typeKey, !!decorationOption.hoverMessage);
                if (decorationOption.hoverMessage) {
                    opts.hoverMessage = decorationOption.hoverMessage;
                }
                newModelDecorations.push({ range: decorationOption.range, options: opts });
            }
            // remove decoration sub types that are no longer used, deregister decoration type if necessary
            for (var subType in oldDecorationsSubTypes) {
                if (!newDecorationsSubTypes[subType]) {
                    this._removeDecorationType(decorationTypeKey + '-' + subType);
                }
            }
            // update all decorations
            var oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey] || [];
            this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationsIds, newModelDecorations);
        };
        CommonCodeEditor.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];
            }
        };
        CommonCodeEditor.prototype.getLayoutInfo = function () {
            return this._configuration.editor.layoutInfo;
        };
        CommonCodeEditor.prototype._attachModel = function (model) {
            var _this = this;
            this.model = model ? model : null;
            this.listenersToRemove = [];
            this.viewModel = null;
            this.cursor = null;
            if (this.model) {
                this.domElement.setAttribute('data-mode-id', this.model.getLanguageIdentifier().language);
                this._configuration.setIsDominatedByLongLines(this.model.isDominatedByLongLines());
                this._configuration.setMaxLineNumber(this.model.getLineCount());
                this.model.onBeforeAttached();
                this.viewModel = new viewModelImpl_1.ViewModel(this.id, this._configuration, this.model);
                this.listenersToRemove.push(this.model.addBulkListener(function (events) {
                    for (var i = 0, len = events.length; i < len; i++) {
                        var eventType = events[i].type;
                        var e = events[i].data;
                        switch (eventType) {
                            case textModelEvents_1.TextModelEventType.ModelDecorationsChanged:
                                _this._onDidChangeModelDecorations.fire(e);
                                break;
                            case textModelEvents_1.TextModelEventType.ModelLanguageChanged:
                                _this.domElement.setAttribute('data-mode-id', _this.model.getLanguageIdentifier().language);
                                _this._onDidChangeModelLanguage.fire(e);
                                break;
                            case textModelEvents_1.TextModelEventType.ModelContentChanged:
                                _this._onDidChangeModelContent.fire(e);
                                break;
                            case textModelEvents_1.TextModelEventType.ModelOptionsChanged:
                                _this._onDidChangeModelOptions.fire(e);
                                break;
                            case textModelEvents_1.TextModelEventType.ModelDispose:
                                // Someone might destroy the model from under the editor, so prevent any exceptions by setting a null model
                                _this.setModel(null);
                                break;
                            default:
                        }
                    }
                }));
                this.cursor = new cursor_1.Cursor(this._configuration, this.model, this.viewModel);
                this._createView();
                this.listenersToRemove.push(this.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);
                }));
            }
            else {
                this.hasView = false;
            }
        };
        CommonCodeEditor.prototype._postDetachModelCleanup = function (detachedModel) {
            if (detachedModel) {
                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 = {};
                }
                detachedModel.removeAllDecorationsWithOwnerId(this.id);
            }
        };
        CommonCodeEditor.prototype._detachModel = function () {
            if (this.model) {
                this.model.onBeforeDetached();
            }
            this.hasView = false;
            this.listenersToRemove = lifecycle_1.dispose(this.listenersToRemove);
            if (this.cursor) {
                this.cursor.dispose();
                this.cursor = null;
            }
            if (this.viewModel) {
                this.viewModel.dispose();
                this.viewModel = null;
            }
            var result = this.model;
            this.model = null;
            this.domElement.removeAttribute('data-mode-id');
            return result;
        };
        CommonCodeEditor.prototype.getTelemetryData = function () {
            return null;
        };
        return CommonCodeEditor;
    }(lifecycle_1.Disposable));
    exports.CommonCodeEditor = CommonCodeEditor;
    var EditorContextKeysManager = (function (_super) {
        __extends(EditorContextKeysManager, _super);
        function EditorContextKeysManager(editor, contextKeyService) {
            var _this = _super.call(this) || this;
            _this._editor = editor;
            _this._editorId = contextKeyService.createKey('editorId', editor.getId());
            _this._editorFocus = editorContextKeys_1.EditorContextKeys.focus.bindTo(contextKeyService);
            _this._editorTextFocus = editorContextKeys_1.EditorContextKeys.textFocus.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._register(_this._editor.onDidChangeConfiguration(function () { return _this._updateFromConfig(); }));
            _this._register(_this._editor.onDidChangeCursorSelection(function () { return _this._updateFromSelection(); }));
            _this._register(_this._editor.onDidFocusEditor(function () { return _this._updateFromFocus(); }));
            _this._register(_this._editor.onDidBlurEditor(function () { return _this._updateFromFocus(); }));
            _this._register(_this._editor.onDidFocusEditorText(function () { return _this._updateFromFocus(); }));
            _this._register(_this._editor.onDidBlurEditorText(function () { return _this._updateFromFocus(); }));
            _this._updateFromConfig();
            _this._updateFromSelection();
            _this._updateFromFocus();
            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._editorTextFocus.set(this._editor.isFocused());
        };
        return EditorContextKeysManager;
    }(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[134/*vs/editor/common/controller/coreCommands*/], __M([1/*require*/,0/*exports*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,39/*vs/editor/common/controller/cursorCommon*/,54/*vs/editor/common/controller/cursorEvents*/,173/*vs/editor/common/controller/cursorMoveCommands*/,13/*vs/editor/common/editorCommonExtensions*/,311/*vs/editor/common/controller/cursorColumnSelection*/,21/*vs/editor/common/editorContextKeys*/,105/*vs/platform/keybinding/common/keybindingsRegistry*/,42/*vs/editor/common/services/codeEditorService*/,19/*vs/platform/contextkey/common/contextkey*/,29/*vs/base/common/types*/,64/*vs/platform/editor/common/editor*/,119/*vs/editor/common/controller/cursorTypeOperations*/,170/*vs/editor/common/controller/cursorDeleteOperations*/]), function (require, exports, position_1, range_1, editorCommon, cursorCommon_1, cursorEvents_1, cursorMoveCommands_1, editorCommonExtensions_1, cursorColumnSelection_1, editorContextKeys_1, keybindingsRegistry_1, codeEditorService_1, contextkey_1, types, editor_1, cursorTypeOperations_1, cursorDeleteOperations_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var H = editorCommon.Handler;
    var CORE_WEIGHT = keybindingsRegistry_1.KeybindingsRegistry.WEIGHT.editorCore();
    var CoreEditorCommand = (function (_super) {
        __extends(CoreEditorCommand, _super);
        function CoreEditorCommand() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        CoreEditorCommand.prototype.runEditorCommand = function (accessor, editor, args) {
            this.runCoreEditorCommand(editor._getCursors(), args || {});
        };
        return CoreEditorCommand;
    }(editorCommonExtensions_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
                }
            ]
        };
        /**
         * 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;
        var Direction;
        (function (Direction) {
            Direction[Direction["Up"] = 1] = "Up";
            Direction[Direction["Down"] = 2] = "Down";
        })(Direction = EditorScroll_.Direction || (EditorScroll_.Direction = {}));
        var Unit;
        (function (Unit) {
            Unit[Unit["Line"] = 1] = "Line";
            Unit[Unit["WrappedLine"] = 2] = "WrappedLine";
            Unit[Unit["Page"] = 3] = "Page";
            Unit[Unit["HalfPage"] = 4] = "HalfPage";
        })(Unit = EditorScroll_.Unit || (EditorScroll_.Unit = {}));
    })(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
                }
            ]
        };
        ;
        /**
         * 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 = (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, cursorEvents_1.CursorChangeReason.Explicit, [
                    cursorMoveCommands_1.CursorMoveCommands.moveTo(cursors.context, cursors.getPrimaryCursor(), this._inSelectionMode, args.position, args.viewPosition)
                ]);
                cursors.reveal(true, 0 /* Primary */);
            };
            return BaseMoveToCommand;
        }(CoreEditorCommand));
        CoreNavigationCommands.MoveTo = editorCommonExtensions_1.registerEditorCommand(new BaseMoveToCommand({
            id: '_moveTo',
            inSelectionMode: false,
            precondition: null
        }));
        CoreNavigationCommands.MoveToSelect = editorCommonExtensions_1.registerEditorCommand(new BaseMoveToCommand({
            id: '_moveToSelect',
            inSelectionMode: true,
            precondition: null
        }));
        var ColumnSelectCommand = (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, cursorEvents_1.CursorChangeReason.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 */));
            };
            return ColumnSelectCommand;
        }(CoreEditorCommand));
        CoreNavigationCommands.ColumnSelect = editorCommonExtensions_1.registerEditorCommand(new (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 = editorCommonExtensions_1.registerEditorCommand(new (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.textFocus,
                        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 = editorCommonExtensions_1.registerEditorCommand(new (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.textFocus,
                        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 = (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 = editorCommonExtensions_1.registerEditorCommand(new ColumnSelectUpCommand({
            isPaged: false,
            id: 'cursorColumnSelectUp',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 16 /* UpArrow */,
                linux: { primary: 0 }
            }
        }));
        CoreNavigationCommands.CursorColumnSelectPageUp = editorCommonExtensions_1.registerEditorCommand(new ColumnSelectUpCommand({
            isPaged: true,
            id: 'cursorColumnSelectPageUp',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 11 /* PageUp */,
                linux: { primary: 0 }
            }
        }));
        var ColumnSelectDownCommand = (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 = editorCommonExtensions_1.registerEditorCommand(new ColumnSelectDownCommand({
            isPaged: false,
            id: 'cursorColumnSelectDown',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 18 /* DownArrow */,
                linux: { primary: 0 }
            }
        }));
        CoreNavigationCommands.CursorColumnSelectPageDown = editorCommonExtensions_1.registerEditorCommand(new ColumnSelectDownCommand({
            isPaged: true,
            id: 'cursorColumnSelectPageDown',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 12 /* PageDown */,
                linux: { primary: 0 }
            }
        }));
        var CursorMoveImpl = (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, cursorEvents_1.CursorChangeReason.Explicit, cursorCommon_1.CursorState.ensureInEditableRange(cursors.context, cursorMoveCommands_1.CursorMoveCommands.move(cursors.context, cursors.getAll(), args)));
                cursors.reveal(true, 0 /* Primary */);
            };
            return CursorMoveImpl;
        }(CoreEditorCommand));
        CoreNavigationCommands.CursorMoveImpl = CursorMoveImpl;
        CoreNavigationCommands.CursorMove = editorCommonExtensions_1.registerEditorCommand(new CursorMoveImpl());
        var Constants;
        (function (Constants) {
            Constants[Constants["PAGE_SIZE_MARKER"] = -1] = "PAGE_SIZE_MARKER";
        })(Constants || (Constants = {}));
        var CursorMoveBasedCommand = (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 = editorCommonExtensions_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.textFocus,
                primary: 15 /* LeftArrow */,
                mac: { primary: 15 /* LeftArrow */, secondary: [256 /* WinCtrl */ | 32 /* KEY_B */] }
            }
        }));
        CoreNavigationCommands.CursorLeftSelect = editorCommonExtensions_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.textFocus,
                primary: 1024 /* Shift */ | 15 /* LeftArrow */
            }
        }));
        CoreNavigationCommands.CursorRight = editorCommonExtensions_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.textFocus,
                primary: 17 /* RightArrow */,
                mac: { primary: 17 /* RightArrow */, secondary: [256 /* WinCtrl */ | 36 /* KEY_F */] }
            }
        }));
        CoreNavigationCommands.CursorRightSelect = editorCommonExtensions_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.textFocus,
                primary: 1024 /* Shift */ | 17 /* RightArrow */
            }
        }));
        CoreNavigationCommands.CursorUp = editorCommonExtensions_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.textFocus,
                primary: 16 /* UpArrow */,
                mac: { primary: 16 /* UpArrow */, secondary: [256 /* WinCtrl */ | 46 /* KEY_P */] }
            }
        }));
        CoreNavigationCommands.CursorUpSelect = editorCommonExtensions_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.textFocus,
                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 = editorCommonExtensions_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.textFocus,
                primary: 11 /* PageUp */
            }
        }));
        CoreNavigationCommands.CursorPageUpSelect = editorCommonExtensions_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.textFocus,
                primary: 1024 /* Shift */ | 11 /* PageUp */
            }
        }));
        CoreNavigationCommands.CursorDown = editorCommonExtensions_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.textFocus,
                primary: 18 /* DownArrow */,
                mac: { primary: 18 /* DownArrow */, secondary: [256 /* WinCtrl */ | 44 /* KEY_N */] }
            }
        }));
        CoreNavigationCommands.CursorDownSelect = editorCommonExtensions_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.textFocus,
                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 = editorCommonExtensions_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.textFocus,
                primary: 12 /* PageDown */
            }
        }));
        CoreNavigationCommands.CursorPageDownSelect = editorCommonExtensions_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.textFocus,
                primary: 1024 /* Shift */ | 12 /* PageDown */
            }
        }));
        CoreNavigationCommands.CreateCursor = editorCommonExtensions_1.registerEditorCommand(new (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;
                if (context.config.readOnly || context.model.hasEditableRange()) {
                    return;
                }
                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, cursorEvents_1.CursorChangeReason.Explicit, states);
                        return;
                    }
                }
                // => Add the new cursor
                states.push(newState);
                cursors.context.model.pushStackElement();
                cursors.setStates(args.source, cursorEvents_1.CursorChangeReason.Explicit, states);
            };
            return class_4;
        }(CoreEditorCommand)));
        CoreNavigationCommands.LastCursorMoveToSelect = editorCommonExtensions_1.registerEditorCommand(new (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;
                if (context.config.readOnly || context.model.hasEditableRange()) {
                    return;
                }
                var lastAddedCursorIndex = cursors.getLastAddedCursorIndex();
                var newStates = cursors.getAll().slice(0);
                newStates[lastAddedCursorIndex] = cursorMoveCommands_1.CursorMoveCommands.moveTo(context, newStates[lastAddedCursorIndex], true, args.position, args.viewPosition);
                cursors.context.model.pushStackElement();
                cursors.setStates(args.source, cursorEvents_1.CursorChangeReason.Explicit, newStates);
            };
            return class_5;
        }(CoreEditorCommand)));
        var HomeCommand = (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, cursorEvents_1.CursorChangeReason.Explicit, cursorCommon_1.CursorState.ensureInEditableRange(cursors.context, cursorMoveCommands_1.CursorMoveCommands.moveToBeginningOfLine(cursors.context, cursors.getAll(), this._inSelectionMode)));
                cursors.reveal(true, 0 /* Primary */);
            };
            return HomeCommand;
        }(CoreEditorCommand));
        CoreNavigationCommands.CursorHome = editorCommonExtensions_1.registerEditorCommand(new HomeCommand({
            inSelectionMode: false,
            id: 'cursorHome',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 14 /* Home */,
                mac: { primary: 14 /* Home */, secondary: [2048 /* CtrlCmd */ | 15 /* LeftArrow */] }
            }
        }));
        CoreNavigationCommands.CursorHomeSelect = editorCommonExtensions_1.registerEditorCommand(new HomeCommand({
            inSelectionMode: true,
            id: 'cursorHomeSelect',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 1024 /* Shift */ | 14 /* Home */,
                mac: { primary: 1024 /* Shift */ | 14 /* Home */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 15 /* LeftArrow */] }
            }
        }));
        CoreNavigationCommands.CursorLineStart = editorCommonExtensions_1.registerEditorCommand(new (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.textFocus,
                        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, cursorEvents_1.CursorChangeReason.Explicit, cursorCommon_1.CursorState.ensureInEditableRange(cursors.context, this._exec(cursors.context, cursors.getAll())));
                cursors.reveal(true, 0 /* Primary */);
            };
            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 = (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, cursorEvents_1.CursorChangeReason.Explicit, cursorCommon_1.CursorState.ensureInEditableRange(cursors.context, cursorMoveCommands_1.CursorMoveCommands.moveToEndOfLine(cursors.context, cursors.getAll(), this._inSelectionMode)));
                cursors.reveal(true, 0 /* Primary */);
            };
            return EndCommand;
        }(CoreEditorCommand));
        CoreNavigationCommands.CursorEnd = editorCommonExtensions_1.registerEditorCommand(new EndCommand({
            inSelectionMode: false,
            id: 'cursorEnd',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 13 /* End */,
                mac: { primary: 13 /* End */, secondary: [2048 /* CtrlCmd */ | 17 /* RightArrow */] }
            }
        }));
        CoreNavigationCommands.CursorEndSelect = editorCommonExtensions_1.registerEditorCommand(new EndCommand({
            inSelectionMode: true,
            id: 'cursorEndSelect',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 1024 /* Shift */ | 13 /* End */,
                mac: { primary: 1024 /* Shift */ | 13 /* End */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 17 /* RightArrow */] }
            }
        }));
        CoreNavigationCommands.CursorLineEnd = editorCommonExtensions_1.registerEditorCommand(new (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.textFocus,
                        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, cursorEvents_1.CursorChangeReason.Explicit, cursorCommon_1.CursorState.ensureInEditableRange(cursors.context, this._exec(cursors.context, cursors.getAll())));
                cursors.reveal(true, 0 /* Primary */);
            };
            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 = (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, cursorEvents_1.CursorChangeReason.Explicit, cursorCommon_1.CursorState.ensureInEditableRange(cursors.context, cursorMoveCommands_1.CursorMoveCommands.moveToBeginningOfBuffer(cursors.context, cursors.getAll(), this._inSelectionMode)));
                cursors.reveal(true, 0 /* Primary */);
            };
            return TopCommand;
        }(CoreEditorCommand));
        CoreNavigationCommands.CursorTop = editorCommonExtensions_1.registerEditorCommand(new TopCommand({
            inSelectionMode: false,
            id: 'cursorTop',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 14 /* Home */,
                mac: { primary: 2048 /* CtrlCmd */ | 16 /* UpArrow */ }
            }
        }));
        CoreNavigationCommands.CursorTopSelect = editorCommonExtensions_1.registerEditorCommand(new TopCommand({
            inSelectionMode: true,
            id: 'cursorTopSelect',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 14 /* Home */,
                mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 16 /* UpArrow */ }
            }
        }));
        var BottomCommand = (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, cursorEvents_1.CursorChangeReason.Explicit, cursorCommon_1.CursorState.ensureInEditableRange(cursors.context, cursorMoveCommands_1.CursorMoveCommands.moveToEndOfBuffer(cursors.context, cursors.getAll(), this._inSelectionMode)));
                cursors.reveal(true, 0 /* Primary */);
            };
            return BottomCommand;
        }(CoreEditorCommand));
        CoreNavigationCommands.CursorBottom = editorCommonExtensions_1.registerEditorCommand(new BottomCommand({
            inSelectionMode: false,
            id: 'cursorBottom',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 13 /* End */,
                mac: { primary: 2048 /* CtrlCmd */ | 18 /* DownArrow */ }
            }
        }));
        CoreNavigationCommands.CursorBottomSelect = editorCommonExtensions_1.registerEditorCommand(new BottomCommand({
            inSelectionMode: true,
            id: 'cursorBottomSelect',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 13 /* End */,
                mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 18 /* DownArrow */ }
            }
        }));
        var EditorScrollImpl = (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, cursorEvents_1.CursorChangeReason.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.getScrollTop() + deltaLines * context.config.lineHeight;
            };
            return EditorScrollImpl;
        }(CoreEditorCommand));
        CoreNavigationCommands.EditorScrollImpl = EditorScrollImpl;
        CoreNavigationCommands.EditorScroll = editorCommonExtensions_1.registerEditorCommand(new EditorScrollImpl());
        CoreNavigationCommands.ScrollLineUp = editorCommonExtensions_1.registerEditorCommand(new (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.textFocus,
                        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 = editorCommonExtensions_1.registerEditorCommand(new (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.textFocus,
                        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 = editorCommonExtensions_1.registerEditorCommand(new (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.textFocus,
                        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 = editorCommonExtensions_1.registerEditorCommand(new (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.textFocus,
                        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 = (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, cursorEvents_1.CursorChangeReason.Explicit, [
                    cursorMoveCommands_1.CursorMoveCommands.word(cursors.context, cursors.getPrimaryCursor(), this._inSelectionMode, args.position)
                ]);
                cursors.reveal(true, 0 /* Primary */);
            };
            return WordCommand;
        }(CoreEditorCommand));
        CoreNavigationCommands.WordSelect = editorCommonExtensions_1.registerEditorCommand(new WordCommand({
            inSelectionMode: false,
            id: '_wordSelect',
            precondition: null
        }));
        CoreNavigationCommands.WordSelectDrag = editorCommonExtensions_1.registerEditorCommand(new WordCommand({
            inSelectionMode: true,
            id: '_wordSelectDrag',
            precondition: null
        }));
        CoreNavigationCommands.LastCursorWordSelect = editorCommonExtensions_1.registerEditorCommand(new (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;
                if (context.config.readOnly || context.model.hasEditableRange()) {
                    return;
                }
                var lastAddedCursorIndex = cursors.getLastAddedCursorIndex();
                var newStates = cursors.getAll().slice(0);
                newStates[lastAddedCursorIndex] = cursorMoveCommands_1.CursorMoveCommands.word(context, newStates[lastAddedCursorIndex], true, args.position);
                context.model.pushStackElement();
                cursors.setStates(args.source, cursorEvents_1.CursorChangeReason.Explicit, newStates);
            };
            return class_12;
        }(CoreEditorCommand)));
        var LineCommand = (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, cursorEvents_1.CursorChangeReason.Explicit, [
                    cursorMoveCommands_1.CursorMoveCommands.line(cursors.context, cursors.getPrimaryCursor(), this._inSelectionMode, args.position, args.viewPosition)
                ]);
                cursors.reveal(false, 0 /* Primary */);
            };
            return LineCommand;
        }(CoreEditorCommand));
        CoreNavigationCommands.LineSelect = editorCommonExtensions_1.registerEditorCommand(new LineCommand({
            inSelectionMode: false,
            id: '_lineSelect',
            precondition: null
        }));
        CoreNavigationCommands.LineSelectDrag = editorCommonExtensions_1.registerEditorCommand(new LineCommand({
            inSelectionMode: true,
            id: '_lineSelectDrag',
            precondition: null
        }));
        var LastCursorLineCommand = (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 context = cursors.context;
                if (context.config.readOnly || context.model.hasEditableRange()) {
                    return;
                }
                var lastAddedCursorIndex = cursors.getLastAddedCursorIndex();
                var newStates = cursors.getAll().slice(0);
                newStates[lastAddedCursorIndex] = cursorMoveCommands_1.CursorMoveCommands.line(cursors.context, newStates[lastAddedCursorIndex], this._inSelectionMode, args.position, args.viewPosition);
                cursors.context.model.pushStackElement();
                cursors.setStates(args.source, cursorEvents_1.CursorChangeReason.Explicit, newStates);
            };
            return LastCursorLineCommand;
        }(CoreEditorCommand));
        CoreNavigationCommands.LastCursorLineSelect = editorCommonExtensions_1.registerEditorCommand(new LastCursorLineCommand({
            inSelectionMode: false,
            id: 'lastCursorLineSelect',
            precondition: null
        }));
        CoreNavigationCommands.LastCursorLineSelectDrag = editorCommonExtensions_1.registerEditorCommand(new LastCursorLineCommand({
            inSelectionMode: true,
            id: 'lastCursorLineSelectDrag',
            precondition: null
        }));
        CoreNavigationCommands.ExpandLineSelection = editorCommonExtensions_1.registerEditorCommand(new (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.textFocus,
                        primary: 2048 /* CtrlCmd */ | 39 /* KEY_I */
                    }
                }) || this;
            }
            class_13.prototype.runCoreEditorCommand = function (cursors, args) {
                cursors.context.model.pushStackElement();
                cursors.setStates(args.source, cursorEvents_1.CursorChangeReason.Explicit, cursorCommon_1.CursorState.ensureInEditableRange(cursors.context, cursorMoveCommands_1.CursorMoveCommands.expandLineSelection(cursors.context, cursors.getAll())));
                cursors.reveal(true, 0 /* Primary */);
            };
            return class_13;
        }(CoreEditorCommand)));
        CoreNavigationCommands.CancelSelection = editorCommonExtensions_1.registerEditorCommand(new (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.textFocus,
                        primary: 9 /* Escape */,
                        secondary: [1024 /* Shift */ | 9 /* Escape */]
                    }
                }) || this;
            }
            class_14.prototype.runCoreEditorCommand = function (cursors, args) {
                cursors.context.model.pushStackElement();
                cursors.setStates(args.source, cursorEvents_1.CursorChangeReason.Explicit, [
                    cursorMoveCommands_1.CursorMoveCommands.cancelSelection(cursors.context, cursors.getPrimaryCursor())
                ]);
                cursors.reveal(true, 0 /* Primary */);
            };
            return class_14;
        }(CoreEditorCommand)));
        CoreNavigationCommands.RemoveSecondaryCursors = editorCommonExtensions_1.registerEditorCommand(new (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.textFocus,
                        primary: 9 /* Escape */,
                        secondary: [1024 /* Shift */ | 9 /* Escape */]
                    }
                }) || this;
            }
            class_15.prototype.runCoreEditorCommand = function (cursors, args) {
                cursors.context.model.pushStackElement();
                cursors.setStates(args.source, cursorEvents_1.CursorChangeReason.Explicit, [
                    cursors.getPrimaryCursor()
                ]);
                cursors.reveal(true, 0 /* Primary */);
            };
            return class_15;
        }(CoreEditorCommand)));
        CoreNavigationCommands.RevealLine = editorCommonExtensions_1.registerEditorCommand(new (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 + 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);
            };
            return class_16;
        }(CoreEditorCommand)));
        CoreNavigationCommands.SelectAll = editorCommonExtensions_1.registerEditorCommand(new (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, cursorEvents_1.CursorChangeReason.Explicit, [
                    cursorMoveCommands_1.CursorMoveCommands.selectAll(cursors.context, cursors.getPrimaryCursor())
                ]);
            };
            return class_17;
        }(CoreEditorCommand)));
    })(CoreNavigationCommands = exports.CoreNavigationCommands || (exports.CoreNavigationCommands = {}));
    var CoreEditingCommands;
    (function (CoreEditingCommands) {
        CoreEditingCommands.LineBreakInsert = editorCommonExtensions_1.registerEditorCommand(new (function (_super) {
            __extends(class_18, _super);
            function class_18() {
                return _super.call(this, {
                    id: 'lineBreakInsert',
                    precondition: editorContextKeys_1.EditorContextKeys.writable,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                        primary: null,
                        mac: { primary: 256 /* WinCtrl */ | 45 /* KEY_O */ }
                    }
                }) || this;
            }
            class_18.prototype.runEditorCommand = function (accessor, editor, args) {
                editor.pushUndoStop();
                editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.lineBreakInsert(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections()));
            };
            return class_18;
        }(editorCommonExtensions_1.EditorCommand)));
        CoreEditingCommands.Outdent = editorCommonExtensions_1.registerEditorCommand(new (function (_super) {
            __extends(class_19, _super);
            function class_19() {
                return _super.call(this, {
                    id: 'outdent',
                    precondition: editorContextKeys_1.EditorContextKeys.writable,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textFocus, editorContextKeys_1.EditorContextKeys.tabDoesNotMoveFocus),
                        primary: 1024 /* Shift */ | 2 /* Tab */
                    }
                }) || this;
            }
            class_19.prototype.runEditorCommand = function (accessor, editor, args) {
                editor.pushUndoStop();
                editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.outdent(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections()));
                editor.pushUndoStop();
            };
            return class_19;
        }(editorCommonExtensions_1.EditorCommand)));
        CoreEditingCommands.Tab = editorCommonExtensions_1.registerEditorCommand(new (function (_super) {
            __extends(class_20, _super);
            function class_20() {
                return _super.call(this, {
                    id: 'tab',
                    precondition: editorContextKeys_1.EditorContextKeys.writable,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textFocus, editorContextKeys_1.EditorContextKeys.tabDoesNotMoveFocus),
                        primary: 2 /* Tab */
                    }
                }) || this;
            }
            class_20.prototype.runEditorCommand = function (accessor, editor, args) {
                editor.pushUndoStop();
                editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.tab(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections()));
                editor.pushUndoStop();
            };
            return class_20;
        }(editorCommonExtensions_1.EditorCommand)));
        CoreEditingCommands.DeleteLeft = editorCommonExtensions_1.registerEditorCommand(new (function (_super) {
            __extends(class_21, _super);
            function class_21() {
                return _super.call(this, {
                    id: 'deleteLeft',
                    precondition: editorContextKeys_1.EditorContextKeys.writable,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                        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_21.prototype.runEditorCommand = function (accessor, editor, args) {
                var _a = cursorDeleteOperations_1.DeleteOperations.deleteLeft(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections()), shouldPushStackElementBefore = _a[0], commands = _a[1];
                if (shouldPushStackElementBefore) {
                    editor.pushUndoStop();
                }
                editor.executeCommands(this.id, commands);
            };
            return class_21;
        }(editorCommonExtensions_1.EditorCommand)));
        CoreEditingCommands.DeleteRight = editorCommonExtensions_1.registerEditorCommand(new (function (_super) {
            __extends(class_22, _super);
            function class_22() {
                return _super.call(this, {
                    id: 'deleteRight',
                    precondition: editorContextKeys_1.EditorContextKeys.writable,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                        primary: 20 /* Delete */,
                        mac: { primary: 20 /* Delete */, secondary: [256 /* WinCtrl */ | 34 /* KEY_D */, 256 /* WinCtrl */ | 20 /* Delete */] }
                    }
                }) || this;
            }
            class_22.prototype.runEditorCommand = function (accessor, editor, args) {
                var _a = cursorDeleteOperations_1.DeleteOperations.deleteRight(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections()), shouldPushStackElementBefore = _a[0], commands = _a[1];
                if (shouldPushStackElementBefore) {
                    editor.pushUndoStop();
                }
                editor.executeCommands(this.id, commands);
            };
            return class_22;
        }(editorCommonExtensions_1.EditorCommand)));
    })(CoreEditingCommands = exports.CoreEditingCommands || (exports.CoreEditingCommands = {}));
    var Config;
    (function (Config) {
        function findFocusedEditor(accessor) {
            return accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
        }
        function getWorkbenchActiveEditor(accessor) {
            var editorService = accessor.get(editor_1.IEditorService);
            var activeEditor = editorService.getActiveEditor && editorService.getActiveEditor();
            return codeEditorService_1.getCodeEditor(activeEditor);
        }
        function registerCommand(command) {
            keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule(command.toCommandAndKeybindingRule(CORE_WEIGHT));
        }
        /**
         * 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 = (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 = findFocusedEditor(accessor);
                // Only if editor text focus (i.e. not if editor has widget focus).
                if (focusedEditor && focusedEditor.isFocused()) {
                    return this._runEditorHandler(focusedEditor, args);
                }
                // Ignore this action when user is focussed 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 last active editor
                var activeEditor = getWorkbenchActiveEditor(accessor);
                if (activeEditor) {
                    activeEditor.focus();
                    return this._runEditorHandler(activeEditor, args);
                }
            };
            EditorOrNativeTextInputCommand.prototype._runEditorHandler = function (editor, args) {
                var HANDLER = this._editorHandler;
                if (typeof HANDLER === 'string') {
                    editor.trigger('keyboard', HANDLER, args);
                }
                else {
                    args = args || {};
                    args.source = 'keyboard';
                    HANDLER.runEditorCommand(null, editor, args);
                }
            };
            return EditorOrNativeTextInputCommand;
        }(editorCommonExtensions_1.Command));
        registerCommand(new EditorOrNativeTextInputCommand({
            editorHandler: CoreNavigationCommands.SelectAll,
            inputHandler: 'selectAll',
            id: 'editor.action.selectAll',
            precondition: null,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: null,
                primary: 2048 /* CtrlCmd */ | 31 /* KEY_A */
            }
        }));
        registerCommand(new EditorOrNativeTextInputCommand({
            editorHandler: H.Undo,
            inputHandler: 'undo',
            id: H.Undo,
            precondition: editorContextKeys_1.EditorContextKeys.writable,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 56 /* KEY_Z */
            }
        }));
        registerCommand(new EditorOrNativeTextInputCommand({
            editorHandler: H.Redo,
            inputHandler: 'redo',
            id: H.Redo,
            precondition: editorContextKeys_1.EditorContextKeys.writable,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 55 /* KEY_Y */,
                secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 56 /* KEY_Z */],
                mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 56 /* KEY_Z */ }
            }
        }));
        /**
         * A command that will invoke a command on the focused editor.
         */
        var EditorHandlerCommand = (function (_super) {
            __extends(EditorHandlerCommand, _super);
            function EditorHandlerCommand(id, handlerId) {
                var _this = _super.call(this, {
                    id: id,
                    precondition: null
                }) || this;
                _this._handlerId = handlerId;
                return _this;
            }
            EditorHandlerCommand.prototype.runCommand = function (accessor, args) {
                var editor = findFocusedEditor(accessor);
                if (!editor) {
                    return;
                }
                editor.trigger('keyboard', this._handlerId, args);
            };
            return EditorHandlerCommand;
        }(editorCommonExtensions_1.Command));
        function registerOverwritableCommand(handlerId) {
            registerCommand(new EditorHandlerCommand('default:' + handlerId, handlerId));
            registerCommand(new EditorHandlerCommand(handlerId, handlerId));
        }
        registerOverwritableCommand(H.Type);
        registerOverwritableCommand(H.ReplacePreviousChar);
        registerOverwritableCommand(H.CompositionStart);
        registerOverwritableCommand(H.CompositionEnd);
        registerOverwritableCommand(H.Paste);
        registerOverwritableCommand(H.Cut);
    })(Config || (Config = {}));
});

define(__m[449/*vs/editor/browser/view/viewController*/], __M([1/*require*/,0/*exports*/,12/*vs/editor/common/core/position*/,20/*vs/editor/common/editorCommon*/,134/*vs/editor/common/controller/coreCommands*/]), function (require, exports, position_1, editorCommon, coreCommands_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ViewController = (function () {
        function ViewController(configuration, viewModel, execCommandFunc, outgoingEvents, commandService) {
            this.configuration = configuration;
            this.viewModel = viewModel;
            this._execCoreEditorCommandFunc = execCommandFunc;
            this.outgoingEvents = outgoingEvents;
            this.commandService = commandService;
        }
        ViewController.prototype._execMouseCommand = function (editorCommand, args) {
            args.source = 'mouse';
            this._execCoreEditorCommandFunc(editorCommand, args);
        };
        ViewController.prototype.paste = function (source, text, pasteOnNewLine) {
            this.commandService.executeCommand(editorCommon.Handler.Paste, {
                text: text,
                pasteOnNewLine: pasteOnNewLine,
            });
        };
        ViewController.prototype.type = function (source, text) {
            this.commandService.executeCommand(editorCommon.Handler.Type, {
                text: text
            });
        };
        ViewController.prototype.replacePreviousChar = function (source, text, replaceCharCnt) {
            this.commandService.executeCommand(editorCommon.Handler.ReplacePreviousChar, {
                text: text,
                replaceCharCnt: replaceCharCnt
            });
        };
        ViewController.prototype.compositionStart = function (source) {
            this.commandService.executeCommand(editorCommon.Handler.CompositionStart, {});
        };
        ViewController.prototype.compositionEnd = function (source) {
            this.commandService.executeCommand(editorCommon.Handler.CompositionEnd, {});
        };
        ViewController.prototype.cut = function (source) {
            this.commandService.executeCommand(editorCommon.Handler.Cut, {});
        };
        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.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) {
                        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);
        };
        return ViewController;
    }());
    exports.ViewController = ViewController;
});

















define(__m[450/*vs/editor/contrib/caretOperations/common/caretOperations*/], __M([1/*require*/,0/*exports*/,342/*vs/nls!vs/editor/contrib/caretOperations/common/caretOperations*/,21/*vs/editor/common/editorContextKeys*/,13/*vs/editor/common/editorCommonExtensions*/,241/*vs/editor/contrib/caretOperations/common/moveCaretCommand*/]), function (require, exports, nls, editorContextKeys_1, editorCommonExtensions_1, moveCaretCommand_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MoveCaretAction = (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) {
            var commands = [];
            var selections = editor.getSelections();
            for (var i = 0; i < selections.length; i++) {
                commands.push(new moveCaretCommand_1.MoveCaretCommand(selections[i], this.left));
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        };
        return MoveCaretAction;
    }(editorCommonExtensions_1.EditorAction));
    var MoveCaretLeftAction = (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;
        }
        MoveCaretLeftAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], MoveCaretLeftAction);
        return MoveCaretLeftAction;
    }(MoveCaretAction));
    var MoveCaretRightAction = (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;
        }
        MoveCaretRightAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], MoveCaretRightAction);
        return MoveCaretRightAction;
    }(MoveCaretAction));
});

















define(__m[451/*vs/editor/contrib/caretOperations/common/transpose*/], __M([1/*require*/,0/*exports*/,343/*vs/nls!vs/editor/contrib/caretOperations/common/transpose*/,2/*vs/editor/common/core/range*/,21/*vs/editor/common/editorContextKeys*/,13/*vs/editor/common/editorCommonExtensions*/,73/*vs/editor/common/commands/replaceCommand*/]), function (require, exports, nls, range_1, editorContextKeys_1, editorCommonExtensions_1, replaceCommand_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var TransposeLettersAction = (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.textFocus,
                    primary: 0,
                    mac: {
                        primary: 256 /* WinCtrl */ | 50 /* KEY_T */
                    }
                }
            }) || this;
        }
        TransposeLettersAction.prototype.run = function (accessor, editor) {
            var model = editor.getModel();
            var commands = [];
            var selections = editor.getSelections();
            for (var i = 0; i < selections.length; i++) {
                var selection = selections[i];
                if (!selection.isEmpty()) {
                    continue;
                }
                var lineNumber = selection.startLineNumber;
                var column = selection.startColumn;
                if (column === 1) {
                    // at the beginning of line
                    continue;
                }
                var maxColumn = model.getLineMaxColumn(lineNumber);
                if (column === maxColumn) {
                    // at the end of line
                    continue;
                }
                var lineContent = model.getLineContent(lineNumber);
                var charToTheLeft = lineContent.charAt(column - 2);
                var charToTheRight = lineContent.charAt(column - 1);
                var replaceRange = new range_1.Range(lineNumber, column - 1, lineNumber, column + 1);
                commands.push(new replaceCommand_1.ReplaceCommand(replaceRange, charToTheRight + charToTheLeft));
            }
            if (commands.length > 0) {
                editor.pushUndoStop();
                editor.executeCommands(this.id, commands);
                editor.pushUndoStop();
            }
        };
        TransposeLettersAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], TransposeLettersAction);
        return TransposeLettersAction;
    }(editorCommonExtensions_1.EditorAction));
});

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
















define(__m[452/*vs/editor/contrib/clipboard/browser/clipboard*/], __M([1/*require*/,0/*exports*/,344/*vs/nls!vs/editor/contrib/clipboard/browser/clipboard*/,28/*vs/base/browser/browser*/,15/*vs/base/common/platform*/,42/*vs/editor/common/services/codeEditorService*/,13/*vs/editor/common/editorCommonExtensions*/,154/*vs/editor/browser/controller/textAreaInput*/,21/*vs/editor/common/editorContextKeys*/,314/*vs/css!vs/editor/contrib/clipboard/browser/clipboard*/]), function (require, exports, nls, browser, platform, codeEditorService_1, editorCommonExtensions_1, textAreaInput_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')));
    function conditionalEditorAction(condition) {
        if (!condition) {
            return function () { };
        }
        return editorCommonExtensions_1.editorAction;
    }
    var ExecCommandAction = (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.isFocused()) {
                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;
    }(editorCommonExtensions_1.EditorAction));
    var ExecCommandCutAction = (function (_super) {
        __extends(ExecCommandCutAction, _super);
        function ExecCommandCutAction() {
            var _this = this;
            var kbOpts = {
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 54 /* KEY_X */,
                win: { primary: 2048 /* CtrlCmd */ | 54 /* KEY_X */, secondary: [1024 /* Shift */ | 20 /* Delete */] }
            };
            // 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
                }
            }) || this;
            return _this;
        }
        ExecCommandCutAction.prototype.run = function (accessor, editor) {
            var emptySelectionClipboard = editor.getConfiguration().emptySelectionClipboard;
            if (!emptySelectionClipboard && editor.getSelection().isEmpty()) {
                return;
            }
            _super.prototype.run.call(this, accessor, editor);
        };
        ExecCommandCutAction = __decorate([
            conditionalEditorAction(supportsCut)
        ], ExecCommandCutAction);
        return ExecCommandCutAction;
    }(ExecCommandAction));
    var ExecCommandCopyAction = (function (_super) {
        __extends(ExecCommandCopyAction, _super);
        function ExecCommandCopyAction() {
            var _this = this;
            var kbOpts = {
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 33 /* KEY_C */,
                win: { primary: 2048 /* CtrlCmd */ | 33 /* KEY_C */, secondary: [2048 /* CtrlCmd */ | 19 /* Insert */] }
            };
            // 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(1, null),
                alias: 'Copy',
                precondition: null,
                kbOpts: kbOpts,
                menuOpts: {
                    group: CLIPBOARD_CONTEXT_MENU_GROUP,
                    order: 2
                }
            }) || this;
            return _this;
        }
        ExecCommandCopyAction.prototype.run = function (accessor, editor) {
            var emptySelectionClipboard = editor.getConfiguration().emptySelectionClipboard;
            if (!emptySelectionClipboard && editor.getSelection().isEmpty()) {
                return;
            }
            _super.prototype.run.call(this, accessor, editor);
        };
        ExecCommandCopyAction = __decorate([
            conditionalEditorAction(supportsCopy)
        ], ExecCommandCopyAction);
        return ExecCommandCopyAction;
    }(ExecCommandAction));
    var ExecCommandPasteAction = (function (_super) {
        __extends(ExecCommandPasteAction, _super);
        function ExecCommandPasteAction() {
            var _this = this;
            var kbOpts = {
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: 2048 /* CtrlCmd */ | 52 /* KEY_V */,
                win: { primary: 2048 /* CtrlCmd */ | 52 /* KEY_V */, secondary: [1024 /* Shift */ | 19 /* Insert */] }
            };
            // 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(2, null),
                alias: 'Paste',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: kbOpts,
                menuOpts: {
                    group: CLIPBOARD_CONTEXT_MENU_GROUP,
                    order: 3
                }
            }) || this;
            return _this;
        }
        ExecCommandPasteAction = __decorate([
            conditionalEditorAction(supportsPaste)
        ], ExecCommandPasteAction);
        return ExecCommandPasteAction;
    }(ExecCommandAction));
    var ExecCommandCopyWithSyntaxHighlightingAction = (function (_super) {
        __extends(ExecCommandCopyWithSyntaxHighlightingAction, _super);
        function ExecCommandCopyWithSyntaxHighlightingAction() {
            return _super.call(this, 'copy', {
                id: 'editor.action.clipboardCopyWithSyntaxHighlightingAction',
                label: nls.localize(3, null),
                alias: 'Copy With Syntax Highlighting',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: null
                }
            }) || this;
        }
        ExecCommandCopyWithSyntaxHighlightingAction.prototype.run = function (accessor, editor) {
            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;
        };
        ExecCommandCopyWithSyntaxHighlightingAction = __decorate([
            conditionalEditorAction(supportsCopyWithSyntaxHighlighting)
        ], ExecCommandCopyWithSyntaxHighlightingAction);
        return ExecCommandCopyWithSyntaxHighlightingAction;
    }(ExecCommandAction));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[453/*vs/editor/contrib/codelens/browser/codelens*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,33/*vs/base/common/arrays*/,24/*vs/base/common/uri*/,7/*vs/base/common/winjs.base*/,13/*vs/editor/common/editorCommonExtensions*/,17/*vs/editor/common/modes*/,56/*vs/editor/common/services/modelService*/,18/*vs/base/common/async*/]), function (require, exports, errors_1, arrays_1, uri_1, winjs_base_1, editorCommonExtensions_1, modes_1, modelService_1, async_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function getCodeLensData(model) {
        var symbols = [];
        var provider = modes_1.CodeLensProviderRegistry.ordered(model);
        var promises = provider.map(function (provider) { return async_1.asWinJsPromise(function (token) { return 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 });
                }
            }
        }, errors_1.onUnexpectedExternalError); });
        return winjs_base_1.TPromise.join(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;
    editorCommonExtensions_1.CommonEditorRegistry.registerLanguageCommand('_executeCodeLensProvider', function (accessor, args) {
        var resource = args.resource;
        if (!(resource instanceof uri_1.default)) {
            throw errors_1.illegalArgument();
        }
        var model = accessor.get(modelService_1.IModelService).getModel(resource);
        if (!model) {
            throw errors_1.illegalArgument();
        }
        return getCodeLensData(model).then(function (value) { return value.map(function (item) { return item.symbol; }); });
    });
});

















define(__m[454/*vs/editor/contrib/comment/common/comment*/], __M([1/*require*/,0/*exports*/,345/*vs/nls!vs/editor/contrib/comment/common/comment*/,40/*vs/base/common/keyCodes*/,21/*vs/editor/common/editorContextKeys*/,13/*vs/editor/common/editorCommonExtensions*/,189/*vs/editor/contrib/comment/common/blockCommentCommand*/,250/*vs/editor/contrib/comment/common/lineCommentCommand*/]), function (require, exports, nls, keyCodes_1, editorContextKeys_1, editorCommonExtensions_1, blockCommentCommand_1, lineCommentCommand_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CommentLineAction = (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) {
            var model = editor.getModel();
            if (!model) {
                return;
            }
            var commands = [];
            var selections = editor.getSelections();
            var opts = model.getOptions();
            for (var i = 0; i < selections.length; i++) {
                commands.push(new lineCommentCommand_1.LineCommentCommand(selections[i], opts.tabSize, this._type));
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        };
        return CommentLineAction;
    }(editorCommonExtensions_1.EditorAction));
    var ToggleCommentLineAction = (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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 85 /* US_SLASH */
                }
            }) || this;
        }
        ToggleCommentLineAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], ToggleCommentLineAction);
        return ToggleCommentLineAction;
    }(CommentLineAction));
    var AddLineCommentAction = (function (_super) {
        __extends(AddLineCommentAction, _super);
        function AddLineCommentAction() {
            return _super.call(this, 1 /* ForceAdd */, {
                id: 'editor.action.addCommentLine',
                label: nls.localize(1, null),
                alias: 'Add Line Comment',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 33 /* KEY_C */)
                }
            }) || this;
        }
        AddLineCommentAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], AddLineCommentAction);
        return AddLineCommentAction;
    }(CommentLineAction));
    var RemoveLineCommentAction = (function (_super) {
        __extends(RemoveLineCommentAction, _super);
        function RemoveLineCommentAction() {
            return _super.call(this, 2 /* ForceRemove */, {
                id: 'editor.action.removeCommentLine',
                label: nls.localize(2, null),
                alias: 'Remove Line Comment',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 51 /* KEY_U */)
                }
            }) || this;
        }
        RemoveLineCommentAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], RemoveLineCommentAction);
        return RemoveLineCommentAction;
    }(CommentLineAction));
    var BlockCommentAction = (function (_super) {
        __extends(BlockCommentAction, _super);
        function BlockCommentAction() {
            return _super.call(this, {
                id: 'editor.action.blockComment',
                label: nls.localize(3, null),
                alias: 'Toggle Block Comment',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 1024 /* Shift */ | 512 /* Alt */ | 31 /* KEY_A */,
                    linux: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 31 /* KEY_A */ }
                }
            }) || this;
        }
        BlockCommentAction.prototype.run = function (accessor, editor) {
            var commands = [];
            var selections = editor.getSelections();
            for (var i = 0; i < selections.length; i++) {
                commands.push(new blockCommentCommand_1.BlockCommentCommand(selections[i]));
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        };
        BlockCommentAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], BlockCommentAction);
        return BlockCommentAction;
    }(editorCommonExtensions_1.EditorAction));
});




















define(__m[455/*vs/editor/contrib/contextmenu/browser/contextmenu*/], __M([1/*require*/,0/*exports*/,346/*vs/nls!vs/editor/contrib/contextmenu/browser/contextmenu*/,3/*vs/base/common/lifecycle*/,7/*vs/base/common/winjs.base*/,4/*vs/base/browser/dom*/,75/*vs/base/browser/ui/actionbar/actionbar*/,69/*vs/platform/contextview/browser/contextView*/,46/*vs/platform/keybinding/common/keybinding*/,19/*vs/platform/contextkey/common/contextkey*/,85/*vs/platform/actions/common/actions*/,21/*vs/editor/common/editorContextKeys*/,13/*vs/editor/common/editorCommonExtensions*/,25/*vs/editor/browser/editorBrowser*/,30/*vs/editor/browser/editorBrowserExtensions*/]), function (require, exports, nls, lifecycle_1, winjs_base_1, dom, actionbar_1, contextView_1, keybinding_1, contextkey_1, actions_1, editorContextKeys_1, editorCommonExtensions_1, editorBrowser_1, editorBrowserExtensions_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ContextMenuController = (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.onDidScrollChange(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_1 = ContextMenuController;
        ContextMenuController.get = function (editor) {
            return editor.getContribution(ContextMenuController_1.ID);
        };
        ContextMenuController.prototype._onContextMenu = function (e) {
            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 === editorBrowser_1.MouseTargetType.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 !== editorBrowser_1.MouseTargetType.CONTENT_TEXT && e.target.type !== editorBrowser_1.MouseTargetType.CONTENT_EMPTY && e.target.type !== editorBrowser_1.MouseTargetType.TEXTAREA) {
                return; // only support mouse click into text or native context menu key for now
            }
            // Ensure the editor gets focus if it hasn't, so the right events are being sent to other contributions
            this._editor.focus();
            // Ensure the cursor is at the position of the mouse click
            if (e.target.position && !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 forcedPosition;
            if (e.target.type !== editorBrowser_1.MouseTargetType.TEXTAREA) {
                forcedPosition = { x: e.event.posx, y: e.event.posy + 1 };
            }
            // Show the context menu
            this.showContextMenu(forcedPosition);
        };
        ContextMenuController.prototype.showContextMenu = function (forcedPosition) {
            if (!this._editor.getConfiguration().contribInfo.contextmenu) {
                return; // Context menu is turned off through configuration
            }
            if (!this._contextMenuService) {
                this._editor.focus();
                return; // We need the context menu service to function
            }
            // Find actions available for menu
            var menuActions = this._getMenuActions();
            // Show menu if we have actions to show
            if (menuActions.length > 0) {
                this._doShowContextMenu(menuActions, forcedPosition);
            }
        };
        ContextMenuController.prototype._getMenuActions = function () {
            var result = [];
            var contextMenu = this._menuService.createMenu(actions_1.MenuId.EditorContext, this._contextKeyService);
            var groups = contextMenu.getActions({ arg: this._editor.getModel().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, forcedPosition) {
            var _this = this;
            if (forcedPosition === void 0) { forcedPosition = null; }
            // Disable hover
            var oldHoverSetting = this._editor.getConfiguration().contribInfo.hover;
            this._editor.updateOptions({
                hover: false
            });
            var menuPosition = forcedPosition;
            if (!menuPosition) {
                // Ensure selection is visible
                this._editor.revealPosition(this._editor.getPosition());
                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;
                menuPosition = { x: posx, y: posy };
            }
            // Show menu
            this._contextMenuIsBeingShownCount++;
            this._contextMenuService.showContextMenu({
                getAnchor: function () { return menuPosition; },
                getActions: function () {
                    return winjs_base_1.TPromise.as(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_1.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 = ContextMenuController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __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;
        var ContextMenuController_1;
    }());
    exports.ContextMenuController = ContextMenuController;
    var ShowContextMenu = (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.textFocus,
                    primary: 1024 /* Shift */ | 68 /* F10 */
                }
            }) || this;
        }
        ShowContextMenu.prototype.run = function (accessor, editor) {
            var contribution = ContextMenuController.get(editor);
            contribution.showContextMenu();
        };
        ShowContextMenu = __decorate([
            editorCommonExtensions_1.editorAction
        ], ShowContextMenu);
        return ShowContextMenu;
    }(editorCommonExtensions_1.EditorAction));
});

















define(__m[456/*vs/editor/contrib/cursorUndo/browser/cursorUndo*/], __M([1/*require*/,0/*exports*/,13/*vs/editor/common/editorCommonExtensions*/,3/*vs/base/common/lifecycle*/,21/*vs/editor/common/editorContextKeys*/,30/*vs/editor/browser/editorBrowserExtensions*/]), function (require, exports, editorCommonExtensions_1, lifecycle_1, editorContextKeys_1, editorBrowserExtensions_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CursorState = (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 = (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 = _this._undoStack.splice(0, _this._undoStack.length - 50);
                    }
                }
                _this._prevState = _this._readState();
            }));
            return _this;
        }
        CursorUndoController_1 = CursorUndoController;
        CursorUndoController.get = function (editor) {
            return editor.getContribution(CursorUndoController_1.ID);
        };
        CursorUndoController.prototype._readState = function () {
            if (!this._editor.getModel()) {
                // no model => no state
                return null;
            }
            return new CursorState(this._editor.getSelections());
        };
        CursorUndoController.prototype.getId = function () {
            return CursorUndoController_1.ID;
        };
        CursorUndoController.prototype.cursorUndo = function () {
            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._isCursorUndo = false;
                    return;
                }
            }
        };
        CursorUndoController.ID = 'editor.contrib.cursorUndoController';
        CursorUndoController = CursorUndoController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution
        ], CursorUndoController);
        return CursorUndoController;
        var CursorUndoController_1;
    }(lifecycle_1.Disposable));
    exports.CursorUndoController = CursorUndoController;
    var CursorUndo = (function (_super) {
        __extends(CursorUndo, _super);
        function CursorUndo() {
            return _super.call(this, {
                id: 'cursorUndo',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 51 /* KEY_U */
                }
            }) || this;
        }
        CursorUndo.prototype.runEditorCommand = function (accessor, editor, args) {
            CursorUndoController.get(editor).cursorUndo();
        };
        CursorUndo = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorUndo);
        return CursorUndo;
    }(editorCommonExtensions_1.EditorCommand));
    exports.CursorUndo = CursorUndo;
});




















define(__m[176/*vs/editor/contrib/find/common/findController*/], __M([1/*require*/,0/*exports*/,348/*vs/nls!vs/editor/contrib/find/common/findController*/,434/*vs/base/common/history*/,40/*vs/base/common/keyCodes*/,3/*vs/base/common/lifecycle*/,19/*vs/platform/contextkey/common/contextkey*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,9/*vs/base/common/strings*/,20/*vs/editor/common/editorCommon*/,13/*vs/editor/common/editorCommonExtensions*/,121/*vs/editor/contrib/find/common/findModel*/,253/*vs/editor/contrib/find/common/findState*/,252/*vs/editor/contrib/find/common/find*/,17/*vs/editor/common/modes*/,18/*vs/base/common/async*/,54/*vs/editor/common/controller/cursorEvents*/,21/*vs/editor/common/editorContextKeys*/,76/*vs/platform/storage/common/storage*/,34/*vs/editor/common/model/textModelWithDecorations*/]), function (require, exports, nls, history_1, keyCodes_1, lifecycle_1, contextkey_1, range_1, selection_1, strings, editorCommon, editorCommonExtensions_1, findModel_1, findState_1, find_1, modes_1, async_1, cursorEvents_1, editorContextKeys_1, storage_1, textModelWithDecorations_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var FindStartFocusAction;
    (function (FindStartFocusAction) {
        FindStartFocusAction[FindStartFocusAction["NoFocusChange"] = 0] = "NoFocusChange";
        FindStartFocusAction[FindStartFocusAction["FocusFindInput"] = 1] = "FocusFindInput";
        FindStartFocusAction[FindStartFocusAction["FocusReplaceInput"] = 2] = "FocusReplaceInput";
    })(FindStartFocusAction = exports.FindStartFocusAction || (exports.FindStartFocusAction = {}));
    exports.CONTEXT_FIND_WIDGET_VISIBLE = new contextkey_1.RawContextKey('findWidgetVisible', false);
    exports.CONTEXT_FIND_WIDGET_NOT_VISIBLE = exports.CONTEXT_FIND_WIDGET_VISIBLE.toNegated();
    exports.CONTEXT_FIND_INPUT_FOCUSSED = new contextkey_1.RawContextKey('findInputFocussed', false);
    var CommonFindController = (function (_super) {
        __extends(CommonFindController, _super);
        function CommonFindController(editor, contextKeyService, storageService) {
            var _this = _super.call(this) || this;
            _this._editor = editor;
            _this._findWidgetVisible = exports.CONTEXT_FIND_WIDGET_VISIBLE.bindTo(contextKeyService);
            _this._storageService = storageService;
            _this._updateHistoryDelayer = new async_1.Delayer(500);
            _this._currentHistoryNavigator = new history_1.HistoryNavigator();
            _this._state = _this._register(new findState_1.FindReplaceState());
            _this.loadQueryState();
            _this._register(_this._state.addChangeListener(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', storage_1.StorageScope.WORKSPACE, false),
                    wholeWord: _this._storageService.getBoolean('editor.wholeWord', storage_1.StorageScope.WORKSPACE, false),
                    isRegex: _this._storageService.getBoolean('editor.isRegex', storage_1.StorageScope.WORKSPACE, false)
                }, false);
                if (shouldRestartFind) {
                    _this._start({
                        forceRevealReplace: false,
                        seedSearchStringFromSelection: false,
                        shouldFocus: 0 /* NoFocusChange */,
                        shouldAnimate: 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.updateHistory && e.searchString) {
                this._delayedUpdateHistory();
            }
            if (e.isRevealed) {
                if (this._state.isRevealed) {
                    this._findWidgetVisible.set(true);
                }
                else {
                    this._findWidgetVisible.reset();
                    this.disposeModel();
                }
            }
        };
        CommonFindController.prototype.saveQueryState = function (e) {
            if (e.isRegex && typeof this._state.isRegex !== 'undefined') {
                this._storageService.store('editor.isRegex', this._state.isRegex, storage_1.StorageScope.WORKSPACE);
            }
            if (e.wholeWord && typeof this._state.wholeWord !== 'undefined') {
                this._storageService.store('editor.wholeWord', this._state.wholeWord, storage_1.StorageScope.WORKSPACE);
            }
            if (e.matchCase && typeof this._state.matchCase !== 'undefined') {
                this._storageService.store('editor.matchCase', this._state.matchCase, storage_1.StorageScope.WORKSPACE);
            }
        };
        CommonFindController.prototype.loadQueryState = function () {
            this._state.change({
                matchCase: this._storageService.getBoolean('editor.matchCase', storage_1.StorageScope.WORKSPACE, this._state.matchCase),
                wholeWord: this._storageService.getBoolean('editor.wholeWord', storage_1.StorageScope.WORKSPACE, this._state.wholeWord),
                isRegex: this._storageService.getBoolean('editor.isRegex', storage_1.StorageScope.WORKSPACE, this._state.isRegex)
            }, false);
        };
        CommonFindController.prototype._delayedUpdateHistory = function () {
            this._updateHistoryDelayer.trigger(this._updateHistory.bind(this));
        };
        CommonFindController.prototype._updateHistory = function () {
            if (this._state.searchString) {
                this._currentHistoryNavigator.add(this._state.searchString);
            }
        };
        CommonFindController.prototype.getState = function () {
            return this._state;
        };
        CommonFindController.prototype.getHistory = function () {
            return this._currentHistoryNavigator;
        };
        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);
        };
        CommonFindController.prototype.toggleWholeWords = function () {
            this._state.change({ wholeWord: !this._state.wholeWord }, false);
        };
        CommonFindController.prototype.toggleRegex = function () {
            this._state.change({ isRegex: !this._state.isRegex }, false);
        };
        CommonFindController.prototype.toggleSearchScope = function () {
            if (this._state.searchScope) {
                this._state.change({ searchScope: null }, true);
            }
            else {
                var selection = this._editor.getSelection();
                if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
                    selection = selection.setEndPosition(selection.endLineNumber - 1, 1);
                }
                if (!selection.isEmpty()) {
                    this._state.change({ searchScope: selection }, true);
                }
            }
        };
        CommonFindController.prototype.setSearchString = function (searchString) {
            this._state.change({ searchString: searchString }, false);
        };
        CommonFindController.prototype.highlightFindOptions = function () {
            // overwritten in subclass
        };
        CommonFindController.prototype._start = function (opts) {
            this.disposeModel();
            if (!this._editor.getModel()) {
                // cannot do anything with an editor that doesn't have a model...
                return;
            }
            var stateChanges = {
                isRevealed: true
            };
            // Consider editor selection and overwrite the state with it
            if (opts.seedSearchStringFromSelection && this._editor.getConfiguration().contribInfo.find.seedSearchStringFromSelection) {
                var selectionSearchString = find_1.getSelectionSearchString(this._editor);
                if (selectionSearchString) {
                    if (this._state.isRegex) {
                        stateChanges.searchString = strings.escapeRegExpCharacters(selectionSearchString);
                    }
                    else {
                        stateChanges.searchString = selectionSearchString;
                    }
                }
            }
            // Overwrite isReplaceRevealed
            if (opts.forceRevealReplace) {
                stateChanges.isReplaceRevealed = true;
            }
            else if (!this._findWidgetVisible.get()) {
                stateChanges.isReplaceRevealed = false;
            }
            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.showPreviousFindTerm = function () {
            var previousTerm = this._currentHistoryNavigator.previous();
            if (previousTerm) {
                this._state.change({ searchString: previousTerm }, false, false);
            }
            return true;
        };
        CommonFindController.prototype.showNextFindTerm = function () {
            var nextTerm = this._currentHistoryNavigator.next();
            if (nextTerm) {
                this._state.change({ searchString: nextTerm }, false, false);
            }
            return true;
        };
        CommonFindController.ID = 'editor.contrib.findController';
        CommonFindController = __decorate([
            __param(1, contextkey_1.IContextKeyService), __param(2, storage_1.IStorageService)
        ], CommonFindController);
        return CommonFindController;
    }(lifecycle_1.Disposable));
    exports.CommonFindController = CommonFindController;
    var StartFindAction = (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 */,
                    mac: {
                        primary: 2048 /* CtrlCmd */ | 36 /* KEY_F */,
                        secondary: [2048 /* CtrlCmd */ | 35 /* KEY_E */]
                    }
                }
            }) || this;
        }
        StartFindAction.prototype.run = function (accessor, editor) {
            var controller = CommonFindController.get(editor);
            if (controller) {
                controller.start({
                    forceRevealReplace: false,
                    seedSearchStringFromSelection: true,
                    shouldFocus: 1 /* FocusFindInput */,
                    shouldAnimate: true
                });
            }
        };
        StartFindAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], StartFindAction);
        return StartFindAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.StartFindAction = StartFindAction;
    var MatchFindAction = (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),
                    shouldFocus: 0 /* NoFocusChange */,
                    shouldAnimate: true
                });
                this._run(controller);
            }
        };
        return MatchFindAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.MatchFindAction = MatchFindAction;
    var NextMatchFindAction = (function (_super) {
        __extends(NextMatchFindAction, _super);
        function NextMatchFindAction() {
            return _super.call(this, {
                id: findModel_1.FIND_IDS.NextMatchFindAction,
                label: nls.localize(1, 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 */] }
                }
            }) || this;
        }
        NextMatchFindAction.prototype._run = function (controller) {
            return controller.moveToNextMatch();
        };
        NextMatchFindAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], NextMatchFindAction);
        return NextMatchFindAction;
    }(MatchFindAction));
    exports.NextMatchFindAction = NextMatchFindAction;
    var PreviousMatchFindAction = (function (_super) {
        __extends(PreviousMatchFindAction, _super);
        function PreviousMatchFindAction() {
            return _super.call(this, {
                id: findModel_1.FIND_IDS.PreviousMatchFindAction,
                label: nls.localize(2, 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 */] }
                }
            }) || this;
        }
        PreviousMatchFindAction.prototype._run = function (controller) {
            return controller.moveToPrevMatch();
        };
        PreviousMatchFindAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], PreviousMatchFindAction);
        return PreviousMatchFindAction;
    }(MatchFindAction));
    exports.PreviousMatchFindAction = PreviousMatchFindAction;
    var SelectionMatchFindAction = (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 = find_1.getSelectionSearchString(editor);
            if (selectionSearchString) {
                controller.setSearchString(selectionSearchString);
            }
            if (!this._run(controller)) {
                controller.start({
                    forceRevealReplace: false,
                    seedSearchStringFromSelection: false,
                    shouldFocus: 0 /* NoFocusChange */,
                    shouldAnimate: true
                });
                this._run(controller);
            }
        };
        return SelectionMatchFindAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.SelectionMatchFindAction = SelectionMatchFindAction;
    var NextSelectionMatchFindAction = (function (_super) {
        __extends(NextSelectionMatchFindAction, _super);
        function NextSelectionMatchFindAction() {
            return _super.call(this, {
                id: findModel_1.FIND_IDS.NextSelectionMatchFindAction,
                label: nls.localize(3, null),
                alias: 'Find Next Selection',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 2048 /* CtrlCmd */ | 61 /* F3 */
                }
            }) || this;
        }
        NextSelectionMatchFindAction.prototype._run = function (controller) {
            return controller.moveToNextMatch();
        };
        NextSelectionMatchFindAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], NextSelectionMatchFindAction);
        return NextSelectionMatchFindAction;
    }(SelectionMatchFindAction));
    exports.NextSelectionMatchFindAction = NextSelectionMatchFindAction;
    var PreviousSelectionMatchFindAction = (function (_super) {
        __extends(PreviousSelectionMatchFindAction, _super);
        function PreviousSelectionMatchFindAction() {
            return _super.call(this, {
                id: findModel_1.FIND_IDS.PreviousSelectionMatchFindAction,
                label: nls.localize(4, null),
                alias: 'Find Previous Selection',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 61 /* F3 */
                }
            }) || this;
        }
        PreviousSelectionMatchFindAction.prototype._run = function (controller) {
            return controller.moveToPrevMatch();
        };
        PreviousSelectionMatchFindAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], PreviousSelectionMatchFindAction);
        return PreviousSelectionMatchFindAction;
    }(SelectionMatchFindAction));
    exports.PreviousSelectionMatchFindAction = PreviousSelectionMatchFindAction;
    var StartFindReplaceAction = (function (_super) {
        __extends(StartFindReplaceAction, _super);
        function StartFindReplaceAction() {
            return _super.call(this, {
                id: findModel_1.FIND_IDS.StartFindReplaceAction,
                label: nls.localize(5, null),
                alias: 'Replace',
                precondition: null,
                kbOpts: {
                    kbExpr: null,
                    primary: 2048 /* CtrlCmd */ | 38 /* KEY_H */,
                    mac: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 36 /* KEY_F */ }
                }
            }) || this;
        }
        StartFindReplaceAction.prototype.run = function (accessor, editor) {
            if (editor.getConfiguration().readOnly) {
                return;
            }
            var controller = CommonFindController.get(editor);
            var currentSelection = editor.getSelection();
            // we only seed search string from selection when the current selection is single line and not empty.
            var seedSearchStringFromSelection = !currentSelection.isEmpty() &&
                currentSelection.startLineNumber === currentSelection.endLineNumber;
            var oldSearchString = controller.getState().searchString;
            // 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.
            var shouldFocus = (!!oldSearchString || seedSearchStringFromSelection) ?
                2 /* FocusReplaceInput */ : 1 /* FocusFindInput */;
            if (controller) {
                controller.start({
                    forceRevealReplace: true,
                    seedSearchStringFromSelection: seedSearchStringFromSelection,
                    shouldFocus: shouldFocus,
                    shouldAnimate: true
                });
            }
        };
        StartFindReplaceAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], StartFindReplaceAction);
        return StartFindReplaceAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.StartFindReplaceAction = StartFindReplaceAction;
    function multiCursorFind(editor, input) {
        var controller = CommonFindController.get(editor);
        if (!controller) {
            return null;
        }
        var state = controller.getState();
        var searchText;
        var currentMatch;
        // In any case, if the find widget was ever opened, the options are taken from it
        var wholeWord = state.wholeWord;
        var matchCase = state.matchCase;
        // Find widget owns 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.isFocused() && state.isRevealed && state.searchString.length > 0) {
            // Find widget owns what is searched for
            searchText = state.searchString;
        }
        else {
            // Selection owns what is searched for
            var s = editor.getSelection();
            if (s.startLineNumber !== s.endLineNumber && !input.allowMultiline) {
                // multiline forbidden
                return 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');
            }
            if (input.changeFindSearchString) {
                controller.setSearchString(searchText);
            }
        }
        if (input.highlightFindOptions) {
            controller.highlightFindOptions();
        }
        return {
            searchText: searchText,
            matchCase: matchCase,
            wholeWord: wholeWord,
            currentMatch: currentMatch
        };
    }
    var SelectNextFindMatchAction = (function (_super) {
        __extends(SelectNextFindMatchAction, _super);
        function SelectNextFindMatchAction() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SelectNextFindMatchAction.prototype._getNextMatch = function (editor) {
            var r = multiCursorFind(editor, {
                changeFindSearchString: true,
                allowMultiline: true,
                highlightFindOptions: true
            });
            if (!r) {
                return null;
            }
            if (r.currentMatch) {
                return r.currentMatch;
            }
            var allSelections = editor.getSelections();
            var lastAddedSelection = allSelections[allSelections.length - 1];
            var nextMatch = editor.getModel().findNextMatch(r.searchText, lastAddedSelection.getEndPosition(), false, r.matchCase, r.wholeWord ? 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);
        };
        return SelectNextFindMatchAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.SelectNextFindMatchAction = SelectNextFindMatchAction;
    var SelectPreviousFindMatchAction = (function (_super) {
        __extends(SelectPreviousFindMatchAction, _super);
        function SelectPreviousFindMatchAction() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SelectPreviousFindMatchAction.prototype._getPreviousMatch = function (editor) {
            var r = multiCursorFind(editor, {
                changeFindSearchString: true,
                allowMultiline: true,
                highlightFindOptions: true
            });
            if (!r) {
                return null;
            }
            if (r.currentMatch) {
                return r.currentMatch;
            }
            var allSelections = editor.getSelections();
            var lastAddedSelection = allSelections[allSelections.length - 1];
            var previousMatch = editor.getModel().findPreviousMatch(r.searchText, lastAddedSelection.getStartPosition(), false, r.matchCase, r.wholeWord ? 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);
        };
        return SelectPreviousFindMatchAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.SelectPreviousFindMatchAction = SelectPreviousFindMatchAction;
    var AddSelectionToNextFindMatchAction = (function (_super) {
        __extends(AddSelectionToNextFindMatchAction, _super);
        function AddSelectionToNextFindMatchAction() {
            return _super.call(this, {
                id: findModel_1.FIND_IDS.AddSelectionToNextFindMatchAction,
                label: nls.localize(6, null),
                alias: 'Add Selection To Next Find Match',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 2048 /* CtrlCmd */ | 34 /* KEY_D */
                }
            }) || this;
        }
        AddSelectionToNextFindMatchAction.prototype.run = function (accessor, editor) {
            var allSelections = editor.getSelections();
            // If there are mulitple cursors, handle the case where they do not all select the same text.
            if (allSelections.length > 1) {
                var model = editor.getModel();
                var controller = CommonFindController.get(editor);
                if (!controller) {
                    return;
                }
                var findState = controller.getState();
                var caseSensitive = findState.matchCase;
                var selectionsContainSameText = true;
                var selectedText = model.getValueInRange(allSelections[0]);
                if (!caseSensitive) {
                    selectedText = selectedText.toLowerCase();
                }
                for (var i = 1, len = allSelections.length; i < len; i++) {
                    var selection = allSelections[i];
                    if (selection.isEmpty()) {
                        selectionsContainSameText = false;
                        break;
                    }
                    var thisSelectedText = model.getValueInRange(selection);
                    if (!caseSensitive) {
                        thisSelectedText = thisSelectedText.toLowerCase();
                    }
                    if (selectedText !== thisSelectedText) {
                        selectionsContainSameText = false;
                        break;
                    }
                }
                if (!selectionsContainSameText) {
                    var resultingSelections = [];
                    for (var i = 0, len = allSelections.length; i < len; i++) {
                        var selection = allSelections[i];
                        if (selection.isEmpty()) {
                            var word = editor.getModel().getWordAtPosition(selection.getStartPosition());
                            if (word) {
                                resultingSelections[i] = new selection_1.Selection(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn);
                                continue;
                            }
                        }
                        resultingSelections[i] = selection;
                    }
                    editor.setSelections(resultingSelections);
                    return;
                }
            }
            var nextMatch = this._getNextMatch(editor);
            if (!nextMatch) {
                return;
            }
            editor.setSelections(allSelections.concat(nextMatch));
            editor.revealRangeInCenterIfOutsideViewport(nextMatch);
        };
        AddSelectionToNextFindMatchAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], AddSelectionToNextFindMatchAction);
        return AddSelectionToNextFindMatchAction;
    }(SelectNextFindMatchAction));
    exports.AddSelectionToNextFindMatchAction = AddSelectionToNextFindMatchAction;
    var AddSelectionToPreviousFindMatchAction = (function (_super) {
        __extends(AddSelectionToPreviousFindMatchAction, _super);
        function AddSelectionToPreviousFindMatchAction() {
            return _super.call(this, {
                id: findModel_1.FIND_IDS.AddSelectionToPreviousFindMatchAction,
                label: nls.localize(7, null),
                alias: 'Add Selection To Previous Find Match',
                precondition: null
            }) || this;
        }
        AddSelectionToPreviousFindMatchAction.prototype.run = function (accessor, editor) {
            var previousMatch = this._getPreviousMatch(editor);
            if (!previousMatch) {
                return;
            }
            var allSelections = editor.getSelections();
            editor.setSelections(allSelections.concat(previousMatch));
            editor.revealRangeInCenterIfOutsideViewport(previousMatch);
        };
        AddSelectionToPreviousFindMatchAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], AddSelectionToPreviousFindMatchAction);
        return AddSelectionToPreviousFindMatchAction;
    }(SelectPreviousFindMatchAction));
    exports.AddSelectionToPreviousFindMatchAction = AddSelectionToPreviousFindMatchAction;
    var MoveSelectionToNextFindMatchAction = (function (_super) {
        __extends(MoveSelectionToNextFindMatchAction, _super);
        function MoveSelectionToNextFindMatchAction() {
            return _super.call(this, {
                id: findModel_1.FIND_IDS.MoveSelectionToNextFindMatchAction,
                label: nls.localize(8, 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 */)
                }
            }) || this;
        }
        MoveSelectionToNextFindMatchAction.prototype.run = function (accessor, editor) {
            var nextMatch = this._getNextMatch(editor);
            if (!nextMatch) {
                return;
            }
            var allSelections = editor.getSelections();
            editor.setSelections(allSelections.slice(0, allSelections.length - 1).concat(nextMatch));
            editor.revealRangeInCenterIfOutsideViewport(nextMatch);
        };
        MoveSelectionToNextFindMatchAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], MoveSelectionToNextFindMatchAction);
        return MoveSelectionToNextFindMatchAction;
    }(SelectNextFindMatchAction));
    exports.MoveSelectionToNextFindMatchAction = MoveSelectionToNextFindMatchAction;
    var MoveSelectionToPreviousFindMatchAction = (function (_super) {
        __extends(MoveSelectionToPreviousFindMatchAction, _super);
        function MoveSelectionToPreviousFindMatchAction() {
            return _super.call(this, {
                id: findModel_1.FIND_IDS.MoveSelectionToPreviousFindMatchAction,
                label: nls.localize(9, null),
                alias: 'Move Last Selection To Previous Find Match',
                precondition: null
            }) || this;
        }
        MoveSelectionToPreviousFindMatchAction.prototype.run = function (accessor, editor) {
            var previousMatch = this._getPreviousMatch(editor);
            if (!previousMatch) {
                return;
            }
            var allSelections = editor.getSelections();
            editor.setSelections(allSelections.slice(0, allSelections.length - 1).concat(previousMatch));
            editor.revealRangeInCenterIfOutsideViewport(previousMatch);
        };
        MoveSelectionToPreviousFindMatchAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], MoveSelectionToPreviousFindMatchAction);
        return MoveSelectionToPreviousFindMatchAction;
    }(SelectPreviousFindMatchAction));
    exports.MoveSelectionToPreviousFindMatchAction = MoveSelectionToPreviousFindMatchAction;
    var AbstractSelectHighlightsAction = (function (_super) {
        __extends(AbstractSelectHighlightsAction, _super);
        function AbstractSelectHighlightsAction() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        AbstractSelectHighlightsAction.prototype.run = function (accessor, editor) {
            var controller = CommonFindController.get(editor);
            if (!controller) {
                return null;
            }
            var matches = null;
            var findState = controller.getState();
            if (findState.isRevealed && findState.isRegex && findState.searchString.length > 0) {
                matches = editor.getModel().findMatches(findState.searchString, true, findState.isRegex, findState.matchCase, findState.wholeWord ? editor.getConfiguration().wordSeparators : null, false).map(function (m) { return m.range; });
            }
            else {
                var r = multiCursorFind(editor, {
                    changeFindSearchString: true,
                    allowMultiline: true,
                    highlightFindOptions: true
                });
                if (!r) {
                    return;
                }
                matches = editor.getModel().findMatches(r.searchText, true, false, r.matchCase, r.wholeWord ? editor.getConfiguration().wordSeparators : null, false).map(function (m) { return m.range; });
            }
            if (matches.length > 0) {
                var editorSelection = editor.getSelection();
                for (var i = 0, len = matches.length; i < len; i++) {
                    var match = matches[i];
                    var intersection = match.intersectRanges(editorSelection);
                    if (intersection) {
                        // bingo!
                        matches.splice(i, 1);
                        matches.unshift(match);
                        break;
                    }
                }
                editor.setSelections(matches.map(function (m) { return new selection_1.Selection(m.startLineNumber, m.startColumn, m.endLineNumber, m.endColumn); }));
            }
        };
        return AbstractSelectHighlightsAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.AbstractSelectHighlightsAction = AbstractSelectHighlightsAction;
    var SelectHighlightsAction = (function (_super) {
        __extends(SelectHighlightsAction, _super);
        function SelectHighlightsAction() {
            return _super.call(this, {
                id: 'editor.action.selectHighlights',
                label: nls.localize(10, null),
                alias: 'Select All Occurrences of Find Match',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 42 /* KEY_L */
                }
            }) || this;
        }
        SelectHighlightsAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], SelectHighlightsAction);
        return SelectHighlightsAction;
    }(AbstractSelectHighlightsAction));
    exports.SelectHighlightsAction = SelectHighlightsAction;
    var CompatChangeAll = (function (_super) {
        __extends(CompatChangeAll, _super);
        function CompatChangeAll() {
            return _super.call(this, {
                id: 'editor.action.changeAll',
                label: nls.localize(11, null),
                alias: 'Change All Occurrences',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 60 /* F2 */
                },
                menuOpts: {
                    group: '1_modification',
                    order: 1.2
                }
            }) || this;
        }
        CompatChangeAll = __decorate([
            editorCommonExtensions_1.editorAction
        ], CompatChangeAll);
        return CompatChangeAll;
    }(AbstractSelectHighlightsAction));
    exports.CompatChangeAll = CompatChangeAll;
    var SelectionHighlighterState = (function () {
        function SelectionHighlighterState(lastWordUnderCursor, 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 = (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 === cursorEvents_1.CursorChangeReason.Explicit) {
                        if (_this.state && (!_this.state.lastWordUnderCursor || !_this.state.lastWordUnderCursor.containsPosition(e.selection.getStartPosition()))) {
                            // 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(CommonFindController.get(editor).getState().addChangeListener(function (e) {
                _this._update();
            }));
            return _this;
        }
        SelectionHighlighter_1 = SelectionHighlighter;
        SelectionHighlighter.prototype.getId = function () {
            return SelectionHighlighter_1.ID;
        };
        SelectionHighlighter.prototype._update = function () {
            this._setState(SelectionHighlighter_1._createState(this._isEnabled, this.editor));
        };
        SelectionHighlighter._createState = function (isEnabled, editor) {
            var model = editor.getModel();
            if (!model) {
                return null;
            }
            var config = editor.getConfiguration();
            var lastWordUnderCursor = null;
            if (!isEnabled) {
                return null;
            }
            var r = multiCursorFind(editor, {
                changeFindSearchString: false,
                allowMultiline: false,
                highlightFindOptions: false
            });
            if (!r) {
                return null;
            }
            var hasFindOccurrences = modes_1.DocumentHighlightProviderRegistry.has(model);
            if (r.currentMatch) {
                // This is an empty selection
                if (hasFindOccurrences) {
                    // Do not interfere with semantic word highlighting in the no selection case
                    return null;
                }
                if (!config.contribInfo.occurrencesHighlight) {
                    return null;
                }
                lastWordUnderCursor = r.currentMatch;
            }
            if (/^[ \t]+$/.test(r.searchText)) {
                // whitespace only selection
                return null;
            }
            if (r.searchText.length > 200) {
                // very long selection
                return null;
            }
            var controller = CommonFindController.get(editor);
            if (!controller) {
                return null;
            }
            var findState = controller.getState();
            var caseSensitive = findState.matchCase;
            var selections = editor.getSelections();
            var firstSelectedText = model.getValueInRange(selections[0]);
            if (!caseSensitive) {
                firstSelectedText = firstSelectedText.toLowerCase();
            }
            for (var i = 1; i < selections.length; i++) {
                var selectedText = model.getValueInRange(selections[i]);
                if (!caseSensitive) {
                    selectedText = selectedText.toLowerCase();
                }
                if (firstSelectedText !== selectedText) {
                    // not all selections have the same text
                    return null;
                }
            }
            return new SelectionHighlighterState(lastWordUnderCursor, 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) {
                if (this.decorations.length > 0) {
                    this.decorations = this.editor.deltaDecorations(this.decorations, []);
                }
                return;
            }
            var model = this.editor.getModel();
            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
                        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_1._SELECTION_HIGHLIGHT : SelectionHighlighter_1._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 = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            className: 'selectionHighlight',
            overviewRuler: {
                color: '#A0A0A0',
                darkColor: '#A0A0A0',
                position: editorCommon.OverviewRulerLane.Center
            }
        });
        SelectionHighlighter._SELECTION_HIGHLIGHT = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            className: 'selectionHighlight',
        });
        SelectionHighlighter = SelectionHighlighter_1 = __decorate([
            editorCommonExtensions_1.commonEditorContribution
        ], SelectionHighlighter);
        return SelectionHighlighter;
        var SelectionHighlighter_1;
    }(lifecycle_1.Disposable));
    exports.SelectionHighlighter = SelectionHighlighter;
    var ShowNextFindTermAction = (function (_super) {
        __extends(ShowNextFindTermAction, _super);
        function ShowNextFindTermAction() {
            return _super.call(this, {
                id: findModel_1.FIND_IDS.ShowNextFindTermAction,
                label: nls.localize(12, null),
                alias: 'Show Next Find Term',
                precondition: exports.CONTEXT_FIND_WIDGET_VISIBLE,
                kbOpts: {
                    weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(5),
                    kbExpr: contextkey_1.ContextKeyExpr.and(exports.CONTEXT_FIND_INPUT_FOCUSSED, editorContextKeys_1.EditorContextKeys.focus),
                    primary: findModel_1.ShowNextFindTermKeybinding.primary,
                    mac: findModel_1.ShowNextFindTermKeybinding.mac,
                    win: findModel_1.ShowNextFindTermKeybinding.win,
                    linux: findModel_1.ShowNextFindTermKeybinding.linux
                }
            }) || this;
        }
        ShowNextFindTermAction.prototype._run = function (controller) {
            return controller.showNextFindTerm();
        };
        ShowNextFindTermAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], ShowNextFindTermAction);
        return ShowNextFindTermAction;
    }(MatchFindAction));
    exports.ShowNextFindTermAction = ShowNextFindTermAction;
    var ShpwPreviousFindTermAction = (function (_super) {
        __extends(ShpwPreviousFindTermAction, _super);
        function ShpwPreviousFindTermAction() {
            return _super.call(this, {
                id: findModel_1.FIND_IDS.ShowPreviousFindTermAction,
                label: nls.localize(13, null),
                alias: 'Find Show Previous Find Term',
                precondition: exports.CONTEXT_FIND_WIDGET_VISIBLE,
                kbOpts: {
                    weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(5),
                    kbExpr: contextkey_1.ContextKeyExpr.and(exports.CONTEXT_FIND_INPUT_FOCUSSED, editorContextKeys_1.EditorContextKeys.focus),
                    primary: findModel_1.ShowPreviousFindTermKeybinding.primary,
                    mac: findModel_1.ShowPreviousFindTermKeybinding.mac,
                    win: findModel_1.ShowPreviousFindTermKeybinding.win,
                    linux: findModel_1.ShowPreviousFindTermKeybinding.linux
                }
            }) || this;
        }
        ShpwPreviousFindTermAction.prototype._run = function (controller) {
            return controller.showPreviousFindTerm();
        };
        ShpwPreviousFindTermAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], ShpwPreviousFindTermAction);
        return ShpwPreviousFindTermAction;
    }(MatchFindAction));
    exports.ShpwPreviousFindTermAction = ShpwPreviousFindTermAction;
    var FindCommand = editorCommonExtensions_1.EditorCommand.bindToContribution(CommonFindController.get);
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new FindCommand({
        id: findModel_1.FIND_IDS.CloseFindWidgetCommand,
        precondition: exports.CONTEXT_FIND_WIDGET_VISIBLE,
        handler: function (x) { return x.closeFindWidget(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(5),
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 9 /* Escape */,
            secondary: [1024 /* Shift */ | 9 /* Escape */]
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new FindCommand({
        id: findModel_1.FIND_IDS.ToggleCaseSensitiveCommand,
        precondition: null,
        handler: function (x) { return x.toggleCaseSensitive(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(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
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new FindCommand({
        id: findModel_1.FIND_IDS.ToggleWholeWordCommand,
        precondition: null,
        handler: function (x) { return x.toggleWholeWords(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(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
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new FindCommand({
        id: findModel_1.FIND_IDS.ToggleRegexCommand,
        precondition: null,
        handler: function (x) { return x.toggleRegex(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(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
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new FindCommand({
        id: findModel_1.FIND_IDS.ToggleSearchScopeCommand,
        precondition: null,
        handler: function (x) { return x.toggleSearchScope(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(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
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new FindCommand({
        id: findModel_1.FIND_IDS.ReplaceOneAction,
        precondition: exports.CONTEXT_FIND_WIDGET_VISIBLE,
        handler: function (x) { return x.replace(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(5),
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 22 /* KEY_1 */
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new FindCommand({
        id: findModel_1.FIND_IDS.ReplaceAllAction,
        precondition: exports.CONTEXT_FIND_WIDGET_VISIBLE,
        handler: function (x) { return x.replaceAll(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(5),
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 3 /* Enter */
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new FindCommand({
        id: findModel_1.FIND_IDS.SelectAllMatchesAction,
        precondition: exports.CONTEXT_FIND_WIDGET_VISIBLE,
        handler: function (x) { return x.selectAllMatches(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(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.
 *--------------------------------------------------------------------------------------------*/
/// <amd-dependency path="vs/css!./folding" />
















define(__m[458/*vs/editor/contrib/folding/browser/folding*/], __M([1/*require*/,0/*exports*/,349/*vs/nls!vs/editor/contrib/folding/browser/folding*/,29/*vs/base/common/types*/,4/*vs/base/browser/dom*/,18/*vs/base/common/async*/,40/*vs/base/common/keyCodes*/,3/*vs/base/common/lifecycle*/,2/*vs/editor/common/core/range*/,13/*vs/editor/common/editorCommonExtensions*/,25/*vs/editor/browser/editorBrowser*/,30/*vs/editor/browser/editorBrowserExtensions*/,333/*vs/editor/contrib/folding/common/foldingModel*/,257/*vs/editor/contrib/folding/common/indentFoldStrategy*/,256/*vs/editor/contrib/folding/common/folding*/,21/*vs/editor/common/editorContextKeys*/,328/*vs/css!vs/editor/contrib/folding/browser/folding*/]), function (require, exports, nls, types, dom, async_1, keyCodes_1, lifecycle_1, range_1, editorCommonExtensions_1, editorBrowser_1, editorBrowserExtensions_1, foldingModel_1, indentFoldStrategy_1, folding_1, editorContextKeys_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var FoldingController = (function () {
        function FoldingController(editor) {
            var _this = this;
            this.editor = editor;
            this._isEnabled = this.editor.getConfiguration().contribInfo.folding;
            this._showFoldingControls = this.editor.getConfiguration().contribInfo.showFoldingControls;
            this.globalToDispose = [];
            this.localToDispose = [];
            this.decorations = [];
            this.computeToken = 0;
            this.globalToDispose.push(this.editor.onDidChangeModel(function () { return _this.onModelChanged(); }));
            this.globalToDispose.push(this.editor.onDidChangeConfiguration(function (e) {
                var oldIsEnabled = _this._isEnabled;
                _this._isEnabled = _this.editor.getConfiguration().contribInfo.folding;
                if (oldIsEnabled !== _this._isEnabled) {
                    _this.onModelChanged();
                }
                var oldShowFoldingControls = _this._showFoldingControls;
                _this._showFoldingControls = _this.editor.getConfiguration().contribInfo.showFoldingControls;
                if (oldShowFoldingControls !== _this._showFoldingControls) {
                    _this.updateHideFoldIconClass();
                }
            }));
            this.onModelChanged();
        }
        FoldingController_1 = FoldingController;
        FoldingController.get = function (editor) {
            return editor.getContribution(folding_1.ID);
        };
        FoldingController.prototype.getId = function () {
            return folding_1.ID;
        };
        FoldingController.prototype.dispose = function () {
            this.cleanState();
            this.globalToDispose = lifecycle_1.dispose(this.globalToDispose);
        };
        FoldingController.prototype.updateHideFoldIconClass = function () {
            var domNode = this.editor.getDomNode();
            if (domNode) {
                dom.toggleClass(domNode, 'alwaysShowFoldIcons', this._showFoldingControls === 'always');
            }
        };
        /**
         * Store view state.
         */
        FoldingController.prototype.saveViewState = function () {
            var model = this.editor.getModel();
            if (!model) {
                return {};
            }
            var collapsedRegions = [];
            this.decorations.forEach(function (d) {
                if (d.isCollapsed) {
                    var range = d.getDecorationRange(model);
                    if (range) {
                        collapsedRegions.push({ startLineNumber: range.startLineNumber, endLineNumber: range.endLineNumber, indent: d.indent, isCollapsed: true });
                    }
                }
            });
            return { collapsedRegions: collapsedRegions, lineCount: model.getLineCount() };
        };
        /**
         * Restore view state.
         */
        FoldingController.prototype.restoreViewState = function (state) {
            var model = this.editor.getModel();
            if (!model) {
                return;
            }
            if (!this._isEnabled) {
                return;
            }
            if (!state || !Array.isArray(state.collapsedRegions) || state.collapsedRegions.length === 0 || state.lineCount !== model.getLineCount()) {
                return;
            }
            // State should be applied on the clean state
            // Clean the state
            this.cleanState();
            // apply state
            this.applyRegions(state.collapsedRegions);
            // Start listening to the model
            this.onModelChanged();
        };
        FoldingController.prototype.cleanState = function () {
            this.localToDispose = lifecycle_1.dispose(this.localToDispose);
        };
        FoldingController.prototype.applyRegions = function (regions) {
            var _this = this;
            var model = this.editor.getModel();
            if (!model) {
                return;
            }
            var updateHiddenRegions = false;
            regions = indentFoldStrategy_1.limitByIndent(regions, FoldingController_1.MAX_FOLDING_REGIONS).sort(function (r1, r2) { return r1.startLineNumber - r2.startLineNumber; });
            this.editor.changeDecorations(function (changeAccessor) {
                var newDecorations = [];
                var k = 0, i = 0;
                while (i < _this.decorations.length && k < regions.length) {
                    var dec = _this.decorations[i];
                    var decRange = dec.getDecorationRange(model);
                    if (!decRange) {
                        updateHiddenRegions = updateHiddenRegions || dec.isCollapsed;
                        dec.dispose(changeAccessor);
                        i++;
                    }
                    else {
                        while (k < regions.length && decRange.startLineNumber > regions[k].startLineNumber) {
                            var region = regions[k];
                            updateHiddenRegions = updateHiddenRegions || region.isCollapsed;
                            newDecorations.push(new foldingModel_1.CollapsibleRegion(region, model, changeAccessor));
                            k++;
                        }
                        if (k < regions.length) {
                            var currRange = regions[k];
                            if (decRange.startLineNumber < currRange.startLineNumber) {
                                updateHiddenRegions = updateHiddenRegions || dec.isCollapsed;
                                dec.dispose(changeAccessor);
                                i++;
                            }
                            else if (decRange.startLineNumber === currRange.startLineNumber) {
                                if (dec.isCollapsed && (dec.startLineNumber !== currRange.startLineNumber || dec.endLineNumber !== currRange.endLineNumber)) {
                                    updateHiddenRegions = true;
                                }
                                currRange.isCollapsed = dec.isCollapsed; // preserve collapse state
                                dec.update(currRange, model, changeAccessor);
                                newDecorations.push(dec);
                                i++;
                                k++;
                            }
                        }
                    }
                }
                while (i < _this.decorations.length) {
                    var dec = _this.decorations[i];
                    updateHiddenRegions = updateHiddenRegions || dec.isCollapsed;
                    dec.dispose(changeAccessor);
                    i++;
                }
                while (k < regions.length) {
                    var region = regions[k];
                    updateHiddenRegions = updateHiddenRegions || region.isCollapsed;
                    newDecorations.push(new foldingModel_1.CollapsibleRegion(region, model, changeAccessor));
                    k++;
                }
                _this.decorations = newDecorations;
            });
            if (updateHiddenRegions) {
                this.updateHiddenAreas();
            }
        };
        FoldingController.prototype.onModelChanged = function () {
            var _this = this;
            this.cleanState();
            this.updateHideFoldIconClass();
            var model = this.editor.getModel();
            if (!this._isEnabled || !model) {
                return;
            }
            this.computeAndApplyCollapsibleRegions();
            this.contentChangedScheduler = new async_1.RunOnceScheduler(function () { return _this.computeAndApplyCollapsibleRegions(); }, 200);
            this.cursorChangedScheduler = new async_1.RunOnceScheduler(function () { return _this.revealCursor(); }, 200);
            this.localToDispose.push(this.contentChangedScheduler);
            this.localToDispose.push(this.cursorChangedScheduler);
            this.localToDispose.push(this.editor.onDidChangeModelContent(function (e) { return _this.contentChangedScheduler.schedule(); }));
            this.localToDispose.push(this.editor.onDidChangeCursorPosition(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;
                }
                _this.cursorChangedScheduler.schedule();
            }));
            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 () { return _this.disposeDecorations(); } });
        };
        FoldingController.prototype.computeAndApplyCollapsibleRegions = function () {
            var model = this.editor.getModel();
            this.applyRegions(model ? indentFoldStrategy_1.computeRanges(model) : []);
        };
        FoldingController.prototype.disposeDecorations = function () {
            var _this = this;
            this.editor.changeDecorations(function (changeAccessor) {
                _this.decorations.forEach(function (dec) { return dec.dispose(changeAccessor); });
            });
            this.decorations = [];
            this.editor.setHiddenAreas([]);
        };
        FoldingController.prototype.revealCursor = function () {
            var _this = this;
            var model = this.editor.getModel();
            if (!model) {
                return;
            }
            var hasChanges = false;
            var selections = this.editor.getSelections();
            this.editor.changeDecorations(function (changeAccessor) {
                return _this.decorations.forEach(function (dec) {
                    if (dec.isCollapsed) {
                        var decRange = dec.getDecorationRange(model);
                        if (decRange) {
                            for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) {
                                var selection = selections_1[_i];
                                // reveal if cursor in in one of the collapsed line (not the first)
                                if (decRange.startLineNumber < selection.selectionStartLineNumber && selection.selectionStartLineNumber <= decRange.endLineNumber) {
                                    dec.setCollapsed(false, changeAccessor);
                                    hasChanges = true;
                                    break;
                                }
                            }
                        }
                    }
                });
            });
            if (hasChanges) {
                this.updateHiddenAreas(this.editor.getPosition().lineNumber);
            }
        };
        FoldingController.prototype.onEditorMouseDown = function (e) {
            this.mouseDownInfo = null;
            if (this.decorations.length === 0) {
                return;
            }
            var range = e.target.range;
            if (!range) {
                return;
            }
            if (!e.event.leftButton) {
                return;
            }
            var model = this.editor.getModel();
            var iconClicked = false;
            switch (e.target.type) {
                case editorBrowser_1.MouseTargetType.GUTTER_LINE_DECORATIONS:
                    iconClicked = true;
                    break;
                case editorBrowser_1.MouseTargetType.CONTENT_EMPTY:
                case editorBrowser_1.MouseTargetType.CONTENT_TEXT:
                    if (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;
            if (!this.mouseDownInfo) {
                return;
            }
            var lineNumber = this.mouseDownInfo.lineNumber;
            var iconClicked = this.mouseDownInfo.iconClicked;
            var range = e.target.range;
            if (!range || range.startLineNumber !== lineNumber) {
                return;
            }
            var model = this.editor.getModel();
            if (iconClicked) {
                if (e.target.type !== editorBrowser_1.MouseTargetType.GUTTER_LINE_DECORATIONS) {
                    return;
                }
            }
            else {
                if (range.startColumn !== model.getLineMaxColumn(lineNumber)) {
                    return;
                }
            }
            this.editor.changeDecorations(function (changeAccessor) {
                for (var i = 0; i < _this.decorations.length; i++) {
                    var dec = _this.decorations[i];
                    var decRange = dec.getDecorationRange(model);
                    if (decRange && decRange.startLineNumber === lineNumber) {
                        if (iconClicked || dec.isCollapsed) {
                            dec.setCollapsed(!dec.isCollapsed, changeAccessor);
                            _this.updateHiddenAreas(lineNumber);
                        }
                        return;
                    }
                }
            });
        };
        FoldingController.prototype.updateHiddenAreas = function (focusLine) {
            var model = this.editor.getModel();
            var selections = this.editor.getSelections();
            var updateSelections = false;
            var hiddenAreas = [];
            this.decorations.filter(function (dec) { return dec.isCollapsed; }).forEach(function (dec) {
                var decRange = dec.getDecorationRange(model);
                if (!decRange) {
                    return;
                }
                hiddenAreas.push(new range_1.Range(decRange.startLineNumber + 1, 1, decRange.endLineNumber, 1));
                selections.forEach(function (selection, i) {
                    if (range_1.Range.containsPosition(decRange, selection.getStartPosition())) {
                        selections[i] = selection = selection.setStartPosition(decRange.startLineNumber, model.getLineMaxColumn(decRange.startLineNumber));
                        updateSelections = true;
                    }
                    if (range_1.Range.containsPosition(decRange, selection.getEndPosition())) {
                        selections[i] = selection.setEndPosition(decRange.startLineNumber, model.getLineMaxColumn(decRange.startLineNumber));
                        updateSelections = true;
                    }
                });
            });
            if (updateSelections) {
                this.editor.setSelections(selections);
            }
            this.editor.setHiddenAreas(hiddenAreas);
            if (focusLine) {
                this.editor.revealPositionInCenterIfOutsideViewport({ lineNumber: focusLine, column: 1 });
            }
        };
        FoldingController.prototype.unfold = function (levels) {
            var _this = this;
            var model = this.editor.getModel();
            var hasChanges = false;
            var selections = this.editor.getSelections();
            var selectionsHasChanged = false;
            selections.forEach(function (selection, index) {
                var toUnfold = foldingModel_1.getCollapsibleRegionsToUnfoldAtLine(_this.decorations, model, selection.startLineNumber, levels);
                if (toUnfold.length > 0) {
                    toUnfold.forEach(function (collapsibleRegion, index) {
                        _this.editor.changeDecorations(function (changeAccessor) {
                            collapsibleRegion.setCollapsed(false, changeAccessor);
                            hasChanges = true;
                        });
                    });
                    if (!foldingModel_1.doesLineBelongsToCollapsibleRegion(toUnfold[0].foldingRange, selection.startLineNumber)) {
                        var lineNumber = toUnfold[0].startLineNumber, column = model.getLineMaxColumn(toUnfold[0].startLineNumber);
                        selections[index] = selection.setEndPosition(lineNumber, column).setStartPosition(lineNumber, column);
                        selectionsHasChanged = true;
                    }
                }
            });
            if (selectionsHasChanged) {
                this.editor.setSelections(selections);
            }
            if (hasChanges) {
                this.updateHiddenAreas(selections[0].startLineNumber);
            }
        };
        FoldingController.prototype.fold = function (levels, up) {
            var _this = this;
            var hasChanges = false;
            var selections = this.editor.getSelections();
            selections.forEach(function (selection) {
                var lineNumber = selection.startLineNumber;
                var toFold = foldingModel_1.getCollapsibleRegionsToFoldAtLine(_this.decorations, _this.editor.getModel(), lineNumber, levels, up);
                toFold.forEach(function (collapsibleRegion) { return _this.editor.changeDecorations(function (changeAccessor) {
                    collapsibleRegion.setCollapsed(true, changeAccessor);
                    hasChanges = true;
                }); });
            });
            if (hasChanges) {
                this.updateHiddenAreas(selections[0].startLineNumber);
            }
        };
        FoldingController.prototype.foldUnfoldRecursively = function (isFold) {
            var _this = this;
            var hasChanges = false;
            var model = this.editor.getModel();
            var selections = this.editor.getSelections();
            selections.forEach(function (selection) {
                var lineNumber = selection.startLineNumber;
                var endLineNumber;
                var decToFoldUnfold = [];
                for (var i = 0, len = _this.decorations.length; i < len; i++) {
                    var dec = _this.decorations[i];
                    var decRange = dec.getDecorationRange(model);
                    if (!decRange) {
                        continue;
                    }
                    if (decRange.startLineNumber >= lineNumber && (decRange.endLineNumber <= endLineNumber || typeof endLineNumber === 'undefined')) {
                        //Protect against cursor not being in decoration and lower decoration folding/unfolding
                        if (decRange.startLineNumber !== lineNumber && typeof endLineNumber === 'undefined') {
                            return;
                        }
                        endLineNumber = endLineNumber || decRange.endLineNumber;
                        decToFoldUnfold.push(dec);
                    }
                }
                ;
                if (decToFoldUnfold.length > 0) {
                    decToFoldUnfold.forEach(function (dec) {
                        _this.editor.changeDecorations(function (changeAccessor) {
                            dec.setCollapsed(isFold, changeAccessor);
                            hasChanges = true;
                        });
                    });
                }
            });
            if (hasChanges) {
                this.updateHiddenAreas(selections[0].startLineNumber);
            }
        };
        FoldingController.prototype.foldAll = function () {
            this.changeAll(true);
        };
        FoldingController.prototype.unfoldAll = function () {
            this.changeAll(false);
        };
        FoldingController.prototype.changeAll = function (collapse) {
            var _this = this;
            if (this.decorations.length > 0) {
                var hasChanges_1 = true;
                this.editor.changeDecorations(function (changeAccessor) {
                    _this.decorations.forEach(function (d) {
                        if (collapse !== d.isCollapsed) {
                            d.setCollapsed(collapse, changeAccessor);
                            hasChanges_1 = true;
                        }
                    });
                });
                if (hasChanges_1) {
                    this.updateHiddenAreas(this.editor.getPosition().lineNumber);
                }
            }
        };
        FoldingController.prototype.foldLevel = function (foldLevel, selectedLineNumbers) {
            var _this = this;
            var model = this.editor.getModel();
            var foldingRegionStack = [model.getFullModelRange()]; // sentinel
            var hasChanges = false;
            this.editor.changeDecorations(function (changeAccessor) {
                _this.decorations.forEach(function (dec) {
                    var decRange = dec.getDecorationRange(model);
                    if (decRange) {
                        while (!range_1.Range.containsRange(foldingRegionStack[foldingRegionStack.length - 1], decRange)) {
                            foldingRegionStack.pop();
                        }
                        foldingRegionStack.push(decRange);
                        if (foldingRegionStack.length === foldLevel + 1 && !dec.isCollapsed && !selectedLineNumbers.some(function (lineNumber) { return decRange.startLineNumber < lineNumber && lineNumber <= decRange.endLineNumber; })) {
                            dec.setCollapsed(true, changeAccessor);
                            hasChanges = true;
                        }
                    }
                });
            });
            if (hasChanges) {
                this.updateHiddenAreas(selectedLineNumbers[0]);
            }
        };
        FoldingController.MAX_FOLDING_REGIONS = 5000;
        FoldingController = FoldingController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution
        ], FoldingController);
        return FoldingController;
        var FoldingController_1;
    }());
    exports.FoldingController = FoldingController;
    var FoldingAction = (function (_super) {
        __extends(FoldingAction, _super);
        function FoldingAction() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        FoldingAction.prototype.runEditorCommand = function (accessor, editor, args) {
            var foldingController = FoldingController.get(editor);
            if (!foldingController) {
                return;
            }
            this.reportTelemetry(accessor, editor);
            this.invoke(foldingController, editor, args);
        };
        FoldingAction.prototype.run = function (accessor, editor) {
        };
        return FoldingAction;
    }(editorCommonExtensions_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;
            }
        }
        return true;
    }
    var UnfoldAction = (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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 89 /* US_CLOSE_SQUARE_BRACKET */,
                    mac: {
                        primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 89 /* US_CLOSE_SQUARE_BRACKET */
                    }
                },
                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\t* 'level': Number of levels to unfold\n\t\t\t\t\t\t",
                            constraint: foldingArgumentsConstraint
                        }
                    ]
                }
            }) || this;
        }
        UnfoldAction.prototype.invoke = function (foldingController, editor, args) {
            foldingController.unfold(args ? args.levels || 1 : 1);
        };
        UnfoldAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], UnfoldAction);
        return UnfoldAction;
    }(FoldingAction));
    var UnFoldRecursivelyAction = (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.textFocus,
                    primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 89 /* US_CLOSE_SQUARE_BRACKET */)
                }
            }) || this;
        }
        UnFoldRecursivelyAction.prototype.invoke = function (foldingController, editor, args) {
            foldingController.foldUnfoldRecursively(false);
        };
        UnFoldRecursivelyAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], UnFoldRecursivelyAction);
        return UnFoldRecursivelyAction;
    }(FoldingAction));
    var FoldAction = (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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 87 /* US_OPEN_SQUARE_BRACKET */,
                    mac: {
                        primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 87 /* US_OPEN_SQUARE_BRACKET */
                    }
                },
                description: {
                    description: 'Fold the content in the editor',
                    args: [
                        {
                            name: 'Fold editor argument',
                            description: "Property-value pairs that can be passed through this argument:\n\t\t\t\t\t\t\t* 'levels': Number of levels to fold\n\t\t\t\t\t\t\t* 'up': If 'true', folds given number of levels up otherwise folds down\n\t\t\t\t\t\t",
                            constraint: foldingArgumentsConstraint
                        }
                    ]
                }
            }) || this;
        }
        FoldAction.prototype.invoke = function (foldingController, editor, args) {
            args = args ? args : { levels: 1, direction: 'up' };
            foldingController.fold(args.levels || 1, args.direction === 'up');
        };
        FoldAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], FoldAction);
        return FoldAction;
    }(FoldingAction));
    var FoldRecursivelyAction = (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.textFocus,
                    primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 87 /* US_OPEN_SQUARE_BRACKET */)
                }
            }) || this;
        }
        FoldRecursivelyAction.prototype.invoke = function (foldingController, editor) {
            foldingController.foldUnfoldRecursively(true);
        };
        FoldRecursivelyAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], FoldRecursivelyAction);
        return FoldRecursivelyAction;
    }(FoldingAction));
    var FoldAllAction = (function (_super) {
        __extends(FoldAllAction, _super);
        function FoldAllAction() {
            return _super.call(this, {
                id: 'editor.foldAll',
                label: nls.localize(4, null),
                alias: 'Fold All',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 21 /* KEY_0 */)
                }
            }) || this;
        }
        FoldAllAction.prototype.invoke = function (foldingController, editor) {
            foldingController.foldAll();
        };
        FoldAllAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], FoldAllAction);
        return FoldAllAction;
    }(FoldingAction));
    var UnfoldAllAction = (function (_super) {
        __extends(UnfoldAllAction, _super);
        function UnfoldAllAction() {
            return _super.call(this, {
                id: 'editor.unfoldAll',
                label: nls.localize(5, null),
                alias: 'Unfold All',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 40 /* KEY_J */)
                }
            }) || this;
        }
        UnfoldAllAction.prototype.invoke = function (foldingController, editor) {
            foldingController.unfoldAll();
        };
        UnfoldAllAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], UnfoldAllAction);
        return UnfoldAllAction;
    }(FoldingAction));
    var FoldLevelAction = (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.getSelectedLines = function (editor) {
            return editor.getSelections().map(function (s) { return s.startLineNumber; });
        };
        FoldLevelAction.prototype.invoke = function (foldingController, editor) {
            foldingController.foldLevel(this.getFoldingLevel(), this.getSelectedLines(editor));
        };
        FoldLevelAction.ID_PREFIX = 'editor.foldLevel';
        FoldLevelAction.ID = function (level) { return FoldLevelAction.ID_PREFIX + level; };
        return FoldLevelAction;
    }(FoldingAction));
    for (var i = 1; i <= 9; i++) {
        editorCommonExtensions_1.CommonEditorRegistry.registerEditorAction(new FoldLevelAction({
            id: FoldLevelAction.ID(i),
            label: nls.localize(6, null, i),
            alias: "Fold Level " + i,
            precondition: null,
            kbOpts: {
                kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | (21 /* KEY_0 */ + i))
            }
        }));
    }
    ;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[459/*vs/editor/contrib/format/common/format*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,24/*vs/base/common/uri*/,33/*vs/base/common/arrays*/,7/*vs/base/common/winjs.base*/,2/*vs/editor/common/core/range*/,13/*vs/editor/common/editorCommonExtensions*/,17/*vs/editor/common/modes*/,56/*vs/editor/common/services/modelService*/,18/*vs/base/common/async*/]), function (require, exports, errors_1, uri_1, arrays_1, winjs_base_1, range_1, editorCommonExtensions_1, modes_1, modelService_1, async_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function getDocumentRangeFormattingEdits(model, range, options) {
        var providers = modes_1.DocumentRangeFormattingEditProviderRegistry.ordered(model);
        if (providers.length === 0) {
            return winjs_base_1.TPromise.as(undefined);
        }
        var result;
        return async_1.sequence(providers.map(function (provider) {
            if (arrays_1.isFalsyOrEmpty(result)) {
                return function () {
                    return async_1.asWinJsPromise(function (token) { return provider.provideDocumentRangeFormattingEdits(model, range, options, token); }).then(function (value) {
                        result = value;
                    }, errors_1.onUnexpectedExternalError);
                };
            }
            return undefined;
        })).then(function () { return result; });
    }
    exports.getDocumentRangeFormattingEdits = getDocumentRangeFormattingEdits;
    function getDocumentFormattingEdits(model, options) {
        var providers = modes_1.DocumentFormattingEditProviderRegistry.ordered(model);
        // try range formatters when no document formatter is registered
        if (providers.length === 0) {
            return getDocumentRangeFormattingEdits(model, model.getFullModelRange(), options);
        }
        var result;
        return async_1.sequence(providers.map(function (provider) {
            if (arrays_1.isFalsyOrEmpty(result)) {
                return function () {
                    return async_1.asWinJsPromise(function (token) { return provider.provideDocumentFormattingEdits(model, options, token); }).then(function (value) {
                        result = value;
                    }, errors_1.onUnexpectedExternalError);
                };
            }
            return undefined;
        })).then(function () { return result; });
    }
    exports.getDocumentFormattingEdits = getDocumentFormattingEdits;
    function getOnTypeFormattingEdits(model, position, ch, options) {
        var support = modes_1.OnTypeFormattingEditProviderRegistry.ordered(model)[0];
        if (!support) {
            return winjs_base_1.TPromise.as(undefined);
        }
        if (support.autoFormatTriggerCharacters.indexOf(ch) < 0) {
            return winjs_base_1.TPromise.as(undefined);
        }
        return async_1.asWinJsPromise(function (token) {
            return support.provideOnTypeFormattingEdits(model, position, ch, options, token);
        }).then(function (r) { return r; }, errors_1.onUnexpectedExternalError);
    }
    exports.getOnTypeFormattingEdits = getOnTypeFormattingEdits;
    editorCommonExtensions_1.CommonEditorRegistry.registerLanguageCommand('_executeFormatRangeProvider', function (accessor, args) {
        var resource = args.resource, range = args.range, options = args.options;
        if (!(resource instanceof uri_1.default) || !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 getDocumentRangeFormattingEdits(model, range_1.Range.lift(range), options);
    });
    editorCommonExtensions_1.CommonEditorRegistry.registerLanguageCommand('_executeFormatDocumentProvider', function (accessor, args) {
        var resource = args.resource, options = args.options;
        if (!(resource instanceof uri_1.default)) {
            throw errors_1.illegalArgument('resource');
        }
        var model = accessor.get(modelService_1.IModelService).getModel(resource);
        if (!model) {
            throw errors_1.illegalArgument('resource');
        }
        return getDocumentFormattingEdits(model, options);
    });
    editorCommonExtensions_1.CommonEditorRegistry.registerDefaultLanguageCommand('_executeFormatOnTypeProvider', function (model, position, args) {
        var ch = args.ch, options = args.options;
        if (typeof ch !== 'string') {
            throw errors_1.illegalArgument('ch');
        }
        return getOnTypeFormattingEdits(model, position, ch, options);
    });
});




















define(__m[460/*vs/editor/contrib/format/browser/formatActions*/], __M([1/*require*/,0/*exports*/,350/*vs/nls!vs/editor/contrib/format/browser/formatActions*/,33/*vs/base/common/arrays*/,40/*vs/base/common/keyCodes*/,3/*vs/base/common/lifecycle*/,7/*vs/base/common/winjs.base*/,19/*vs/platform/contextkey/common/contextkey*/,13/*vs/editor/common/editorCommonExtensions*/,17/*vs/editor/common/modes*/,459/*vs/editor/contrib/format/common/format*/,258/*vs/editor/contrib/format/common/formatCommand*/,31/*vs/platform/commands/common/commands*/,42/*vs/editor/common/services/codeEditorService*/,61/*vs/editor/common/services/editorWorkerService*/,89/*vs/editor/common/core/characterClassifier*/,2/*vs/editor/common/core/range*/,51/*vs/base/browser/ui/aria/aria*/,131/*vs/editor/common/core/editorState*/,21/*vs/editor/common/editorContextKeys*/]), function (require, exports, nls, arrays_1, keyCodes_1, lifecycle_1, winjs_base_1, contextkey_1, editorCommonExtensions_1, modes_1, format_1, formatCommand_1, commands_1, codeEditorService_1, editorWorkerService_1, characterClassifier_1, range_1, aria_1, editorState_1, editorContextKeys_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    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));
            }
        }
    }
    var FormatOnType = (function () {
        function FormatOnType(editor, workerService) {
            var _this = this;
            this.editor = editor;
            this.workerService = workerService;
            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.OnTypeFormattingEditProviderRegistry.onDidChange(this.update, this));
        }
        FormatOnType_1 = FormatOnType;
        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.getModel()) {
                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.getSelections().length > 1) {
                return;
            }
            var model = this.editor.getModel(), position = this.editor.getPosition(), 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;
                    }
                }
            });
            var modelOpts = model.getOptions();
            format_1.getOnTypeFormattingEdits(model, position, ch, {
                tabSize: modelOpts.tabSize,
                insertSpaces: modelOpts.insertSpaces
            }).then(function (edits) {
                return _this.workerService.computeMoreMinimalEdits(model.uri, edits, []);
            }).then(function (edits) {
                unbind.dispose();
                if (canceled || arrays_1.isFalsyOrEmpty(edits)) {
                    return;
                }
                formatCommand_1.EditOperationsCommand.execute(_this.editor, edits);
                alertFormattingEdits(edits);
            }, function (err) {
                unbind.dispose();
                throw err;
            });
        };
        FormatOnType.prototype.getId = function () {
            return FormatOnType_1.ID;
        };
        FormatOnType.prototype.dispose = function () {
            this.callOnDispose = lifecycle_1.dispose(this.callOnDispose);
            this.callOnModel = lifecycle_1.dispose(this.callOnModel);
        };
        FormatOnType.ID = 'editor.contrib.autoFormat';
        FormatOnType = FormatOnType_1 = __decorate([
            editorCommonExtensions_1.commonEditorContribution,
            __param(1, editorWorkerService_1.IEditorWorkerService)
        ], FormatOnType);
        return FormatOnType;
        var FormatOnType_1;
    }());
    var FormatOnPaste = (function () {
        function FormatOnPaste(editor, workerService) {
            var _this = this;
            this.editor = editor;
            this.workerService = workerService;
            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_1 = FormatOnPaste;
        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.getModel()) {
                return;
            }
            var model = this.editor.getModel();
            // no support
            var support = modes_1.DocumentRangeFormattingEditProviderRegistry.ordered(model)[0];
            if (!support || !support.provideDocumentRangeFormattingEdits) {
                return;
            }
            this.callOnModel.push(this.editor.onDidPaste(function (range) {
                _this.trigger(range);
            }));
        };
        FormatOnPaste.prototype.trigger = function (range) {
            var _this = this;
            if (this.editor.getSelections().length > 1) {
                return;
            }
            var model = this.editor.getModel();
            var _a = model.getOptions(), tabSize = _a.tabSize, insertSpaces = _a.insertSpaces;
            var state = new editorState_1.EditorState(this.editor, 1 /* Value */ | 4 /* Position */);
            format_1.getDocumentRangeFormattingEdits(model, range, { tabSize: tabSize, insertSpaces: insertSpaces }).then(function (edits) {
                return _this.workerService.computeMoreMinimalEdits(model.uri, edits, []);
            }).then(function (edits) {
                if (!state.validate(_this.editor) || arrays_1.isFalsyOrEmpty(edits)) {
                    return;
                }
                formatCommand_1.EditOperationsCommand.execute(_this.editor, edits);
                alertFormattingEdits(edits);
            });
        };
        FormatOnPaste.prototype.getId = function () {
            return FormatOnPaste_1.ID;
        };
        FormatOnPaste.prototype.dispose = function () {
            this.callOnDispose = lifecycle_1.dispose(this.callOnDispose);
            this.callOnModel = lifecycle_1.dispose(this.callOnModel);
        };
        FormatOnPaste.ID = 'editor.contrib.formatOnPaste';
        FormatOnPaste = FormatOnPaste_1 = __decorate([
            editorCommonExtensions_1.commonEditorContribution,
            __param(1, editorWorkerService_1.IEditorWorkerService)
        ], FormatOnPaste);
        return FormatOnPaste;
        var FormatOnPaste_1;
    }());
    var AbstractFormatAction = (function (_super) {
        __extends(AbstractFormatAction, _super);
        function AbstractFormatAction() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        AbstractFormatAction.prototype.run = function (accessor, editor) {
            var workerService = accessor.get(editorWorkerService_1.IEditorWorkerService);
            var formattingPromise = this._getFormattingEdits(editor);
            if (!formattingPromise) {
                return winjs_base_1.TPromise.as(void 0);
            }
            // Capture the state of the editor
            var state = new editorState_1.EditorState(editor, 1 /* Value */ | 4 /* Position */);
            // Receive formatted value from worker
            return formattingPromise.then(function (edits) { return workerService.computeMoreMinimalEdits(editor.getModel().uri, edits, editor.getSelections()); }).then(function (edits) {
                if (!state.validate(editor) || arrays_1.isFalsyOrEmpty(edits)) {
                    return;
                }
                formatCommand_1.EditOperationsCommand.execute(editor, edits);
                alertFormattingEdits(edits);
                editor.focus();
            });
        };
        return AbstractFormatAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.AbstractFormatAction = AbstractFormatAction;
    var FormatDocumentAction = (function (_super) {
        __extends(FormatDocumentAction, _super);
        function FormatDocumentAction() {
            return _super.call(this, {
                id: 'editor.action.formatDocument',
                label: nls.localize(4, null),
                alias: 'Format Document',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasDocumentFormattingProvider),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 1024 /* Shift */ | 512 /* Alt */ | 36 /* KEY_F */,
                    // secondary: [KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_D)],
                    linux: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 39 /* KEY_I */ }
                },
                menuOpts: {
                    group: '1_modification',
                    order: 1.3
                }
            }) || this;
        }
        FormatDocumentAction.prototype._getFormattingEdits = function (editor) {
            var model = editor.getModel();
            var _a = model.getOptions(), tabSize = _a.tabSize, insertSpaces = _a.insertSpaces;
            return format_1.getDocumentFormattingEdits(model, { tabSize: tabSize, insertSpaces: insertSpaces });
        };
        FormatDocumentAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], FormatDocumentAction);
        return FormatDocumentAction;
    }(AbstractFormatAction));
    exports.FormatDocumentAction = FormatDocumentAction;
    var FormatSelectionAction = (function (_super) {
        __extends(FormatSelectionAction, _super);
        function FormatSelectionAction() {
            return _super.call(this, {
                id: 'editor.action.formatSelection',
                label: nls.localize(5, null),
                alias: 'Format Code',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasDocumentSelectionFormattingProvider, editorContextKeys_1.EditorContextKeys.hasNonEmptySelection),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 36 /* KEY_F */)
                },
                menuOpts: {
                    group: '1_modification',
                    order: 1.31
                }
            }) || this;
        }
        FormatSelectionAction.prototype._getFormattingEdits = function (editor) {
            var model = editor.getModel();
            var _a = model.getOptions(), tabSize = _a.tabSize, insertSpaces = _a.insertSpaces;
            return format_1.getDocumentRangeFormattingEdits(model, editor.getSelection(), { tabSize: tabSize, insertSpaces: insertSpaces });
        };
        FormatSelectionAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], FormatSelectionAction);
        return FormatSelectionAction;
    }(AbstractFormatAction));
    exports.FormatSelectionAction = 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) {
        var editor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
        if (editor) {
            return new (function (_super) {
                __extends(class_1, _super);
                function class_1() {
                    return _super.call(this, {}) || this;
                }
                class_1.prototype._getFormattingEdits = function (editor) {
                    var model = editor.getModel();
                    var editorSelection = editor.getSelection();
                    var _a = model.getOptions(), tabSize = _a.tabSize, insertSpaces = _a.insertSpaces;
                    return editorSelection.isEmpty()
                        ? format_1.getDocumentFormattingEdits(model, { tabSize: tabSize, insertSpaces: insertSpaces })
                        : format_1.getDocumentRangeFormattingEdits(model, editorSelection, { tabSize: tabSize, insertSpaces: insertSpaces });
                };
                return class_1;
            }(AbstractFormatAction))().run(accessor, editor);
        }
        return undefined;
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[177/*vs/editor/contrib/goToDeclaration/browser/goToDeclaration*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,7/*vs/base/common/winjs.base*/,13/*vs/editor/common/editorCommonExtensions*/,17/*vs/editor/common/modes*/,18/*vs/base/common/async*/]), function (require, exports, errors_1, winjs_base_1, editorCommonExtensions_1, modes_1, async_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function outputResults(promises) {
        return winjs_base_1.TPromise.join(promises).then(function (allReferences) {
            var result = [];
            for (var _i = 0, allReferences_1 = allReferences; _i < allReferences_1.length; _i++) {
                var references = allReferences_1[_i];
                if (Array.isArray(references)) {
                    result.push.apply(result, references);
                }
                else if (references) {
                    result.push(references);
                }
            }
            return result;
        });
    }
    function getDefinitions(model, position, registry, provide) {
        var provider = registry.ordered(model);
        // get results
        var promises = provider.map(function (provider, idx) {
            return async_1.asWinJsPromise(function (token) {
                return provide(provider, model, position, token);
            }).then(function (result) {
                return result;
            }, function (err) {
                errors_1.onUnexpectedExternalError(err);
            });
        });
        return outputResults(promises);
    }
    function getDefinitionsAtPosition(model, position) {
        return getDefinitions(model, position, modes_1.DefinitionProviderRegistry, function (provider, model, position, token) {
            return provider.provideDefinition(model, position, token);
        });
    }
    exports.getDefinitionsAtPosition = getDefinitionsAtPosition;
    function getImplementationsAtPosition(model, position) {
        return getDefinitions(model, position, modes_1.ImplementationProviderRegistry, function (provider, model, position, token) {
            return provider.provideImplementation(model, position, token);
        });
    }
    exports.getImplementationsAtPosition = getImplementationsAtPosition;
    function getTypeDefinitionsAtPosition(model, position) {
        return getDefinitions(model, position, modes_1.TypeDefinitionProviderRegistry, function (provider, model, position, token) {
            return provider.provideTypeDefinition(model, position, token);
        });
    }
    exports.getTypeDefinitionsAtPosition = getTypeDefinitionsAtPosition;
    editorCommonExtensions_1.CommonEditorRegistry.registerDefaultLanguageCommand('_executeDefinitionProvider', getDefinitionsAtPosition);
    editorCommonExtensions_1.CommonEditorRegistry.registerDefaultLanguageCommand('_executeImplementationProvider', getImplementationsAtPosition);
    editorCommonExtensions_1.CommonEditorRegistry.registerDefaultLanguageCommand('_executeTypeDefinitionProvider', getTypeDefinitionsAtPosition);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[462/*vs/editor/contrib/hover/common/hover*/], __M([1/*require*/,0/*exports*/,33/*vs/base/common/arrays*/,10/*vs/base/common/errors*/,7/*vs/base/common/winjs.base*/,13/*vs/editor/common/editorCommonExtensions*/,17/*vs/editor/common/modes*/,18/*vs/base/common/async*/]), function (require, exports, arrays_1, errors_1, winjs_base_1, editorCommonExtensions_1, modes_1, async_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function getHover(model, position) {
        var supports = modes_1.HoverProviderRegistry.ordered(model);
        var values = [];
        var promises = supports.map(function (support, idx) {
            return async_1.asWinJsPromise(function (token) {
                return support.provideHover(model, position, token);
            }).then(function (result) {
                if (result) {
                    var hasRange = (typeof result.range !== 'undefined');
                    var hasHtmlContent = typeof result.contents !== 'undefined' && result.contents && result.contents.length > 0;
                    if (hasRange && hasHtmlContent) {
                        values[idx] = result;
                    }
                }
            }, function (err) {
                errors_1.onUnexpectedExternalError(err);
            });
        });
        return winjs_base_1.TPromise.join(promises).then(function () { return arrays_1.coalesce(values); });
    }
    exports.getHover = getHover;
    editorCommonExtensions_1.CommonEditorRegistry.registerDefaultLanguageCommand('_executeHoverProvider', getHover);
});











define(__m[463/*vs/editor/contrib/hover/browser/modesContentHover*/], __M([1/*require*/,0/*exports*/,355/*vs/nls!vs/editor/contrib/hover/browser/modesContentHover*/,24/*vs/base/common/uri*/,10/*vs/base/common/errors*/,4/*vs/base/browser/dom*/,7/*vs/base/common/winjs.base*/,102/*vs/base/browser/htmlContentRenderer*/,71/*vs/platform/opener/common/opener*/,2/*vs/editor/common/core/range*/,12/*vs/editor/common/core/position*/,17/*vs/editor/common/modes*/,122/*vs/editor/common/modes/textToHtmlTokenizer*/,462/*vs/editor/contrib/hover/common/hover*/,195/*vs/editor/contrib/hover/browser/hoverOperation*/,196/*vs/editor/contrib/hover/browser/hoverWidgets*/,133/*vs/base/common/htmlContent*/,34/*vs/editor/common/model/textModelWithDecorations*/,242/*vs/editor/contrib/colorPicker/browser/colorPickerModel*/,245/*vs/editor/contrib/colorPicker/browser/colorPickerWidget*/,246/*vs/editor/contrib/colorPicker/common/color*/,247/*vs/editor/contrib/colorPicker/common/colorFormatter*/,32/*vs/base/common/color*/,3/*vs/base/common/lifecycle*/]), function (require, exports, nls, uri_1, errors_1, dom, winjs_base_1, htmlContentRenderer_1, opener_1, range_1, position_1, modes_1, textToHtmlTokenizer_1, hover_1, hoverOperation_1, hoverWidgets_1, htmlContent_1, textModelWithDecorations_1, colorPickerModel_1, colorPickerWidget_1, color_1, colorFormatter_1, color_2, lifecycle) {
    /*---------------------------------------------------------------------------------------------
     *  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 $ = dom.$;
    var ColorHover = (function () {
        function ColorHover(range, color, format, availableFormats) {
            this.range = range;
            this.color = color;
            this.format = format;
            this.availableFormats = availableFormats;
        }
        return ColorHover;
    }());
    var ModesContentComputer = (function () {
        function ModesContentComputer(editor) {
            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 () {
            var model = this._editor.getModel();
            if (!modes_1.HoverProviderRegistry.has(model)) {
                return winjs_base_1.TPromise.as(null);
            }
            return hover_1.getHover(model, new position_1.Position(this._range.startLineNumber, this._range.startColumn));
        };
        ModesContentComputer.prototype.computeSync = function () {
            var _this = this;
            var lineNumber = this._range.startLineNumber;
            if (lineNumber > this._editor.getModel().getLineCount()) {
                // Illegal line number => no results
                return [];
            }
            var hasHoverContent = function (contents) {
                return contents && (!Array.isArray(contents) || contents.length > 0);
            };
            var maxColumn = this._editor.getModel().getLineMaxColumn(lineNumber);
            var lineDecorations = this._editor.getLineDecorations(lineNumber);
            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 > _this._range.startColumn || _this._range.endColumn > endColumn) {
                    return null;
                }
                var range = new range_1.Range(_this._range.startLineNumber, startColumn, _this._range.startLineNumber, endColumn);
                // TOOD@Joao
                var options = d.options;
                var extraOptions = options && options.extraOptions;
                if (color_1.isColorDecorationOptions(extraOptions)) {
                    var color = extraOptions.color, format = extraOptions.format, availableFormats = extraOptions.availableFormats;
                    return new ColorHover(range, color, format, availableFormats);
                }
                else {
                    if (!hasHoverContent(d.options.hoverMessage)) {
                        return null;
                    }
                    var contents = void 0;
                    if (d.options.hoverMessage) {
                        if (Array.isArray(d.options.hoverMessage)) {
                            contents = d.options.hoverMessage.slice();
                        }
                        else {
                            contents = [d.options.hoverMessage];
                        }
                    }
                    return { contents: contents, range: range };
                }
            });
            return result.filter(function (d) { return !!d; });
        };
        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) {
                        return -1;
                    }
                    else if (b instanceof ColorHover) {
                        return 1;
                    }
                    return 0;
                }));
            }
            else {
                this._result = this._result.concat(result);
            }
        };
        ModesContentComputer.prototype.getResult = function () {
            return this._result.slice(0);
        };
        ModesContentComputer.prototype.getResultWithLoadingMessage = function () {
            return this._result.slice(0).concat([this._getLoadingMessage()]);
        };
        ModesContentComputer.prototype._getLoadingMessage = function () {
            return {
                range: this._range,
                contents: [htmlContent_1.textToMarkedString(nls.localize(0, null))]
            };
        };
        return ModesContentComputer;
    }());
    var ModesContentHoverWidget = (function (_super) {
        __extends(ModesContentHoverWidget, _super);
        function ModesContentHoverWidget(editor, openerService, modeService) {
            var _this = _super.call(this, ModesContentHoverWidget.ID, editor) || this;
            _this._computer = new ModesContentComputer(_this._editor);
            _this._highlightDecorations = [];
            _this._isChangingDecorations = false;
            _this._openerService = openerService || opener_1.NullOpenerService;
            _this._modeService = modeService;
            _this._hoverOperation = new hoverOperation_1.HoverOperation(_this._computer, function (result) { return _this._withResult(result, true); }, null, function (result) { return _this._withResult(result, false); });
            _this.toDispose = [];
            _this.toDispose.push(dom.addStandardDisposableListener(_this.getDomNode(), dom.EventType.FOCUS, function () {
                if (_this._colorPicker) {
                    dom.addClass(_this.getDomNode(), 'colorpicker-hover');
                }
            }));
            _this.toDispose.push(dom.addStandardDisposableListener(_this.getDomNode(), dom.EventType.BLUR, function () {
                dom.removeClass(_this.getDomNode(), 'colorpicker-hover');
            }));
            return _this;
        }
        ModesContentHoverWidget.prototype.dispose = function () {
            this._hoverOperation.cancel();
            if (this._colorPicker) {
                this._colorPicker.dispose();
            }
            this.toDispose = lifecycle.dispose(this.toDispose);
            _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) {
                    this._hoverOperation.start();
                }
            }
        };
        ModesContentHoverWidget.prototype.startShowingAt = function (range, 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.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.startColumn <= range.startColumn && rng.endColumn >= range.endColumn) {
                            filteredMessages.push(msg);
                        }
                    }
                    if (filteredMessages.length > 0) {
                        this._renderMessages(range, filteredMessages);
                    }
                    else {
                        this.hide();
                    }
                }
            }
            this._lastRange = range;
            this._computer.setRange(range);
            this._shouldFocus = focus;
            this._hoverOperation.start();
        };
        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._colorPicker = null;
            if (this._colorPicker) {
                this._colorPicker.dispose();
            }
        };
        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;
            // update column from which to show
            var renderColumn = Number.MAX_VALUE, highlightRange = messages[0].range, fragment = document.createDocumentFragment();
            messages.forEach(function (msg) {
                if (!msg.range) {
                    return;
                }
                renderColumn = Math.min(renderColumn, msg.range.startColumn);
                highlightRange = range_1.Range.plusRange(highlightRange, msg.range);
                if (!(msg instanceof ColorHover)) {
                    msg.contents
                        .filter(function (contents) { return !!contents; })
                        .forEach(function (contents) {
                        var renderedContents = htmlContentRenderer_1.renderMarkedString(contents, {
                            actionCallback: function (content) {
                                _this._openerService.open(uri_1.default.parse(content)).then(void 0, errors_1.onUnexpectedError);
                            },
                            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 = languageAlias
                                    ? _this._modeService.getModeIdForLanguageName(languageAlias)
                                    : _this._editor.getModel().getLanguageIdentifier().language;
                                return _this._modeService.getOrCreateMode(modeId).then(function (_) {
                                    return textToHtmlTokenizer_1.tokenizeToString(value, modeId);
                                });
                            }
                        });
                        fragment.appendChild($('div.hover-row', null, renderedContents));
                    });
                }
                else {
                    var opaqueFormatter = void 0, transparentFormatter = void 0;
                    if (typeof msg.format === 'string') {
                        opaqueFormatter = new colorFormatter_1.ColorFormatter(msg.format);
                    }
                    else {
                        opaqueFormatter = new colorFormatter_1.ColorFormatter(msg.format.opaque);
                        transparentFormatter = new colorFormatter_1.ColorFormatter(msg.format.transparent);
                    }
                    var availableFormatters_1 = [];
                    if (msg.availableFormats) {
                        msg.availableFormats.forEach(function (format) {
                            var colorPickerFormatter;
                            if (typeof format === 'string') {
                                colorPickerFormatter = new colorFormatter_1.ColorFormatter(format);
                            }
                            else {
                                colorPickerFormatter = {
                                    opaqueFormatter: new colorFormatter_1.ColorFormatter(format.opaque),
                                    transparentFormatter: new colorFormatter_1.ColorFormatter(format.transparent)
                                };
                            }
                            availableFormatters_1.push(colorPickerFormatter);
                        });
                    }
                    var _a = msg.color, red = _a.red, green = _a.green, blue = _a.blue, alpha = _a.alpha;
                    var rgba = new color_2.RGBA(red * 255, green * 255, blue * 255, alpha * 255);
                    var color = color_2.Color.fromRGBA(rgba);
                    var model = new colorPickerModel_1.ColorPickerModel(rgba.toString(), color, opaqueFormatter, transparentFormatter, availableFormatters_1, _this._editor.getModel(), msg.range);
                    var widget = _this._register(new colorPickerWidget_1.ColorPickerWidget(model, _this._editor));
                    model.widget = widget;
                    _this._colorPicker = widget;
                    fragment.appendChild(widget.getDomNode());
                }
            });
            // show
            this.showAt(new position_1.Position(renderRange.startLineNumber, renderColumn), this._shouldFocus);
            this.updateContents(fragment);
            if (this._colorPicker) {
                this._colorPicker.layout();
                this._colorPicker.layoutSaturationBox();
            }
            this._isChangingDecorations = true;
            this._highlightDecorations = this._editor.deltaDecorations(this._highlightDecorations, [{
                    range: highlightRange,
                    options: ModesContentHoverWidget._DECORATION_OPTIONS
                }]);
            this._isChangingDecorations = false;
        };
        ModesContentHoverWidget.ID = 'editor.contrib.modesContentHoverWidget';
        ModesContentHoverWidget._DECORATION_OPTIONS = textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'hoverHighlight'
        });
        return ModesContentHoverWidget;
    }(hoverWidgets_1.ContentHoverWidget));
    exports.ModesContentHoverWidget = ModesContentHoverWidget;
});

















define(__m[464/*vs/editor/contrib/linesOperations/common/linesOperations*/], __M([1/*require*/,0/*exports*/,357/*vs/nls!vs/editor/contrib/linesOperations/common/linesOperations*/,40/*vs/base/common/keyCodes*/,266/*vs/editor/contrib/linesOperations/common/sortLinesCommand*/,59/*vs/editor/common/core/editOperation*/,435/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/,21/*vs/editor/common/editorContextKeys*/,73/*vs/editor/common/commands/replaceCommand*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,13/*vs/editor/common/editorCommonExtensions*/,264/*vs/editor/contrib/linesOperations/common/copyLinesCommand*/,265/*vs/editor/contrib/linesOperations/common/deleteLinesCommand*/,319/*vs/editor/contrib/linesOperations/common/moveLinesCommand*/,119/*vs/editor/common/controller/cursorTypeOperations*/,134/*vs/editor/common/controller/coreCommands*/]), function (require, exports, nls, keyCodes_1, sortLinesCommand_1, editOperation_1, trimTrailingWhitespaceCommand_1, editorContextKeys_1, replaceCommand_1, range_1, selection_1, editorCommonExtensions_1, copyLinesCommand_1, deleteLinesCommand_1, moveLinesCommand_1, cursorTypeOperations_1, coreCommands_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    // copy lines
    var AbstractCopyLinesAction = (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; i < selections.length; i++) {
                commands.push(new copyLinesCommand_1.CopyLinesCommand(selections[i], this.down));
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        };
        return AbstractCopyLinesAction;
    }(editorCommonExtensions_1.EditorAction));
    var CopyLinesUpAction = (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.textFocus,
                    primary: 512 /* Alt */ | 1024 /* Shift */ | 16 /* UpArrow */,
                    linux: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 1024 /* Shift */ | 16 /* UpArrow */ }
                }
            }) || this;
        }
        CopyLinesUpAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], CopyLinesUpAction);
        return CopyLinesUpAction;
    }(AbstractCopyLinesAction));
    var CopyLinesDownAction = (function (_super) {
        __extends(CopyLinesDownAction, _super);
        function CopyLinesDownAction() {
            return _super.call(this, true, {
                id: 'editor.action.copyLinesDownAction',
                label: nls.localize(1, null),
                alias: 'Copy Line Down',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 512 /* Alt */ | 1024 /* Shift */ | 18 /* DownArrow */,
                    linux: { primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 1024 /* Shift */ | 18 /* DownArrow */ }
                }
            }) || this;
        }
        CopyLinesDownAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], CopyLinesDownAction);
        return CopyLinesDownAction;
    }(AbstractCopyLinesAction));
    // move lines
    var AbstractMoveLinesAction = (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; i < selections.length; i++) {
                commands.push(new moveLinesCommand_1.MoveLinesCommand(selections[i], this.down, autoIndent));
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        };
        return AbstractMoveLinesAction;
    }(editorCommonExtensions_1.EditorAction));
    var MoveLinesUpAction = (function (_super) {
        __extends(MoveLinesUpAction, _super);
        function MoveLinesUpAction() {
            return _super.call(this, false, {
                id: 'editor.action.moveLinesUpAction',
                label: nls.localize(2, null),
                alias: 'Move Line Up',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 512 /* Alt */ | 16 /* UpArrow */,
                    linux: { primary: 512 /* Alt */ | 16 /* UpArrow */ }
                }
            }) || this;
        }
        MoveLinesUpAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], MoveLinesUpAction);
        return MoveLinesUpAction;
    }(AbstractMoveLinesAction));
    var MoveLinesDownAction = (function (_super) {
        __extends(MoveLinesDownAction, _super);
        function MoveLinesDownAction() {
            return _super.call(this, true, {
                id: 'editor.action.moveLinesDownAction',
                label: nls.localize(3, null),
                alias: 'Move Line Down',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 512 /* Alt */ | 18 /* DownArrow */,
                    linux: { primary: 512 /* Alt */ | 18 /* DownArrow */ }
                }
            }) || this;
        }
        MoveLinesDownAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], MoveLinesDownAction);
        return MoveLinesDownAction;
    }(AbstractMoveLinesAction));
    var AbstractSortLinesAction = (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) {
            if (!sortLinesCommand_1.SortLinesCommand.canRun(editor.getModel(), editor.getSelection(), this.descending)) {
                return;
            }
            var command = new sortLinesCommand_1.SortLinesCommand(editor.getSelection(), this.descending);
            editor.pushUndoStop();
            editor.executeCommands(this.id, [command]);
            editor.pushUndoStop();
        };
        return AbstractSortLinesAction;
    }(editorCommonExtensions_1.EditorAction));
    var SortLinesAscendingAction = (function (_super) {
        __extends(SortLinesAscendingAction, _super);
        function SortLinesAscendingAction() {
            return _super.call(this, false, {
                id: 'editor.action.sortLinesAscending',
                label: nls.localize(4, null),
                alias: 'Sort Lines Ascending',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            }) || this;
        }
        SortLinesAscendingAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], SortLinesAscendingAction);
        return SortLinesAscendingAction;
    }(AbstractSortLinesAction));
    var SortLinesDescendingAction = (function (_super) {
        __extends(SortLinesDescendingAction, _super);
        function SortLinesDescendingAction() {
            return _super.call(this, true, {
                id: 'editor.action.sortLinesDescending',
                label: nls.localize(5, null),
                alias: 'Sort Lines Descending',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            }) || this;
        }
        SortLinesDescendingAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], SortLinesDescendingAction);
        return SortLinesDescendingAction;
    }(AbstractSortLinesAction));
    var TrimTrailingWhitespaceAction = (function (_super) {
        __extends(TrimTrailingWhitespaceAction, _super);
        function TrimTrailingWhitespaceAction() {
            return _super.call(this, {
                id: TrimTrailingWhitespaceAction_1.ID,
                label: nls.localize(6, null),
                alias: 'Trim Trailing Whitespace',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 54 /* KEY_X */)
                }
            }) || this;
        }
        TrimTrailingWhitespaceAction_1 = TrimTrailingWhitespaceAction;
        TrimTrailingWhitespaceAction.prototype.run = function (accessor, editor) {
            var command = new trimTrailingWhitespaceCommand_1.TrimTrailingWhitespaceCommand(editor.getSelection());
            editor.pushUndoStop();
            editor.executeCommands(this.id, [command]);
            editor.pushUndoStop();
        };
        TrimTrailingWhitespaceAction.ID = 'editor.action.trimTrailingWhitespace';
        TrimTrailingWhitespaceAction = TrimTrailingWhitespaceAction_1 = __decorate([
            editorCommonExtensions_1.editorAction
        ], TrimTrailingWhitespaceAction);
        return TrimTrailingWhitespaceAction;
        var TrimTrailingWhitespaceAction_1;
    }(editorCommonExtensions_1.EditorAction));
    exports.TrimTrailingWhitespaceAction = TrimTrailingWhitespaceAction;
    var AbstractRemoveLinesAction = (function (_super) {
        __extends(AbstractRemoveLinesAction, _super);
        function AbstractRemoveLinesAction() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        AbstractRemoveLinesAction.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,
                    endLineNumber: endLineNumber,
                    positionColumn: s.positionColumn
                };
            });
            // Sort delete operations
            operations.sort(function (a, b) {
                return a.startLineNumber - b.startLineNumber;
            });
            // Merge delete operations on consecutive lines
            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 AbstractRemoveLinesAction;
    }(editorCommonExtensions_1.EditorAction));
    var DeleteLinesAction = (function (_super) {
        __extends(DeleteLinesAction, _super);
        function DeleteLinesAction() {
            return _super.call(this, {
                id: 'editor.action.deleteLines',
                label: nls.localize(7, null),
                alias: 'Delete Line',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 41 /* KEY_K */
                }
            }) || this;
        }
        DeleteLinesAction.prototype.run = function (accessor, editor) {
            var ops = this._getLinesToRemove(editor);
            // Finally, construct the delete lines commands
            var commands = ops.map(function (op) {
                return new deleteLinesCommand_1.DeleteLinesCommand(op.startLineNumber, op.endLineNumber, op.positionColumn);
            });
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        };
        DeleteLinesAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], DeleteLinesAction);
        return DeleteLinesAction;
    }(AbstractRemoveLinesAction));
    var IndentLinesAction = (function (_super) {
        __extends(IndentLinesAction, _super);
        function IndentLinesAction() {
            return _super.call(this, {
                id: 'editor.action.indentLines',
                label: nls.localize(8, null),
                alias: 'Indent Line',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 89 /* US_CLOSE_SQUARE_BRACKET */
                }
            }) || this;
        }
        IndentLinesAction.prototype.run = function (accessor, editor) {
            editor.pushUndoStop();
            editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.indent(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections()));
            editor.pushUndoStop();
        };
        IndentLinesAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], IndentLinesAction);
        return IndentLinesAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.IndentLinesAction = IndentLinesAction;
    var OutdentLinesAction = (function (_super) {
        __extends(OutdentLinesAction, _super);
        function OutdentLinesAction() {
            return _super.call(this, {
                id: 'editor.action.outdentLines',
                label: nls.localize(9, null),
                alias: 'Outdent Line',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 87 /* US_OPEN_SQUARE_BRACKET */
                }
            }) || this;
        }
        OutdentLinesAction.prototype.run = function (accessor, editor) {
            coreCommands_1.CoreEditingCommands.Outdent.runEditorCommand(null, editor, null);
        };
        OutdentLinesAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], OutdentLinesAction);
        return OutdentLinesAction;
    }(editorCommonExtensions_1.EditorAction));
    var InsertLineBeforeAction = (function (_super) {
        __extends(InsertLineBeforeAction, _super);
        function InsertLineBeforeAction() {
            return _super.call(this, {
                id: 'editor.action.insertLineBefore',
                label: nls.localize(10, null),
                alias: 'Insert Line Above',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 3 /* Enter */
                }
            }) || this;
        }
        InsertLineBeforeAction.prototype.run = function (accessor, editor) {
            editor.pushUndoStop();
            editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.lineInsertBefore(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections()));
        };
        InsertLineBeforeAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], InsertLineBeforeAction);
        return InsertLineBeforeAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.InsertLineBeforeAction = InsertLineBeforeAction;
    var InsertLineAfterAction = (function (_super) {
        __extends(InsertLineAfterAction, _super);
        function InsertLineAfterAction() {
            return _super.call(this, {
                id: 'editor.action.insertLineAfter',
                label: nls.localize(11, null),
                alias: 'Insert Line Below',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 3 /* Enter */
                }
            }) || this;
        }
        InsertLineAfterAction.prototype.run = function (accessor, editor) {
            editor.pushUndoStop();
            editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.lineInsertAfter(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections()));
        };
        InsertLineAfterAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], InsertLineAfterAction);
        return InsertLineAfterAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.InsertLineAfterAction = InsertLineAfterAction;
    var AbstractDeleteAllToBoundaryAction = (function (_super) {
        __extends(AbstractDeleteAllToBoundaryAction, _super);
        function AbstractDeleteAllToBoundaryAction() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        AbstractDeleteAllToBoundaryAction.prototype.run = function (accessor, editor) {
            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) {
                endCursorState.push(new selection_1.Selection(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn));
                return editOperation_1.EditOperation.replace(range, '');
            });
            editor.executeEdits(this.id, edits, endCursorState);
        };
        return AbstractDeleteAllToBoundaryAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.AbstractDeleteAllToBoundaryAction = AbstractDeleteAllToBoundaryAction;
    var DeleteAllLeftAction = (function (_super) {
        __extends(DeleteAllLeftAction, _super);
        function DeleteAllLeftAction() {
            return _super.call(this, {
                id: 'deleteAllLeft',
                label: nls.localize(12, null),
                alias: 'Delete All Left',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: null,
                    mac: { primary: 2048 /* CtrlCmd */ | 1 /* Backspace */ }
                }
            }) || this;
        }
        DeleteAllLeftAction.prototype._getEndCursorState = function (primaryCursor, rangesToDelete) {
            var endPrimaryCursor;
            var endCursorState = [];
            for (var i = 0, len = rangesToDelete.length; i < len; i++) {
                var range = rangesToDelete[i];
                var endCursor = new selection_1.Selection(rangesToDelete[i].startLineNumber, rangesToDelete[i].startColumn, rangesToDelete[i].startLineNumber, rangesToDelete[i].startColumn);
                if (range.intersectRanges(primaryCursor)) {
                    endPrimaryCursor = endCursor;
                }
                else {
                    endCursorState.push(endCursor);
                }
            }
            if (endPrimaryCursor) {
                endCursorState.unshift(endPrimaryCursor);
            }
            return endCursorState;
        };
        DeleteAllLeftAction.prototype._getRangesToDelete = function (editor) {
            var rangesToDelete = editor.getSelections();
            rangesToDelete.sort(range_1.Range.compareRangesUsingStarts);
            rangesToDelete = rangesToDelete.map(function (selection) {
                if (selection.isEmpty()) {
                    return new range_1.Range(selection.startLineNumber, 1, selection.startLineNumber, selection.startColumn);
                }
                else {
                    return selection;
                }
            });
            return rangesToDelete;
        };
        DeleteAllLeftAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], DeleteAllLeftAction);
        return DeleteAllLeftAction;
    }(AbstractDeleteAllToBoundaryAction));
    exports.DeleteAllLeftAction = DeleteAllLeftAction;
    var DeleteAllRightAction = (function (_super) {
        __extends(DeleteAllRightAction, _super);
        function DeleteAllRightAction() {
            return _super.call(this, {
                id: 'deleteAllRight',
                label: nls.localize(13, null),
                alias: 'Delete All Right',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: null,
                    mac: { primary: 256 /* WinCtrl */ | 41 /* KEY_K */, secondary: [2048 /* CtrlCmd */ | 20 /* Delete */] }
                }
            }) || this;
        }
        DeleteAllRightAction.prototype._getEndCursorState = function (primaryCursor, rangesToDelete) {
            var endPrimaryCursor;
            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();
            var rangesToDelete = editor.getSelections().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;
        };
        DeleteAllRightAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], DeleteAllRightAction);
        return DeleteAllRightAction;
    }(AbstractDeleteAllToBoundaryAction));
    exports.DeleteAllRightAction = DeleteAllRightAction;
    var JoinLinesAction = (function (_super) {
        __extends(JoinLinesAction, _super);
        function JoinLinesAction() {
            return _super.call(this, {
                id: 'editor.action.joinLines',
                label: nls.localize(14, null),
                alias: 'Join Lines',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 0,
                    mac: { primary: 256 /* WinCtrl */ | 40 /* KEY_J */ }
                }
            }) || this;
        }
        JoinLinesAction.prototype.run = function (accessor, editor) {
            var selections = editor.getSelections();
            var primaryCursor = editor.getSelection();
            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();
            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 endLineNumber = void 0, endColumn = void 0, columnDeltaOffset = 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.executeEdits(this.id, edits, endCursorState);
        };
        JoinLinesAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], JoinLinesAction);
        return JoinLinesAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.JoinLinesAction = JoinLinesAction;
    var TransposeAction = (function (_super) {
        __extends(TransposeAction, _super);
        function TransposeAction() {
            return _super.call(this, {
                id: 'editor.action.transpose',
                label: nls.localize(15, null),
                alias: 'Transpose characters around the cursor',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            }) || this;
        }
        TransposeAction.prototype.run = function (accessor, editor) {
            var selections = editor.getSelections();
            var model = editor.getModel();
            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();
        };
        TransposeAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], TransposeAction);
        return TransposeAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.TransposeAction = TransposeAction;
    var AbstractCaseAction = (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();
            var model = editor.getModel();
            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), 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), selection));
                }
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        };
        return AbstractCaseAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.AbstractCaseAction = AbstractCaseAction;
    var UpperCaseAction = (function (_super) {
        __extends(UpperCaseAction, _super);
        function UpperCaseAction() {
            return _super.call(this, {
                id: 'editor.action.transformToUppercase',
                label: nls.localize(16, null),
                alias: 'Transform to Uppercase',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            }) || this;
        }
        UpperCaseAction.prototype._modifyText = function (text) {
            return text.toLocaleUpperCase();
        };
        UpperCaseAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], UpperCaseAction);
        return UpperCaseAction;
    }(AbstractCaseAction));
    exports.UpperCaseAction = UpperCaseAction;
    var LowerCaseAction = (function (_super) {
        __extends(LowerCaseAction, _super);
        function LowerCaseAction() {
            return _super.call(this, {
                id: 'editor.action.transformToLowercase',
                label: nls.localize(17, null),
                alias: 'Transform to Lowercase',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            }) || this;
        }
        LowerCaseAction.prototype._modifyText = function (text) {
            return text.toLocaleLowerCase();
        };
        LowerCaseAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], LowerCaseAction);
        return LowerCaseAction;
    }(AbstractCaseAction));
    exports.LowerCaseAction = LowerCaseAction;
});

















define(__m[465/*vs/editor/contrib/multicursor/common/multicursor*/], __M([1/*require*/,0/*exports*/,359/*vs/nls!vs/editor/contrib/multicursor/common/multicursor*/,21/*vs/editor/common/editorContextKeys*/,13/*vs/editor/common/editorCommonExtensions*/,22/*vs/editor/common/core/selection*/,54/*vs/editor/common/controller/cursorEvents*/,173/*vs/editor/common/controller/cursorMoveCommands*/,39/*vs/editor/common/controller/cursorCommon*/]), function (require, exports, nls, editorContextKeys_1, editorCommonExtensions_1, selection_1, cursorEvents_1, cursorMoveCommands_1, cursorCommon_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var InsertCursorAbove = (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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 16 /* UpArrow */,
                    linux: {
                        primary: 1024 /* Shift */ | 512 /* Alt */ | 16 /* UpArrow */,
                        secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 16 /* UpArrow */]
                    }
                }
            }) || this;
        }
        InsertCursorAbove.prototype.run = function (accessor, editor, args) {
            var cursors = editor._getCursors();
            var context = cursors.context;
            if (context.config.readOnly) {
                return;
            }
            context.model.pushStackElement();
            cursors.setStates(args.source, cursorEvents_1.CursorChangeReason.Explicit, cursorCommon_1.CursorState.ensureInEditableRange(context, cursorMoveCommands_1.CursorMoveCommands.addCursorUp(context, cursors.getAll())));
            cursors.reveal(true, 1 /* TopMost */);
        };
        InsertCursorAbove = __decorate([
            editorCommonExtensions_1.editorAction
        ], InsertCursorAbove);
        return InsertCursorAbove;
    }(editorCommonExtensions_1.EditorAction));
    exports.InsertCursorAbove = InsertCursorAbove;
    var InsertCursorBelow = (function (_super) {
        __extends(InsertCursorBelow, _super);
        function InsertCursorBelow() {
            return _super.call(this, {
                id: 'editor.action.insertCursorBelow',
                label: nls.localize(1, null),
                alias: 'Add Cursor Below',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 18 /* DownArrow */,
                    linux: {
                        primary: 1024 /* Shift */ | 512 /* Alt */ | 18 /* DownArrow */,
                        secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 18 /* DownArrow */]
                    }
                }
            }) || this;
        }
        InsertCursorBelow.prototype.run = function (accessor, editor, args) {
            var cursors = editor._getCursors();
            var context = cursors.context;
            if (context.config.readOnly) {
                return;
            }
            context.model.pushStackElement();
            cursors.setStates(args.source, cursorEvents_1.CursorChangeReason.Explicit, cursorCommon_1.CursorState.ensureInEditableRange(context, cursorMoveCommands_1.CursorMoveCommands.addCursorDown(context, cursors.getAll())));
            cursors.reveal(true, 2 /* BottomMost */);
        };
        InsertCursorBelow = __decorate([
            editorCommonExtensions_1.editorAction
        ], InsertCursorBelow);
        return InsertCursorBelow;
    }(editorCommonExtensions_1.EditorAction));
    exports.InsertCursorBelow = InsertCursorBelow;
    var InsertCursorAtEndOfEachLineSelected = (function (_super) {
        __extends(InsertCursorAtEndOfEachLineSelected, _super);
        function InsertCursorAtEndOfEachLineSelected() {
            return _super.call(this, {
                id: 'editor.action.insertCursorAtEndOfEachLineSelected',
                label: nls.localize(2, null),
                alias: 'Add Cursors to Line Ends',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 1024 /* Shift */ | 512 /* Alt */ | 39 /* KEY_I */
                }
            }) || this;
        }
        InsertCursorAtEndOfEachLineSelected.prototype.getCursorsForSelection = function (selection, editor) {
            if (selection.isEmpty()) {
                return [];
            }
            var model = editor.getModel();
            var newSelections = [];
            for (var i = selection.startLineNumber; i < selection.endLineNumber; i++) {
                var currentLineMaxColumn = model.getLineMaxColumn(i);
                newSelections.push(new selection_1.Selection(i, currentLineMaxColumn, i, currentLineMaxColumn));
            }
            if (selection.endColumn > 1) {
                newSelections.push(new selection_1.Selection(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn));
            }
            return newSelections;
        };
        InsertCursorAtEndOfEachLineSelected.prototype.run = function (accessor, editor) {
            var _this = this;
            var selections = editor.getSelections();
            var newSelections = selections
                .map(function (selection) { return _this.getCursorsForSelection(selection, editor); })
                .reduce(function (prev, curr) { return prev.concat(curr); });
            if (newSelections.length > 0) {
                editor.setSelections(newSelections);
            }
        };
        InsertCursorAtEndOfEachLineSelected = __decorate([
            editorCommonExtensions_1.editorAction
        ], InsertCursorAtEndOfEachLineSelected);
        return InsertCursorAtEndOfEachLineSelected;
    }(editorCommonExtensions_1.EditorAction));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[178/*vs/editor/contrib/parameterHints/common/parameterHints*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,13/*vs/editor/common/editorCommonExtensions*/,17/*vs/editor/common/modes*/,18/*vs/base/common/async*/,19/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, errors_1, editorCommonExtensions_1, modes_1, async_1, contextkey_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) {
        var supports = modes_1.SignatureHelpProviderRegistry.ordered(model);
        var result;
        return async_1.sequence(supports.map(function (support) { return function () {
            if (result) {
                // stop when there is a result
                return undefined;
            }
            return async_1.asWinJsPromise(function (token) { return support.provideSignatureHelp(model, position, token); }).then(function (thisResult) {
                result = thisResult;
            }, errors_1.onUnexpectedExternalError);
        }; })).then(function () { return result; });
    }
    exports.provideSignatureHelp = provideSignatureHelp;
    editorCommonExtensions_1.CommonEditorRegistry.registerDefaultLanguageCommand('_executeSignatureHelpProvider', provideSignatureHelp);
});

define(__m[467/*vs/editor/contrib/quickFix/browser/quickFix*/], __M([1/*require*/,0/*exports*/,24/*vs/base/common/uri*/,2/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,18/*vs/base/common/async*/,7/*vs/base/common/winjs.base*/,10/*vs/base/common/errors*/,56/*vs/editor/common/services/modelService*/,13/*vs/editor/common/editorCommonExtensions*/]), function (require, exports, uri_1, range_1, modes_1, async_1, winjs_base_1, errors_1, modelService_1, editorCommonExtensions_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function getCodeActions(model, range) {
        var allResults = [];
        var promises = modes_1.CodeActionProviderRegistry.all(model).map(function (support) {
            return async_1.asWinJsPromise(function (token) { return support.provideCodeActions(model, range, token); }).then(function (result) {
                if (Array.isArray(result)) {
                    for (var _i = 0, result_1 = result; _i < result_1.length; _i++) {
                        var quickFix = result_1[_i];
                        if (quickFix) {
                            allResults.push(quickFix);
                        }
                    }
                }
            }, function (err) {
                errors_1.onUnexpectedExternalError(err);
            });
        });
        return winjs_base_1.TPromise.join(promises).then(function () { return allResults; });
    }
    exports.getCodeActions = getCodeActions;
    editorCommonExtensions_1.CommonEditorRegistry.registerLanguageCommand('_executeCodeActionProvider', function (accessor, args) {
        var resource = args.resource, range = args.range;
        if (!(resource instanceof uri_1.default) || !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));
    });
});

define(__m[468/*vs/editor/contrib/quickFix/browser/quickFixModel*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/event*/,3/*vs/base/common/lifecycle*/,2/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,467/*vs/editor/contrib/quickFix/browser/quickFix*/]), function (require, exports, event_1, lifecycle_1, range_1, modes_1, quickFix_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var QuickFixOracle = (function () {
        function QuickFixOracle(_editor, _markerService, _signalChange, delay) {
            if (delay === void 0) { delay = 250; }
            var _this = this;
            this._editor = _editor;
            this._markerService = _markerService;
            this._signalChange = _signalChange;
            this._disposables = [];
            this._disposables.push(event_1.debounceEvent(this._markerService.onMarkerChanged, function (last, cur) { return last ? last.concat(cur) : cur; }, delay / 2)(function (e) { return _this._onMarkerChanges(e); }), event_1.debounceEvent(this._editor.onDidChangeCursorPosition, function (last) { return last; }, delay)(function (e) { return _this._onCursorChange(); }));
        }
        QuickFixOracle.prototype.dispose = function () {
            this._disposables = lifecycle_1.dispose(this._disposables);
        };
        QuickFixOracle.prototype.trigger = function (type) {
            // get selection from marker or current word
            // unless the selection is non-empty and manually
            // requesting code actions
            var selection = this._editor.getSelection();
            var range = this._getActiveMarkerOrWordRange();
            if (type === 'manual' && !selection.isEmpty()) {
                range = selection;
            }
            // empty selection somewhere in nowhere
            if (!range) {
                range = selection;
            }
            this._signalChange({
                type: type,
                range: range,
                position: this._editor.getPosition(),
                fixes: range && quickFix_1.getCodeActions(this._editor.getModel(), this._editor.getModel().validateRange(range))
            });
        };
        QuickFixOracle.prototype._onMarkerChanges = function (resources) {
            var uri = this._editor.getModel().uri;
            for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
                var resource = resources_1[_i];
                if (resource.toString() === uri.toString()) {
                    this._currentRange = undefined;
                    this._onCursorChange();
                    return;
                }
            }
        };
        QuickFixOracle.prototype._onCursorChange = function () {
            var range = this._getActiveMarkerOrWordRange();
            if (!range_1.Range.equalsRange(this._currentRange, range)) {
                this._currentRange = range;
                this._signalChange({
                    type: 'auto',
                    range: range,
                    position: this._editor.getPosition(),
                    fixes: range && quickFix_1.getCodeActions(this._editor.getModel(), this._editor.getModel().validateRange(range))
                });
            }
        };
        QuickFixOracle.prototype._getActiveMarkerOrWordRange = function () {
            var selection = this._editor.getSelection();
            var model = this._editor.getModel();
            // (1) return marker that contains a (empty/non-empty) selection
            for (var _i = 0, _a = this._markerService.read({ resource: model.uri }); _i < _a.length; _i++) {
                var marker = _a[_i];
                var range = range_1.Range.lift(marker);
                if (range.containsRange(selection)) {
                    return range;
                }
            }
            // (2) return range of current word
            if (selection.isEmpty()) {
                var pos = selection.getStartPosition();
                var info = model.getWordAtPosition(pos);
                if (info) {
                    return new range_1.Range(pos.lineNumber, info.startColumn, pos.lineNumber, info.endColumn);
                }
            }
            return undefined;
        };
        return QuickFixOracle;
    }());
    exports.QuickFixOracle = QuickFixOracle;
    var QuickFixModel = (function () {
        function QuickFixModel(editor, markerService) {
            var _this = this;
            this._onDidChangeFixes = new event_1.Emitter();
            this._disposables = [];
            this._editor = editor;
            this._markerService = markerService;
            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(this._update, this));
            this._update();
        }
        QuickFixModel.prototype.dispose = function () {
            this._disposables = lifecycle_1.dispose(this._disposables);
            lifecycle_1.dispose(this._quickFixOracle);
        };
        Object.defineProperty(QuickFixModel.prototype, "onDidChangeFixes", {
            get: function () {
                return this._onDidChangeFixes.event;
            },
            enumerable: true,
            configurable: true
        });
        QuickFixModel.prototype._update = function () {
            var _this = this;
            if (this._quickFixOracle) {
                this._quickFixOracle.dispose();
                this._quickFixOracle = undefined;
                this._onDidChangeFixes.fire(undefined);
            }
            if (this._editor.getModel()
                && modes_1.CodeActionProviderRegistry.has(this._editor.getModel())
                && !this._editor.getConfiguration().readOnly) {
                this._quickFixOracle = new QuickFixOracle(this._editor, this._markerService, function (p) { return _this._onDidChangeFixes.fire(p); });
                this._quickFixOracle.trigger('auto');
            }
        };
        QuickFixModel.prototype.trigger = function (type) {
            if (this._quickFixOracle) {
                this._quickFixOracle.trigger(type);
            }
        };
        return QuickFixModel;
    }());
    exports.QuickFixModel = QuickFixModel;
});




















define(__m[469/*vs/editor/contrib/quickFix/browser/quickFixCommands*/], __M([1/*require*/,0/*exports*/,362/*vs/nls!vs/editor/contrib/quickFix/browser/quickFixCommands*/,3/*vs/base/common/lifecycle*/,31/*vs/platform/commands/common/commands*/,69/*vs/platform/contextview/browser/contextView*/,19/*vs/platform/contextkey/common/contextkey*/,46/*vs/platform/keybinding/common/keybinding*/,103/*vs/platform/markers/common/markers*/,21/*vs/editor/common/editorContextKeys*/,13/*vs/editor/common/editorCommonExtensions*/,30/*vs/editor/browser/editorBrowserExtensions*/,268/*vs/editor/contrib/quickFix/browser/quickFixWidget*/,267/*vs/editor/contrib/quickFix/browser/lightBulbWidget*/,468/*vs/editor/contrib/quickFix/browser/quickFixModel*/]), function (require, exports, nls, lifecycle_1, commands_1, contextView_1, contextkey_1, keybinding_1, markers_1, editorContextKeys_1, editorCommonExtensions_1, editorBrowserExtensions_1, quickFixWidget_1, lightBulbWidget_1, quickFixModel_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var QuickFixController = (function () {
        function QuickFixController(editor, markerService, contextKeyService, commandService, contextMenuService, _keybindingService) {
            var _this = this;
            this._keybindingService = _keybindingService;
            this._disposables = [];
            this._editor = editor;
            this._model = new quickFixModel_1.QuickFixModel(this._editor, markerService);
            this._quickFixContextMenu = new quickFixWidget_1.QuickFixContextMenu(editor, contextMenuService, commandService);
            this._lightBulbWidget = new lightBulbWidget_1.LightBulbWidget(editor);
            this._updateLightBulbTitle();
            this._disposables.push(this._quickFixContextMenu.onDidExecuteCodeAction(function (_) { return _this._model.trigger('auto'); }), this._lightBulbWidget.onClick(this._handleLightBulbSelect, this), this._model.onDidChangeFixes(function (e) { return _this._onQuickFixEvent(e); }), this._keybindingService.onDidUpdateKeybindings(this._updateLightBulbTitle, this));
        }
        QuickFixController_1 = QuickFixController;
        QuickFixController.get = function (editor) {
            return editor.getContribution(QuickFixController_1.ID);
        };
        QuickFixController.prototype.dispose = function () {
            this._model.dispose();
            lifecycle_1.dispose(this._disposables);
        };
        QuickFixController.prototype._onQuickFixEvent = function (e) {
            if (e && e.type === 'manual') {
                this._quickFixContextMenu.show(e.fixes, e.position);
            }
            else if (e && e.fixes) {
                // auto magically triggered
                // * update an existing list of code actions
                // * manage light bulb
                if (this._quickFixContextMenu.isVisible) {
                    this._quickFixContextMenu.show(e.fixes, e.position);
                }
                else {
                    this._lightBulbWidget.model = e;
                }
            }
            else {
                this._lightBulbWidget.hide();
            }
        };
        QuickFixController.prototype.getId = function () {
            return QuickFixController_1.ID;
        };
        QuickFixController.prototype._handleLightBulbSelect = function (coords) {
            this._quickFixContextMenu.show(this._lightBulbWidget.model.fixes, coords);
        };
        QuickFixController.prototype.triggerFromEditorSelection = function () {
            this._model.trigger('manual');
        };
        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.ID = 'editor.contrib.quickFixController';
        QuickFixController = QuickFixController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, markers_1.IMarkerService),
            __param(2, contextkey_1.IContextKeyService),
            __param(3, commands_1.ICommandService),
            __param(4, contextView_1.IContextMenuService),
            __param(5, keybinding_1.IKeybindingService)
        ], QuickFixController);
        return QuickFixController;
        var QuickFixController_1;
    }());
    exports.QuickFixController = QuickFixController;
    var QuickFixAction = (function (_super) {
        __extends(QuickFixAction, _super);
        function QuickFixAction() {
            return _super.call(this, {
                id: QuickFixAction_1.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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 84 /* US_DOT */
                }
            }) || this;
        }
        QuickFixAction_1 = QuickFixAction;
        QuickFixAction.prototype.run = function (accessor, editor) {
            var controller = QuickFixController.get(editor);
            if (controller) {
                controller.triggerFromEditorSelection();
            }
        };
        QuickFixAction.Id = 'editor.action.quickFix';
        QuickFixAction = QuickFixAction_1 = __decorate([
            editorCommonExtensions_1.editorAction
        ], QuickFixAction);
        return QuickFixAction;
        var QuickFixAction_1;
    }(editorCommonExtensions_1.EditorAction));
    exports.QuickFixAction = QuickFixAction;
});

/*---------------------------------------------------------------------------------------------
 *  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/quickOpen/common/quickOpen*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,24/*vs/base/common/uri*/,7/*vs/base/common/winjs.base*/,2/*vs/editor/common/core/range*/,13/*vs/editor/common/editorCommonExtensions*/,17/*vs/editor/common/modes*/,56/*vs/editor/common/services/modelService*/,18/*vs/base/common/async*/]), function (require, exports, errors_1, uri_1, winjs_base_1, range_1, editorCommonExtensions_1, modes_1, modelService_1, async_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function getDocumentSymbols(model) {
        var entries = [];
        var promises = modes_1.DocumentSymbolProviderRegistry.all(model).map(function (support) {
            return async_1.asWinJsPromise(function (token) {
                return support.provideDocumentSymbols(model, token);
            }).then(function (result) {
                if (Array.isArray(result)) {
                    entries.push.apply(entries, result);
                }
            }, function (err) {
                errors_1.onUnexpectedExternalError(err);
            });
        });
        return winjs_base_1.TPromise.join(promises).then(function () {
            var flatEntries = [];
            flatten(flatEntries, entries, '');
            flatEntries.sort(compareEntriesUsingStart);
            return {
                entries: flatEntries,
            };
        });
    }
    exports.getDocumentSymbols = getDocumentSymbols;
    function compareEntriesUsingStart(a, b) {
        return range_1.Range.compareRangesUsingStarts(range_1.Range.lift(a.location.range), range_1.Range.lift(b.location.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,
                location: entry.location,
                name: entry.name,
                containerName: entry.containerName || overrideContainerLabel
            });
        }
    }
    editorCommonExtensions_1.CommonEditorRegistry.registerLanguageCommand('_executeDocumentSymbolProvider', function (accessor, args) {
        var resource = args.resource;
        if (!(resource instanceof uri_1.default)) {
            throw errors_1.illegalArgument('resource');
        }
        var model = accessor.get(modelService_1.IModelService).getModel(resource);
        if (!model) {
            throw errors_1.illegalArgument('resource');
        }
        return getDocumentSymbols(model);
    });
});




















define(__m[471/*vs/editor/contrib/smartSelect/common/smartSelect*/], __M([1/*require*/,0/*exports*/,370/*vs/nls!vs/editor/contrib/smartSelect/common/smartSelect*/,33/*vs/base/common/arrays*/,7/*vs/base/common/winjs.base*/,16/*vs/platform/instantiation/common/instantiation*/,2/*vs/editor/common/core/range*/,21/*vs/editor/common/editorContextKeys*/,13/*vs/editor/common/editorCommonExtensions*/,398/*vs/editor/contrib/smartSelect/common/tokenSelectionSupport*/]), function (require, exports, nls, arrays, winjs_base_1, instantiation_1, range_1, editorContextKeys_1, editorCommonExtensions_1, tokenSelectionSupport_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    // --- selection state machine
    var State = (function () {
        function State(editor) {
            this.editor = editor;
            this.next = null;
            this.previous = null;
            this.selection = editor.getSelection();
        }
        return State;
    }());
    // --- shared state between grow and shrink actions
    var state = null;
    var ignoreSelection = false;
    // -- action implementation
    var SmartSelectController = (function () {
        function SmartSelectController(editor, instantiationService) {
            this.editor = editor;
            this._tokenSelectionSupport = instantiationService.createInstance(tokenSelectionSupport_1.TokenSelectionSupport);
        }
        SmartSelectController_1 = SmartSelectController;
        SmartSelectController.get = function (editor) {
            return editor.getContribution(SmartSelectController_1.ID);
        };
        SmartSelectController.prototype.dispose = function () {
        };
        SmartSelectController.prototype.getId = function () {
            return SmartSelectController_1.ID;
        };
        SmartSelectController.prototype.run = function (forward) {
            var _this = this;
            var selection = this.editor.getSelection();
            var model = this.editor.getModel();
            // forget about current state
            if (state) {
                if (state.editor !== this.editor) {
                    state = null;
                }
            }
            var promise = winjs_base_1.TPromise.as(null);
            if (!state) {
                promise = this._tokenSelectionSupport.getRangesToPosition(model.uri, selection.getStartPosition()).then(function (elements) {
                    if (arrays.isFalsyOrEmpty(elements)) {
                        return;
                    }
                    var lastState;
                    elements.filter(function (element) {
                        // filter ranges inside the selection
                        var selection = _this.editor.getSelection();
                        var range = new range_1.Range(element.range.startLineNumber, element.range.startColumn, element.range.endLineNumber, element.range.endColumn);
                        return range.containsPosition(selection.getStartPosition()) && range.containsPosition(selection.getEndPosition());
                    }).forEach(function (element) {
                        // create ranges
                        var range = element.range;
                        var state = new State(_this.editor);
                        state.selection = new range_1.Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
                        if (lastState) {
                            state.next = lastState;
                            lastState.previous = state;
                        }
                        lastState = state;
                    });
                    // insert current selection
                    var editorState = new State(_this.editor);
                    editorState.next = lastState;
                    if (lastState) {
                        lastState.previous = editorState;
                    }
                    state = editorState;
                    // listen to caret move and forget about state
                    var unhook = _this.editor.onDidChangeCursorPosition(function (e) {
                        if (ignoreSelection) {
                            return;
                        }
                        state = null;
                        unhook.dispose();
                    });
                });
            }
            return promise.then(function () {
                if (!state) {
                    return;
                }
                state = forward ? state.next : state.previous;
                if (!state) {
                    return;
                }
                ignoreSelection = true;
                try {
                    _this.editor.setSelection(state.selection);
                }
                finally {
                    ignoreSelection = false;
                }
                return;
            });
        };
        SmartSelectController.ID = 'editor.contrib.smartSelectController';
        SmartSelectController = SmartSelectController_1 = __decorate([
            editorCommonExtensions_1.commonEditorContribution,
            __param(1, instantiation_1.IInstantiationService)
        ], SmartSelectController);
        return SmartSelectController;
        var SmartSelectController_1;
    }());
    var AbstractSmartSelect = (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) {
            var controller = SmartSelectController.get(editor);
            if (controller) {
                return controller.run(this._forward);
            }
            return undefined;
        };
        return AbstractSmartSelect;
    }(editorCommonExtensions_1.EditorAction));
    var GrowSelectionAction = (function (_super) {
        __extends(GrowSelectionAction, _super);
        function GrowSelectionAction() {
            return _super.call(this, true, {
                id: 'editor.action.smartSelect.grow',
                label: nls.localize(0, null),
                alias: 'Expand Select',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 1024 /* Shift */ | 512 /* Alt */ | 17 /* RightArrow */,
                    mac: { primary: 2048 /* CtrlCmd */ | 256 /* WinCtrl */ | 1024 /* Shift */ | 17 /* RightArrow */ }
                }
            }) || this;
        }
        GrowSelectionAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], GrowSelectionAction);
        return GrowSelectionAction;
    }(AbstractSmartSelect));
    var ShrinkSelectionAction = (function (_super) {
        __extends(ShrinkSelectionAction, _super);
        function ShrinkSelectionAction() {
            return _super.call(this, false, {
                id: 'editor.action.smartSelect.shrink',
                label: nls.localize(1, null),
                alias: 'Shrink Select',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 1024 /* Shift */ | 512 /* Alt */ | 15 /* LeftArrow */,
                    mac: { primary: 2048 /* CtrlCmd */ | 256 /* WinCtrl */ | 1024 /* Shift */ | 15 /* LeftArrow */ }
                }
            }) || this;
        }
        ShrinkSelectionAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], ShrinkSelectionAction);
        return ShrinkSelectionAction;
    }(AbstractSmartSelect));
});

define(__m[109/*vs/editor/contrib/suggest/browser/suggest*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/async*/,33/*vs/base/common/arrays*/,9/*vs/base/common/strings*/,26/*vs/base/common/objects*/,10/*vs/base/common/errors*/,7/*vs/base/common/winjs.base*/,13/*vs/editor/common/editorCommonExtensions*/,17/*vs/editor/common/modes*/,19/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, async_1, arrays_1, strings_1, objects_1, errors_1, winjs_base_1, editorCommonExtensions_1, modes_1, contextkey_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Context = {
        Visible: new contextkey_1.RawContextKey('suggestWidgetVisible', false),
        MultipleSuggestions: new contextkey_1.RawContextKey('suggestWidgetMultipleSuggestions', false),
        MakesTextEdit: new contextkey_1.RawContextKey('suggestionMakesTextEdit', true),
        AcceptOnKey: new contextkey_1.RawContextKey('suggestionSupportsAcceptOnKey', true),
        AcceptSuggestionsOnEnter: new contextkey_1.RawContextKey('acceptSuggestionOnEnter', true)
    };
    var _snippetSuggestSupport;
    function setSnippetSuggestSupport(support) {
        var old = _snippetSuggestSupport;
        _snippetSuggestSupport = support;
        return old;
    }
    exports.setSnippetSuggestSupport = setSnippetSuggestSupport;
    function provideSuggestionItems(model, position, snippetConfig, onlyFrom) {
        if (snippetConfig === void 0) { snippetConfig = 'bottom'; }
        var allSuggestions = [];
        var acceptSuggestion = createSuggesionFilter(snippetConfig);
        position = position.clone();
        // get provider groups, always add snippet suggestion provider
        var supports = modes_1.SuggestRegistry.orderedGroups(model);
        // add snippets provider unless turned off
        if (snippetConfig !== 'none' && _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 () {
                // stop when we have a result
                if (hasResult) {
                    return undefined;
                }
                // for each support in the group ask for suggestions
                return winjs_base_1.TPromise.join(supports.map(function (support) {
                    if (!arrays_1.isFalsyOrEmpty(onlyFrom) && onlyFrom.indexOf(support) < 0) {
                        return undefined;
                    }
                    return async_1.asWinJsPromise(function (token) { return support.provideCompletionItems(model, position, token); }).then(function (container) {
                        var len = allSuggestions.length;
                        if (container && !arrays_1.isFalsyOrEmpty(container.suggestions)) {
                            for (var _i = 0, _a = container.suggestions; _i < _a.length; _i++) {
                                var suggestion = _a[_i];
                                if (acceptSuggestion(suggestion)) {
                                    fixOverwriteBeforeAfter(suggestion, container);
                                    allSuggestions.push({
                                        position: position,
                                        container: container,
                                        suggestion: suggestion,
                                        support: support,
                                        resolve: createSuggestionResolver(support, suggestion, model, position)
                                    });
                                }
                            }
                        }
                        if (len !== allSuggestions.length && support !== _snippetSuggestSupport) {
                            hasResult = true;
                        }
                    }, errors_1.onUnexpectedExternalError);
                }));
            };
        });
        var result = async_1.sequence(factory).then(function () { return allSuggestions.sort(getSuggestionComparator(snippetConfig)); });
        // 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 fixOverwriteBeforeAfter(suggestion, container) {
        if (typeof suggestion.overwriteBefore !== 'number') {
            suggestion.overwriteBefore = 0;
        }
        if (typeof suggestion.overwriteAfter !== 'number' || suggestion.overwriteAfter < 0) {
            suggestion.overwriteAfter = 0;
        }
    }
    function createSuggestionResolver(provider, suggestion, model, position) {
        return function () {
            if (typeof provider.resolveCompletionItem === 'function') {
                return async_1.asWinJsPromise(function (token) { return provider.resolveCompletionItem(model, position, suggestion, token); })
                    .then(function (value) { objects_1.assign(suggestion, value); });
            }
            return winjs_base_1.TPromise.as(void 0);
        };
    }
    function createSuggesionFilter(snippetConfig) {
        if (snippetConfig === 'none') {
            return function (suggestion) { return suggestion.type !== 'snippet'; };
        }
        else {
            return function () { return true; };
        }
    }
    function defaultComparator(a, b) {
        var ret = 0;
        // check with 'sortText'
        if (typeof a.suggestion.sortText === 'string' && typeof b.suggestion.sortText === 'string') {
            ret = strings_1.compareIgnoreCase(a.suggestion.sortText, b.suggestion.sortText);
        }
        // check with 'label'
        if (ret === 0) {
            ret = strings_1.compareIgnoreCase(a.suggestion.label, b.suggestion.label);
        }
        // check with 'type' and lower snippets
        if (ret === 0 && a.suggestion.type !== b.suggestion.type) {
            if (a.suggestion.type === 'snippet') {
                ret = 1;
            }
            else if (b.suggestion.type === 'snippet') {
                ret = -1;
            }
        }
        return ret;
    }
    function snippetUpComparator(a, b) {
        if (a.suggestion.type !== b.suggestion.type) {
            if (a.suggestion.type === 'snippet') {
                return -1;
            }
            else if (b.suggestion.type === 'snippet') {
                return 1;
            }
        }
        return defaultComparator(a, b);
    }
    function snippetDownComparator(a, b) {
        if (a.suggestion.type !== b.suggestion.type) {
            if (a.suggestion.type === 'snippet') {
                return 1;
            }
            else if (b.suggestion.type === 'snippet') {
                return -1;
            }
        }
        return defaultComparator(a, b);
    }
    function getSuggestionComparator(snippetConfig) {
        if (snippetConfig === 'top') {
            return snippetUpComparator;
        }
        else if (snippetConfig === 'bottom') {
            return snippetDownComparator;
        }
        else {
            return defaultComparator;
        }
    }
    exports.getSuggestionComparator = getSuggestionComparator;
    editorCommonExtensions_1.CommonEditorRegistry.registerDefaultLanguageCommand('_executeCompletionItemProvider', function (model, position, args) {
        var result = {
            incomplete: false,
            suggestions: []
        };
        return provideSuggestionItems(model, position).then(function (items) {
            for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
                var _a = items_1[_i], container = _a.container, suggestion = _a.suggestion;
                result.incomplete = result.incomplete || container.incomplete;
                result.suggestions.push(suggestion);
            }
            return result;
        });
    });
    var _suggestions;
    var _provider = new (function () {
        function class_1() {
        }
        class_1.prototype.provideCompletionItems = function () {
            return _suggestions && { suggestions: _suggestions };
        };
        return class_1;
    }());
    modes_1.SuggestRegistry.register('*', _provider);
    /**
     *
     * @param editor
     * @param suggestions
     */
    function showSimpleSuggestions(editor, suggestions) {
        setTimeout(function () {
            _suggestions = suggestions;
            editor.getContribution('editor.contrib.suggestController').triggerSuggest([_provider]);
            _suggestions = undefined;
        }, 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[180/*vs/editor/contrib/snippet/browser/snippetController2*/], __M([1/*require*/,0/*exports*/,19/*vs/platform/contextkey/common/contextkey*/,13/*vs/editor/common/editorCommonExtensions*/,3/*vs/base/common/lifecycle*/,334/*vs/editor/contrib/snippet/browser/snippetSession*/,21/*vs/editor/common/editorContextKeys*/,109/*vs/editor/contrib/suggest/browser/suggest*/,22/*vs/editor/common/core/selection*/]), function (require, exports, contextkey_1, editorCommonExtensions_1, lifecycle_1, snippetSession_1, editorContextKeys_1, suggest_1, selection_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var SnippetController2 = (function () {
        function SnippetController2(_editor, contextKeyService) {
            this._editor = _editor;
            this._snippetListener = [];
            this._inSnippet = SnippetController2_1.InSnippetMode.bindTo(contextKeyService);
            this._hasNextTabstop = SnippetController2_1.HasNextTabstop.bindTo(contextKeyService);
            this._hasPrevTabstop = SnippetController2_1.HasPrevTabstop.bindTo(contextKeyService);
        }
        SnippetController2_1 = SnippetController2;
        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) {
            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; }
            // 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);
                this._session.insert();
            }
            else {
                this._session.merge(template, overwriteBefore, overwriteAfter);
            }
            if (undoStopAfter) {
                this._editor.getModel().pushStackElement();
            }
            this._updateState();
            this._snippetListener = [
                this._editor.onDidChangeModel(function () { return _this.cancel(); }),
                this._editor.onDidChangeCursorSelection(function () { return _this._updateState(); })
            ];
        };
        SnippetController2.prototype._updateState = function () {
            if (!this._session) {
                // 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 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 {
                        type: 'value',
                        label: option.value,
                        insertText: option.value,
                        // insertText: `\${1|${after.concat(before).join(',')}|}$0`,
                        // snippetType: 'textmate',
                        sortText: String(i),
                        overwriteAfter: first_1.value.length
                    };
                }));
            }
        };
        SnippetController2.prototype.finish = function () {
            while (this._inSnippet.get()) {
                this.next();
            }
        };
        SnippetController2.prototype.cancel = function () {
            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;
        };
        SnippetController2.prototype.prev = function () {
            this._session.prev();
            this._updateState();
        };
        SnippetController2.prototype.next = function () {
            this._session.next();
            this._updateState();
        };
        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 = SnippetController2_1 = __decorate([
            editorCommonExtensions_1.commonEditorContribution,
            __param(1, contextkey_1.IContextKeyService)
        ], SnippetController2);
        return SnippetController2;
        var SnippetController2_1;
    }());
    exports.SnippetController2 = SnippetController2;
    var CommandCtor = editorCommonExtensions_1.EditorCommand.bindToContribution(SnippetController2.get);
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new CommandCtor({
        id: 'jumpToNextSnippetPlaceholder',
        precondition: contextkey_1.ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasNextTabstop),
        handler: function (ctrl) { return ctrl.next(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(30),
            kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
            primary: 2 /* Tab */
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new CommandCtor({
        id: 'jumpToPrevSnippetPlaceholder',
        precondition: contextkey_1.ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasPrevTabstop),
        handler: function (ctrl) { return ctrl.prev(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(30),
            kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
            primary: 1024 /* Shift */ | 2 /* Tab */
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new CommandCtor({
        id: 'leaveSnippet',
        precondition: SnippetController2.InSnippetMode,
        handler: function (ctrl) { return ctrl.cancel(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(30),
            kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
            primary: 9 /* Escape */,
            secondary: [1024 /* Shift */ | 9 /* Escape */]
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new CommandCtor({
        id: 'acceptSnippet',
        precondition: SnippetController2.InSnippetMode,
        handler: function (ctrl) { return ctrl.finish(); },
    }));
});

define(__m[474/*vs/editor/contrib/suggest/browser/suggestModel*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,33/*vs/base/common/arrays*/,18/*vs/base/common/async*/,11/*vs/base/common/event*/,3/*vs/base/common/lifecycle*/,7/*vs/base/common/winjs.base*/,17/*vs/editor/common/modes*/,12/*vs/editor/common/core/position*/,109/*vs/editor/contrib/suggest/browser/suggest*/,272/*vs/editor/contrib/suggest/browser/completionModel*/,54/*vs/editor/common/controller/cursorEvents*/]), function (require, exports, errors_1, arrays_1, async_1, event_1, lifecycle_1, winjs_base_1, modes_1, position_1, suggest_1, completionModel_1, cursorEvents_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var LineContext = (function () {
        function LineContext(model, position, auto) {
            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;
        }
        LineContext.shouldAutoTrigger = function (editor) {
            var model = editor.getModel();
            if (!model) {
                return false;
            }
            var pos = editor.getPosition();
            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;
        };
        LineContext.isInEditableRange = function (editor) {
            var model = editor.getModel();
            var position = editor.getPosition();
            if (model.hasEditableRange()) {
                var editableRange = model.getEditableRange();
                if (!editableRange.containsPosition(position)) {
                    return false;
                }
            }
            return true;
        };
        return LineContext;
    }());
    exports.LineContext = LineContext;
    var State;
    (function (State) {
        State[State["Idle"] = 0] = "Idle";
        State[State["Manual"] = 1] = "Manual";
        State[State["Auto"] = 2] = "Auto";
    })(State = exports.State || (exports.State = {}));
    var SuggestModel = (function () {
        function SuggestModel(editor) {
            var _this = this;
            this.editor = editor;
            this.toDispose = [];
            this.triggerRefilter = new async_1.TimeoutTimer();
            this._onDidCancel = new event_1.Emitter();
            this._onDidTrigger = new event_1.Emitter();
            this._onDidSuggest = new event_1.Emitter();
            this._state = 0 /* Idle */;
            this.triggerAutoSuggestPromise = null;
            this.requestPromise = null;
            this.completionModel = null;
            this.context = null;
            this.currentPosition = editor.getPosition() || new position_1.Position(1, 1);
            // wire up various listeners
            this.toDispose.push(this.editor.onDidChangeModel(function () {
                _this.updateTriggerCharacters();
                _this.cancel();
            }));
            this.toDispose.push(editor.onDidChangeModelLanguage(function () {
                _this.updateTriggerCharacters();
                _this.cancel();
            }));
            this.toDispose.push(this.editor.onDidChangeConfiguration(function () {
                _this.updateTriggerCharacters();
                _this.updateQuickSuggest();
            }));
            this.toDispose.push(modes_1.SuggestRegistry.onDidChange(function () {
                _this.updateTriggerCharacters();
                _this.updateActiveSuggestSession();
            }));
            this.toDispose.push(this.editor.onDidChangeCursorSelection(function (e) {
                _this.onCursorChange(e);
            }));
            this.updateTriggerCharacters();
            this.updateQuickSuggest();
        }
        Object.defineProperty(SuggestModel.prototype, "onDidCancel", {
            get: function () { return this._onDidCancel.event; },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SuggestModel.prototype, "onDidTrigger", {
            get: function () { return this._onDidTrigger.event; },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SuggestModel.prototype, "onDidSuggest", {
            get: function () { return this._onDidSuggest.event; },
            enumerable: true,
            configurable: true
        });
        SuggestModel.prototype.dispose = function () {
            lifecycle_1.dispose([this._onDidCancel, this._onDidSuggest, this._onDidTrigger, this.triggerCharacterListener, this.triggerRefilter]);
            this.toDispose = lifecycle_1.dispose(this.toDispose);
            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.getModel()
                || !this.editor.getConfiguration().contribInfo.suggestOnTriggerCharacters) {
                return;
            }
            var supportsByTriggerCharacter = Object.create(null);
            for (var _i = 0, _a = modes_1.SuggestRegistry.all(this.editor.getModel()); _i < _a.length; _i++) {
                var support = _a[_i];
                if (arrays_1.isFalsyOrEmpty(support.triggerCharacters)) {
                    continue;
                }
                for (var _b = 0, _c = support.triggerCharacters; _b < _c.length; _b++) {
                    var ch = _c[_b];
                    var array = supportsByTriggerCharacter[ch];
                    if (!array) {
                        supportsByTriggerCharacter[ch] = [support];
                    }
                    else {
                        array.push(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 = [];
                    if (_this.completionModel) {
                        for (var _i = 0, _a = _this.completionModel.items; _i < _a.length; _i++) {
                            var item = _a[_i];
                            if (supports.indexOf(item.support) < 0) {
                                items.push(item);
                            }
                        }
                    }
                    _this.trigger(true, 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.triggerAutoSuggestPromise) {
                this.triggerAutoSuggestPromise.cancel();
                this.triggerAutoSuggestPromise = null;
            }
            if (this.requestPromise) {
                this.requestPromise.cancel();
                this.requestPromise = null;
            }
            this._state = 0 /* Idle */;
            this.completionModel = null;
            this.context = null;
            this._onDidCancel.fire({ retrigger: retrigger });
        };
        SuggestModel.prototype.updateActiveSuggestSession = function () {
            if (this._state !== 0 /* Idle */) {
                if (!modes_1.SuggestRegistry.has(this.editor.getModel())) {
                    this.cancel();
                }
                else {
                    this.trigger(this._state === 2 /* Auto */, true);
                }
            }
        };
        SuggestModel.prototype.onCursorChange = function (e) {
            var _this = this;
            var prevPosition = this.currentPosition;
            this.currentPosition = this.editor.getPosition();
            if (!e.selection.isEmpty()
                || e.source !== 'keyboard'
                || e.reason !== cursorEvents_1.CursorChangeReason.NotSet) {
                if (this._state === 0 /* Idle */) {
                    // 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.cancel();
                return;
            }
            if (!modes_1.SuggestRegistry.has(this.editor.getModel())) {
                return;
            }
            var model = this.editor.getModel();
            if (!model) {
                return;
            }
            if (this._state === 0 /* Idle */) {
                // trigger 24x7 IntelliSense when idle, enabled, when cursor
                // moved RIGHT, and when at a good position
                if (this.editor.getConfiguration().contribInfo.quickSuggestions !== false
                    && prevPosition.isBefore(this.currentPosition)) {
                    this.cancel();
                    if (LineContext.shouldAutoTrigger(this.editor)) {
                        this.triggerAutoSuggestPromise = winjs_base_1.TPromise.timeout(this.quickSuggestDelay);
                        this.triggerAutoSuggestPromise.then(function () {
                            var model = _this.editor.getModel();
                            var pos = _this.editor.getPosition();
                            if (!model) {
                                return;
                            }
                            // validate enabled now
                            var quickSuggestions = _this.editor.getConfiguration().contribInfo.quickSuggestions;
                            if (quickSuggestions === false) {
                                return;
                            }
                            else if (quickSuggestions === true) {
                                // all good
                            }
                            else {
                                model.forceTokenization(pos.lineNumber);
                                var tokenType = model
                                    .getLineTokens(pos.lineNumber)
                                    .findTokenAtOffset(pos.column - 1).tokenType;
                                var inValidScope = quickSuggestions.other && tokenType === 0 /* Other */
                                    || quickSuggestions.comments && tokenType === 1 /* Comment */
                                    || quickSuggestions.strings && tokenType === 2 /* String */;
                                if (!inValidScope) {
                                    return;
                                }
                            }
                            _this.triggerAutoSuggestPromise = null;
                            _this.trigger(true);
                        });
                    }
                }
            }
            else {
                // refine active suggestion
                this.triggerRefilter.cancelAndSet(function () {
                    var position = _this.editor.getPosition();
                    var ctx = new LineContext(model, position, _this._state === 2 /* Auto */);
                    _this.onNewContext(ctx);
                }, 25);
            }
        };
        SuggestModel.prototype.trigger = function (auto, retrigger, onlyFrom, existingItems) {
            var _this = this;
            if (retrigger === void 0) { retrigger = false; }
            var model = this.editor.getModel();
            if (!model) {
                return;
            }
            var ctx = new LineContext(model, this.editor.getPosition(), auto);
            if (!LineContext.isInEditableRange(this.editor)) {
                return;
            }
            // Cancel previous requests, change state & update UI
            this.cancel(retrigger);
            this._state = auto ? 2 /* Auto */ : 1 /* Manual */;
            this._onDidTrigger.fire({ auto: auto });
            // Capture context when request was sent
            this.context = ctx;
            this.requestPromise = suggest_1.provideSuggestionItems(model, this.editor.getPosition(), this.editor.getConfiguration().contribInfo.snippetSuggestions, onlyFrom).then(function (items) {
                _this.requestPromise = null;
                if (_this._state === 0 /* Idle */) {
                    return;
                }
                var model = _this.editor.getModel();
                if (!model) {
                    return;
                }
                if (!arrays_1.isFalsyOrEmpty(existingItems)) {
                    var cmpFn = suggest_1.getSuggestionComparator(_this.editor.getConfiguration().contribInfo.snippetSuggestions);
                    items = items.concat(existingItems).sort(cmpFn);
                }
                var ctx = new LineContext(model, _this.editor.getPosition(), auto);
                _this.completionModel = new completionModel_1.CompletionModel(items, _this.context.column, {
                    leadingLineContent: ctx.leadingLineContent,
                    characterCountDelta: _this.context ? ctx.column - _this.context.column : 0
                }, _this.editor.getConfiguration().contribInfo.snippetSuggestions);
                _this.onNewContext(ctx);
            }).then(null, 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.column < this.context.column) {
                // typed -> moved cursor LEFT -> retrigger if still on a word
                if (ctx.leadingWord.word) {
                    this.trigger(this.context.auto, 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 && ctx.leadingWord.word.length !== 0) {
                // typed -> moved cursor RIGHT & incomple model & still on a word -> retrigger
                var _a = this.completionModel.resolveIncompleteInfo(), complete = _a.complete, incomplete = _a.incomplete;
                this.trigger(this._state === 2 /* Auto */, true, incomplete, complete);
            }
            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(this.context.auto, 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,
                    isFrozen: isFrozen,
                });
            }
        };
        return SuggestModel;
    }());
    exports.SuggestModel = SuggestModel;
});

















define(__m[181/*vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode*/], __M([1/*require*/,0/*exports*/,373/*vs/nls!vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode*/,13/*vs/editor/common/editorCommonExtensions*/,168/*vs/editor/common/config/commonEditorConfig*/]), function (require, exports, nls, editorCommonExtensions_1, commonEditorConfig_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ToggleTabFocusModeAction = (function (_super) {
        __extends(ToggleTabFocusModeAction, _super);
        function ToggleTabFocusModeAction() {
            return _super.call(this, {
                id: ToggleTabFocusModeAction_1.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 */ }
                }
            }) || this;
        }
        ToggleTabFocusModeAction_1 = ToggleTabFocusModeAction;
        ToggleTabFocusModeAction.prototype.run = function (accessor, editor) {
            var oldValue = commonEditorConfig_1.TabFocus.getTabFocusMode();
            commonEditorConfig_1.TabFocus.setTabFocusMode(!oldValue);
        };
        ToggleTabFocusModeAction.ID = 'editor.action.toggleTabFocusMode';
        ToggleTabFocusModeAction = ToggleTabFocusModeAction_1 = __decorate([
            editorCommonExtensions_1.editorAction
        ], ToggleTabFocusModeAction);
        return ToggleTabFocusModeAction;
        var ToggleTabFocusModeAction_1;
    }(editorCommonExtensions_1.EditorAction));
    exports.ToggleTabFocusModeAction = 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[476/*vs/editor/contrib/wordOperations/common/wordOperations*/], __M([1/*require*/,0/*exports*/,21/*vs/editor/common/editorContextKeys*/,22/*vs/editor/common/core/selection*/,13/*vs/editor/common/editorCommonExtensions*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,172/*vs/editor/common/controller/cursorWordOperations*/,73/*vs/editor/common/commands/replaceCommand*/,94/*vs/editor/common/controller/wordCharacterClassifier*/,39/*vs/editor/common/controller/cursorCommon*/,54/*vs/editor/common/controller/cursorEvents*/]), function (require, exports, editorContextKeys_1, selection_1, editorCommonExtensions_1, position_1, range_1, cursorWordOperations_1, replaceCommand_1, wordCharacterClassifier_1, cursorCommon_1, cursorEvents_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MoveWordCommand = (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;
            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', cursorEvents_1.CursorChangeReason.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, false, true);
            }
        };
        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;
    }(editorCommonExtensions_1.EditorCommand));
    exports.MoveWordCommand = MoveWordCommand;
    var WordLeftCommand = (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 = (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 = (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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 15 /* LeftArrow */,
                    mac: { primary: 512 /* Alt */ | 15 /* LeftArrow */ }
                }
            }) || this;
        }
        CursorWordStartLeft = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordStartLeft);
        return CursorWordStartLeft;
    }(WordLeftCommand));
    exports.CursorWordStartLeft = CursorWordStartLeft;
    var CursorWordEndLeft = (function (_super) {
        __extends(CursorWordEndLeft, _super);
        function CursorWordEndLeft() {
            return _super.call(this, {
                inSelectionMode: false,
                wordNavigationType: 1 /* WordEnd */,
                id: 'cursorWordEndLeft',
                precondition: null
            }) || this;
        }
        CursorWordEndLeft = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordEndLeft);
        return CursorWordEndLeft;
    }(WordLeftCommand));
    exports.CursorWordEndLeft = CursorWordEndLeft;
    var CursorWordLeft = (function (_super) {
        __extends(CursorWordLeft, _super);
        function CursorWordLeft() {
            return _super.call(this, {
                inSelectionMode: false,
                wordNavigationType: 0 /* WordStart */,
                id: 'cursorWordLeft',
                precondition: null
            }) || this;
        }
        CursorWordLeft = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordLeft);
        return CursorWordLeft;
    }(WordLeftCommand));
    exports.CursorWordLeft = CursorWordLeft;
    var CursorWordStartLeftSelect = (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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 15 /* LeftArrow */,
                    mac: { primary: 512 /* Alt */ | 1024 /* Shift */ | 15 /* LeftArrow */ }
                }
            }) || this;
        }
        CursorWordStartLeftSelect = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordStartLeftSelect);
        return CursorWordStartLeftSelect;
    }(WordLeftCommand));
    exports.CursorWordStartLeftSelect = CursorWordStartLeftSelect;
    var CursorWordEndLeftSelect = (function (_super) {
        __extends(CursorWordEndLeftSelect, _super);
        function CursorWordEndLeftSelect() {
            return _super.call(this, {
                inSelectionMode: true,
                wordNavigationType: 1 /* WordEnd */,
                id: 'cursorWordEndLeftSelect',
                precondition: null
            }) || this;
        }
        CursorWordEndLeftSelect = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordEndLeftSelect);
        return CursorWordEndLeftSelect;
    }(WordLeftCommand));
    exports.CursorWordEndLeftSelect = CursorWordEndLeftSelect;
    var CursorWordLeftSelect = (function (_super) {
        __extends(CursorWordLeftSelect, _super);
        function CursorWordLeftSelect() {
            return _super.call(this, {
                inSelectionMode: true,
                wordNavigationType: 0 /* WordStart */,
                id: 'cursorWordLeftSelect',
                precondition: null
            }) || this;
        }
        CursorWordLeftSelect = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordLeftSelect);
        return CursorWordLeftSelect;
    }(WordLeftCommand));
    exports.CursorWordLeftSelect = CursorWordLeftSelect;
    var CursorWordStartRight = (function (_super) {
        __extends(CursorWordStartRight, _super);
        function CursorWordStartRight() {
            return _super.call(this, {
                inSelectionMode: false,
                wordNavigationType: 0 /* WordStart */,
                id: 'cursorWordStartRight',
                precondition: null
            }) || this;
        }
        CursorWordStartRight = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordStartRight);
        return CursorWordStartRight;
    }(WordRightCommand));
    exports.CursorWordStartRight = CursorWordStartRight;
    var CursorWordEndRight = (function (_super) {
        __extends(CursorWordEndRight, _super);
        function CursorWordEndRight() {
            return _super.call(this, {
                inSelectionMode: false,
                wordNavigationType: 1 /* WordEnd */,
                id: 'cursorWordEndRight',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 17 /* RightArrow */,
                    mac: { primary: 512 /* Alt */ | 17 /* RightArrow */ }
                }
            }) || this;
        }
        CursorWordEndRight = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordEndRight);
        return CursorWordEndRight;
    }(WordRightCommand));
    exports.CursorWordEndRight = CursorWordEndRight;
    var CursorWordRight = (function (_super) {
        __extends(CursorWordRight, _super);
        function CursorWordRight() {
            return _super.call(this, {
                inSelectionMode: false,
                wordNavigationType: 1 /* WordEnd */,
                id: 'cursorWordRight',
                precondition: null
            }) || this;
        }
        CursorWordRight = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordRight);
        return CursorWordRight;
    }(WordRightCommand));
    exports.CursorWordRight = CursorWordRight;
    var CursorWordStartRightSelect = (function (_super) {
        __extends(CursorWordStartRightSelect, _super);
        function CursorWordStartRightSelect() {
            return _super.call(this, {
                inSelectionMode: true,
                wordNavigationType: 0 /* WordStart */,
                id: 'cursorWordStartRightSelect',
                precondition: null
            }) || this;
        }
        CursorWordStartRightSelect = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordStartRightSelect);
        return CursorWordStartRightSelect;
    }(WordRightCommand));
    exports.CursorWordStartRightSelect = CursorWordStartRightSelect;
    var CursorWordEndRightSelect = (function (_super) {
        __extends(CursorWordEndRightSelect, _super);
        function CursorWordEndRightSelect() {
            return _super.call(this, {
                inSelectionMode: true,
                wordNavigationType: 1 /* WordEnd */,
                id: 'cursorWordEndRightSelect',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 17 /* RightArrow */,
                    mac: { primary: 512 /* Alt */ | 1024 /* Shift */ | 17 /* RightArrow */ }
                }
            }) || this;
        }
        CursorWordEndRightSelect = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordEndRightSelect);
        return CursorWordEndRightSelect;
    }(WordRightCommand));
    exports.CursorWordEndRightSelect = CursorWordEndRightSelect;
    var CursorWordRightSelect = (function (_super) {
        __extends(CursorWordRightSelect, _super);
        function CursorWordRightSelect() {
            return _super.call(this, {
                inSelectionMode: true,
                wordNavigationType: 1 /* WordEnd */,
                id: 'cursorWordRightSelect',
                precondition: null
            }) || this;
        }
        CursorWordRightSelect = __decorate([
            editorCommonExtensions_1.editorCommand
        ], CursorWordRightSelect);
        return CursorWordRightSelect;
    }(WordRightCommand));
    exports.CursorWordRightSelect = CursorWordRightSelect;
    var DeleteWordCommand = (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;
            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;
    }(editorCommonExtensions_1.EditorCommand));
    exports.DeleteWordCommand = DeleteWordCommand;
    var DeleteWordLeftCommand = (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 = (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 = (function (_super) {
        __extends(DeleteWordStartLeft, _super);
        function DeleteWordStartLeft() {
            return _super.call(this, {
                whitespaceHeuristics: false,
                wordNavigationType: 0 /* WordStart */,
                id: 'deleteWordStartLeft',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            }) || this;
        }
        DeleteWordStartLeft = __decorate([
            editorCommonExtensions_1.editorCommand
        ], DeleteWordStartLeft);
        return DeleteWordStartLeft;
    }(DeleteWordLeftCommand));
    exports.DeleteWordStartLeft = DeleteWordStartLeft;
    var DeleteWordEndLeft = (function (_super) {
        __extends(DeleteWordEndLeft, _super);
        function DeleteWordEndLeft() {
            return _super.call(this, {
                whitespaceHeuristics: false,
                wordNavigationType: 1 /* WordEnd */,
                id: 'deleteWordEndLeft',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            }) || this;
        }
        DeleteWordEndLeft = __decorate([
            editorCommonExtensions_1.editorCommand
        ], DeleteWordEndLeft);
        return DeleteWordEndLeft;
    }(DeleteWordLeftCommand));
    exports.DeleteWordEndLeft = DeleteWordEndLeft;
    var DeleteWordLeft = (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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1 /* Backspace */,
                    mac: { primary: 512 /* Alt */ | 1 /* Backspace */ }
                }
            }) || this;
        }
        DeleteWordLeft = __decorate([
            editorCommonExtensions_1.editorCommand
        ], DeleteWordLeft);
        return DeleteWordLeft;
    }(DeleteWordLeftCommand));
    exports.DeleteWordLeft = DeleteWordLeft;
    var DeleteWordStartRight = (function (_super) {
        __extends(DeleteWordStartRight, _super);
        function DeleteWordStartRight() {
            return _super.call(this, {
                whitespaceHeuristics: false,
                wordNavigationType: 0 /* WordStart */,
                id: 'deleteWordStartRight',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            }) || this;
        }
        DeleteWordStartRight = __decorate([
            editorCommonExtensions_1.editorCommand
        ], DeleteWordStartRight);
        return DeleteWordStartRight;
    }(DeleteWordRightCommand));
    exports.DeleteWordStartRight = DeleteWordStartRight;
    var DeleteWordEndRight = (function (_super) {
        __extends(DeleteWordEndRight, _super);
        function DeleteWordEndRight() {
            return _super.call(this, {
                whitespaceHeuristics: false,
                wordNavigationType: 1 /* WordEnd */,
                id: 'deleteWordEndRight',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            }) || this;
        }
        DeleteWordEndRight = __decorate([
            editorCommonExtensions_1.editorCommand
        ], DeleteWordEndRight);
        return DeleteWordEndRight;
    }(DeleteWordRightCommand));
    exports.DeleteWordEndRight = DeleteWordEndRight;
    var DeleteWordRight = (function (_super) {
        __extends(DeleteWordRight, _super);
        function DeleteWordRight() {
            return _super.call(this, {
                whitespaceHeuristics: true,
                wordNavigationType: 1 /* WordEnd */,
                id: 'deleteWordRight',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 20 /* Delete */,
                    mac: { primary: 512 /* Alt */ | 20 /* Delete */ }
                }
            }) || this;
        }
        DeleteWordRight = __decorate([
            editorCommonExtensions_1.editorCommand
        ], DeleteWordRight);
        return DeleteWordRight;
    }(DeleteWordRightCommand));
    exports.DeleteWordRight = DeleteWordRight;
});

















define(__m[477/*vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast*/], __M([1/*require*/,0/*exports*/,381/*vs/nls!vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast*/,13/*vs/editor/common/editorCommonExtensions*/,77/*vs/editor/standalone/common/standaloneThemeService*/]), function (require, exports, nls, editorCommonExtensions_1, standaloneThemeService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ToggleHighContrast = (function (_super) {
        __extends(ToggleHighContrast, _super);
        function ToggleHighContrast() {
            var _this = _super.call(this, {
                id: 'editor.action.toggleHighContrast',
                label: nls.localize(0, null),
                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');
            }
        };
        ToggleHighContrast = __decorate([
            editorCommonExtensions_1.editorAction
        ], ToggleHighContrast);
        return ToggleHighContrast;
    }(editorCommonExtensions_1.EditorAction));
});










define(__m[478/*vs/platform/contextview/browser/contextViewService*/], __M([1/*require*/,0/*exports*/,160/*vs/base/browser/ui/contextview/contextview*/,58/*vs/platform/telemetry/common/telemetry*/,50/*vs/platform/message/common/message*/]), function (require, exports, contextview_1, telemetry_1, message_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ContextViewService = (function () {
        function ContextViewService(container, telemetryService, messageService) {
            this.contextView = new contextview_1.ContextView(container);
        }
        ContextViewService.prototype.dispose = function () {
            this.contextView.dispose();
        };
        // 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(1, telemetry_1.ITelemetryService),
            __param(2, message_1.IMessageService)
        ], ContextViewService);
        return ContextViewService;
    }());
    exports.ContextViewService = ContextViewService;
});

define(__m[479/*vs/platform/telemetry/common/telemetryUtils*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,166/*vs/base/common/mime*/,45/*vs/base/common/paths*/,62/*vs/platform/configuration/common/configuration*/,46/*vs/platform/keybinding/common/keybinding*/,420/*vs/platform/lifecycle/common/lifecycle*/]), function (require, exports, winjs_base_1, mime_1, paths, configuration_1, keybinding_1, lifecycle_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NullTelemetryService = {
        _serviceBrand: undefined,
        publicLog: function (eventName, data) {
            return winjs_base_1.TPromise.as(null);
        },
        isOptedIn: true,
        getTelemetryInfo: function () {
            return winjs_base_1.TPromise.as({
                instanceId: 'someValue.instanceId',
                sessionId: 'someValue.sessionId',
                machineId: 'someValue.machineId'
            });
        }
    };
    function combinedAppender() {
        var appenders = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            appenders[_i] = arguments[_i];
        }
        return { log: function (e, d) { return appenders.forEach(function (a) { return a.log(e, d); }); } };
    }
    exports.combinedAppender = combinedAppender;
    exports.NullAppender = { log: function () { return null; } };
    // --- util
    function anonymize(input) {
        if (!input) {
            return input;
        }
        var r = '';
        for (var i = 0; i < input.length; i++) {
            var ch = input[i];
            if (ch >= '0' && ch <= '9') {
                r += '0';
                continue;
            }
            if (ch >= 'a' && ch <= 'z') {
                r += 'a';
                continue;
            }
            if (ch >= 'A' && ch <= 'Z') {
                r += 'A';
                continue;
            }
            r += ch;
        }
        return r;
    }
    exports.anonymize = anonymize;
    function telemetryURIDescriptor(uri) {
        var fsPath = uri && uri.fsPath;
        return fsPath ? { mimeType: mime_1.guessMimeTypes(fsPath).join(', '), ext: paths.extname(fsPath), path: anonymize(fsPath) } : {};
    }
    exports.telemetryURIDescriptor = telemetryURIDescriptor;
    /**
     * Only add settings that cannot contain any personal/private information of users (PII).
     */
    var configurationValueWhitelist = [
        'editor.tabCompletion',
        'editor.fontFamily',
        'editor.fontWeight',
        'editor.fontSize',
        'editor.lineHeight',
        'editor.letterSpacing',
        'editor.lineNumbers',
        'editor.rulers',
        'editor.wordSeparators',
        'editor.tabSize',
        'editor.insertSpaces',
        'editor.detectIndentation',
        'editor.roundedSelection',
        'editor.scrollBeyondLastLine',
        'editor.minimap.enabled',
        'editor.minimap.renderCharacters',
        'editor.minimap.maxColumn',
        'editor.find.seedSearchStringFromSelection',
        'editor.find.autoFindInSelection',
        'editor.wordWrap',
        'editor.wordWrapColumn',
        'editor.wrappingIndent',
        'editor.mouseWheelScrollSensitivity',
        'editor.multiCursorModifier',
        'editor.quickSuggestions',
        'editor.quickSuggestionsDelay',
        'editor.parameterHints',
        'editor.autoClosingBrackets',
        'editor.autoIndent',
        'editor.formatOnType',
        'editor.formatOnPaste',
        'editor.suggestOnTriggerCharacters',
        'editor.acceptSuggestionOnEnter',
        'editor.acceptSuggestionOnCommitCharacter',
        'editor.snippetSuggestions',
        'editor.emptySelectionClipboard',
        'editor.wordBasedSuggestions',
        'editor.suggestFontSize',
        'editor.suggestLineHeight',
        'editor.selectionHighlight',
        'editor.occurrencesHighlight',
        'editor.overviewRulerLanes',
        'editor.overviewRulerBorder',
        'editor.cursorBlinking',
        'editor.cursorStyle',
        'editor.mouseWheelZoom',
        'editor.fontLigatures',
        'editor.hideCursorInOverviewRuler',
        'editor.renderWhitespace',
        'editor.renderControlCharacters',
        'editor.renderIndentGuides',
        'editor.renderLineHighlight',
        'editor.codeLens',
        'editor.folding',
        'editor.showFoldingControls',
        'editor.matchBrackets',
        'editor.glyphMargin',
        'editor.useTabStops',
        'editor.trimAutoWhitespace',
        'editor.stablePeek',
        'editor.dragAndDrop',
        'editor.formatOnSave',
        'window.zoomLevel',
        'files.autoSave',
        'files.hotExit',
        'files.associations',
        'workbench.statusBar.visible',
        'files.trimTrailingWhitespace',
        'git.confirmSync',
        'workbench.sideBar.location',
        'window.openFilesInNewWindow',
        'javascript.validate.enable',
        'window.reopenFolders',
        'window.restoreWindows',
        'extensions.autoUpdate',
        'files.eol',
        'explorer.openEditors.visible',
        'workbench.editor.enablePreview',
        'files.autoSaveDelay',
        'workbench.editor.showTabs',
        'files.encoding',
        'files.autoGuessEncoding',
        'git.enabled',
        'http.proxyStrictSSL',
        'terminal.integrated.fontFamily',
        'workbench.editor.enablePreviewFromQuickOpen',
        'workbench.editor.swipeToNavigate',
        'php.builtInCompletions.enable',
        'php.validate.enable',
        'php.validate.run',
        'workbench.welcome.enabled',
        'workbench.startupEditor',
    ];
    function configurationTelemetry(telemetryService, configurationService) {
        return configurationService.onDidUpdateConfiguration(function (event) {
            if (event.source !== configuration_1.ConfigurationSource.Default) {
                telemetryService.publicLog('updateConfiguration', {
                    configurationSource: configuration_1.ConfigurationSource[event.source],
                    configurationKeys: flattenKeys(event.sourceConfig)
                });
                telemetryService.publicLog('updateConfigurationValues', {
                    configurationSource: configuration_1.ConfigurationSource[event.source],
                    configurationValues: flattenValues(event.sourceConfig, configurationValueWhitelist)
                });
            }
        });
    }
    exports.configurationTelemetry = configurationTelemetry;
    function lifecycleTelemetry(telemetryService, lifecycleService) {
        return lifecycleService.onShutdown(function (event) {
            telemetryService.publicLog('shutdown', { reason: lifecycle_1.ShutdownReason[event] });
        });
    }
    exports.lifecycleTelemetry = lifecycleTelemetry;
    function keybindingsTelemetry(telemetryService, keybindingService) {
        return keybindingService.onDidUpdateKeybindings(function (event) {
            if (event.source === keybinding_1.KeybindingSource.User && event.keybindings) {
                telemetryService.publicLog('updateKeybindings', {
                    bindings: event.keybindings.map(function (binding) { return ({
                        key: binding.key,
                        command: binding.command,
                        when: binding.when,
                        args: binding.args ? true : undefined
                    }); })
                });
            }
        });
    }
    exports.keybindingsTelemetry = keybindingsTelemetry;
    function flattenKeys(value) {
        if (!value) {
            return [];
        }
        var result = [];
        flatKeys(result, '', value);
        return result;
    }
    function flatKeys(result, prefix, value) {
        if (value && typeof value === 'object' && !Array.isArray(value)) {
            Object.keys(value)
                .forEach(function (key) { return flatKeys(result, prefix ? prefix + "." + key : key, value[key]); });
        }
        else {
            result.push(prefix);
        }
    }
    function flattenValues(value, keys) {
        if (!value) {
            return [];
        }
        return keys.reduce(function (array, key) {
            var v = key.split('.')
                .reduce(function (tmp, k) { return tmp && typeof tmp === 'object' ? tmp[k] : undefined; }, value);
            if (typeof v !== 'undefined') {
                array.push((_a = {}, _a[key] = v, _a));
            }
            return array;
            var _a;
        }, []);
    }
});










define(__m[480/*vs/platform/opener/browser/openerService*/], __M([1/*require*/,0/*exports*/,24/*vs/base/common/uri*/,487/*vs/base/common/marshalling*/,70/*vs/base/common/network*/,7/*vs/base/common/winjs.base*/,64/*vs/platform/editor/common/editor*/,45/*vs/base/common/paths*/,31/*vs/platform/commands/common/commands*/,58/*vs/platform/telemetry/common/telemetry*/,16/*vs/platform/instantiation/common/instantiation*/,479/*vs/platform/telemetry/common/telemetryUtils*/]), function (require, exports, uri_1, marshalling_1, network_1, winjs_base_1, editor_1, paths_1, commands_1, telemetry_1, instantiation_1, telemetryUtils_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var OpenerService = (function () {
        function OpenerService(_editorService, _commandService, _telemetryService) {
            if (_telemetryService === void 0) { _telemetryService = telemetryUtils_1.NullTelemetryService; }
            this._editorService = _editorService;
            this._commandService = _commandService;
            this._telemetryService = _telemetryService;
            //
        }
        OpenerService.prototype.open = function (resource, options) {
            this._telemetryService.publicLog('openerService', { scheme: resource.scheme });
            var scheme = resource.scheme, path = resource.path, query = resource.query, fragment = resource.fragment;
            var promise;
            if (scheme === network_1.Schemas.http || scheme === network_1.Schemas.https) {
                // open http
                window.open(resource.toString(true));
            }
            else if (scheme === 'command' && commands_1.CommandsRegistry.getCommand(path)) {
                // execute as command
                var args = [];
                try {
                    args = marshalling_1.parse(query);
                    if (!Array.isArray(args)) {
                        args = [args];
                    }
                }
                catch (e) {
                    //
                }
                promise = (_a = this._commandService).executeCommand.apply(_a, [path].concat(args));
            }
            else {
                var selection = void 0;
                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) {
                    // we cannot handle those
                    return winjs_base_1.TPromise.as(undefined);
                }
                else if (resource.scheme === network_1.Schemas.file) {
                    resource = uri_1.default.file(paths_1.normalize(resource.fsPath)); // workaround for non-normalized paths (https://github.com/Microsoft/vscode/issues/12954)
                }
                promise = this._editorService.openEditor({ resource: resource, options: { selection: selection, } }, options && options.openToSide);
            }
            return winjs_base_1.TPromise.as(promise);
            var _a;
        };
        OpenerService = __decorate([
            __param(0, editor_1.IEditorService),
            __param(1, commands_1.ICommandService),
            __param(2, instantiation_1.optional(telemetry_1.ITelemetryService))
        ], OpenerService);
        return OpenerService;
    }());
    exports.OpenerService = OpenerService;
});

define(__m[23/*vs/platform/theme/common/colorRegistry*/], __M([1/*require*/,0/*exports*/,44/*vs/platform/registry/common/platform*/,32/*vs/base/common/color*/,385/*vs/nls!vs/platform/theme/common/colorRegistry*/]), function (require, exports, platform, color_1, nls) {
    /*---------------------------------------------------------------------------------------------
     *  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 });
    // color registry
    exports.Extensions = {
        ColorContribution: 'base.contributions.colors'
    };
    var colorPattern = '^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$';
    var colorPatternErrorMessage = nls.localize(0, null);
    var ColorRegistry = (function () {
        function ColorRegistry() {
            this.colorSchema = { type: 'object', description: nls.localize(1, null), properties: {}, additionalProperties: false };
            this.colorsById = {};
        }
        ColorRegistry.prototype.registerColor = function (id, defaults, description) {
            var colorContribution = { id: id, description: description, defaults: defaults };
            this.colorsById[id] = colorContribution;
            this.colorSchema.properties[id] = { type: 'string', description: description, format: 'color', pattern: colorPattern, patternErrorMessage: colorPatternErrorMessage };
            return id;
        };
        ColorRegistry.prototype.getColors = function () {
            var _this = this;
            return Object.keys(this.colorsById).map(function (id) { return _this.colorsById[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 null;
        };
        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) {
        return colorRegistry.registerColor(id, defaults, description);
    }
    exports.registerColor = registerColor;
    // ----- base colors
    exports.foreground = registerColor('foreground', { dark: '#CCCCCC', light: '#6C6C6C', hc: '#FFFFFF' }, nls.localize(2, null));
    exports.errorForeground = registerColor('errorForeground', { dark: '#F48771', light: '#A1260D', hc: '#F48771' }, nls.localize(3, null));
    exports.descriptionForeground = registerColor('descriptionForeground', { light: transparent(exports.foreground, 0.7), dark: transparent(exports.foreground, 0.7), hc: transparent(exports.foreground, 0.7) }, nls.localize(4, null));
    exports.focusBorder = registerColor('focusBorder', { dark: color_1.Color.fromHex('#0E639C').transparent(0.6), light: color_1.Color.fromHex('#007ACC').transparent(0.4), hc: '#F38518' }, nls.localize(5, null));
    exports.contrastBorder = registerColor('contrastBorder', { light: null, dark: null, hc: '#6FC3DF' }, nls.localize(6, null));
    exports.activeContrastBorder = registerColor('contrastActiveBorder', { light: null, dark: null, hc: exports.focusBorder }, nls.localize(7, null));
    exports.selectionBackground = registerColor('selection.background', { light: null, dark: null, hc: null }, nls.localize(8, null));
    // ------ text colors
    exports.textSeparatorForeground = registerColor('textSeparator.foreground', { light: '#0000002e', dark: '#ffffff2e', hc: color_1.Color.black }, nls.localize(9, null));
    exports.textLinkForeground = registerColor('textLink.foreground', { light: '#4080D0', dark: '#4080D0', hc: '#4080D0' }, nls.localize(10, null));
    exports.textLinkActiveForeground = registerColor('textLink.activeForeground', { light: '#4080D0', dark: '#4080D0', hc: '#4080D0' }, nls.localize(11, null));
    exports.textPreformatForeground = registerColor('textPreformat.foreground', { light: '#A31515', dark: '#D7BA7D', hc: '#D7BA7D' }, nls.localize(12, null));
    exports.textBlockQuoteBackground = registerColor('textBlockQuote.background', { light: '#7f7f7f1a', dark: '#7f7f7f1a', hc: null }, nls.localize(13, null));
    exports.textBlockQuoteBorder = registerColor('textBlockQuote.border', { light: '#007acc80', dark: '#007acc80', hc: color_1.Color.white }, nls.localize(14, null));
    exports.textCodeBlockBackground = registerColor('textCodeBlock.background', { light: '#dcdcdc66', dark: '#0a0a0a66', hc: color_1.Color.black }, nls.localize(15, null));
    // ----- widgets
    exports.widgetShadow = registerColor('widget.shadow', { dark: '#000000', light: '#A8A8A8', hc: null }, nls.localize(16, null));
    exports.inputBackground = registerColor('input.background', { dark: '#3C3C3C', light: color_1.Color.white, hc: color_1.Color.black }, nls.localize(17, null));
    exports.inputForeground = registerColor('input.foreground', { dark: exports.foreground, light: exports.foreground, hc: exports.foreground }, nls.localize(18, null));
    exports.inputBorder = registerColor('input.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(19, null));
    exports.inputActiveOptionBorder = registerColor('inputOption.activeBorder', { dark: '#007ACC', light: '#007ACC', hc: exports.activeContrastBorder }, nls.localize(20, null));
    exports.inputPlaceholderForeground = registerColor('input.placeholderForeground', { dark: null, light: null, hc: null }, nls.localize(21, null));
    exports.inputValidationInfoBackground = registerColor('inputValidation.infoBackground', { dark: '#063B49', light: '#D6ECF2', hc: color_1.Color.black }, nls.localize(22, null));
    exports.inputValidationInfoBorder = registerColor('inputValidation.infoBorder', { dark: '#007acc', light: '#007acc', hc: exports.contrastBorder }, nls.localize(23, null));
    exports.inputValidationWarningBackground = registerColor('inputValidation.warningBackground', { dark: '#352A05', light: '#F6F5D2', hc: color_1.Color.black }, nls.localize(24, null));
    exports.inputValidationWarningBorder = registerColor('inputValidation.warningBorder', { dark: '#B89500', light: '#B89500', hc: exports.contrastBorder }, nls.localize(25, null));
    exports.inputValidationErrorBackground = registerColor('inputValidation.errorBackground', { dark: '#5A1D1D', light: '#F2DEDE', hc: color_1.Color.black }, nls.localize(26, null));
    exports.inputValidationErrorBorder = registerColor('inputValidation.errorBorder', { dark: '#BE1100', light: '#BE1100', hc: exports.contrastBorder }, nls.localize(27, null));
    exports.selectBackground = registerColor('dropdown.background', { dark: '#3C3C3C', light: color_1.Color.white, hc: color_1.Color.black }, nls.localize(28, null));
    exports.selectForeground = registerColor('dropdown.foreground', { dark: '#F0F0F0', light: null, hc: color_1.Color.white }, nls.localize(29, null));
    exports.selectBorder = registerColor('dropdown.border', { dark: exports.selectBackground, light: '#CECECE', hc: exports.contrastBorder }, nls.localize(30, null));
    exports.listFocusBackground = registerColor('list.focusBackground', { dark: '#073655', light: '#DCEBFC', hc: null }, nls.localize(31, null));
    exports.listFocusForeground = registerColor('list.focusForeground', { dark: null, light: null, hc: null }, nls.localize(32, null));
    exports.listActiveSelectionBackground = registerColor('list.activeSelectionBackground', { dark: '#094771', light: '#3399FF', hc: null }, nls.localize(33, null));
    exports.listActiveSelectionForeground = registerColor('list.activeSelectionForeground', { dark: color_1.Color.white, light: color_1.Color.white, hc: null }, nls.localize(34, null));
    exports.listInactiveSelectionBackground = registerColor('list.inactiveSelectionBackground', { dark: '#3F3F46', light: '#CCCEDB', hc: null }, nls.localize(35, null));
    exports.listInactiveSelectionForeground = registerColor('list.inactiveSelectionForeground', { dark: null, light: null, hc: null }, nls.localize(36, null));
    exports.listInactiveFocusBackground = registerColor('list.inactiveFocusBackground', { dark: '#313135', light: '#d8dae6', hc: null }, nls.localize(37, null));
    exports.listInactiveFocusForeground = registerColor('list.inactiveFocusForeground', { dark: null, light: null, hc: null }, nls.localize(38, null));
    exports.listHoverBackground = registerColor('list.hoverBackground', { dark: '#2A2D2E', light: '#F0F0F0', hc: null }, nls.localize(39, null));
    exports.listHoverForeground = registerColor('list.hoverForeground', { dark: null, light: null, hc: null }, nls.localize(40, null));
    exports.listDropBackground = registerColor('list.dropBackground', { dark: exports.listFocusBackground, light: exports.listFocusBackground, hc: null }, nls.localize(41, null));
    exports.listHighlightForeground = registerColor('list.highlightForeground', { dark: '#0097fb', light: '#007acc', hc: exports.focusBorder }, nls.localize(42, null));
    exports.pickerGroupForeground = registerColor('pickerGroup.foreground', { dark: color_1.Color.fromHex('#0097FB').transparent(0.6), light: color_1.Color.fromHex('#007ACC').transparent(0.6), hc: color_1.Color.white }, nls.localize(43, null));
    exports.pickerGroupBorder = registerColor('pickerGroup.border', { dark: '#3F3F46', light: '#CCCEDB', hc: color_1.Color.white }, nls.localize(44, null));
    exports.buttonForeground = registerColor('button.foreground', { dark: color_1.Color.white, light: color_1.Color.white, hc: color_1.Color.white }, nls.localize(45, null));
    exports.buttonBackground = registerColor('button.background', { dark: '#0E639C', light: '#007ACC', hc: null }, nls.localize(46, null));
    exports.buttonHoverBackground = registerColor('button.hoverBackground', { dark: lighten(exports.buttonBackground, 0.2), light: darken(exports.buttonBackground, 0.2), hc: null }, nls.localize(47, null));
    exports.badgeBackground = registerColor('badge.background', { dark: '#4D4D4D', light: '#BEBEBE', hc: color_1.Color.black }, nls.localize(48, null));
    exports.badgeForeground = registerColor('badge.foreground', { dark: color_1.Color.white, light: color_1.Color.white, hc: color_1.Color.white }, nls.localize(49, null));
    exports.scrollbarShadow = registerColor('scrollbar.shadow', { dark: '#000000', light: '#DDDDDD', hc: null }, nls.localize(50, 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(51, 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(52, 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(53, null));
    exports.progressBarBackground = registerColor('progressBar.background', { dark: color_1.Color.fromHex('#0E70C0'), light: color_1.Color.fromHex('#0E70C0'), hc: exports.contrastBorder }, nls.localize(54, 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(55, null));
    /**
     * Editor foreground color.
     */
    exports.editorForeground = registerColor('editor.foreground', { light: '#333333', dark: '#BBBBBB', hc: color_1.Color.white }, nls.localize(56, null));
    /**
     * Editor widgets
     */
    exports.editorWidgetBackground = registerColor('editorWidget.background', { dark: '#2D2D30', light: '#EFEFF2', hc: '#0C141F' }, nls.localize(57, null));
    exports.editorWidgetBorder = registerColor('editorWidget.border', { dark: '#454545', light: '#C8C8C8', hc: exports.contrastBorder }, nls.localize(58, null));
    /**
     * Editor selection colors.
     */
    exports.editorSelectionBackground = registerColor('editor.selectionBackground', { light: '#ADD6FF', dark: '#264F78', hc: '#f3f518' }, nls.localize(59, null));
    exports.editorSelectionForeground = registerColor('editor.selectionForeground', { light: null, dark: null, hc: '#000000' }, nls.localize(60, 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(61, null));
    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(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));
    exports.editorFindRangeHighlight = registerColor('editor.findRangeHighlightBackground', { dark: '#3a3d4166', light: '#b4b4b44d', hc: null }, nls.localize(65, null));
    /**
     * Editor hover
     */
    exports.editorHoverHighlight = registerColor('editor.hoverHighlightBackground', { light: '#ADD6FF26', dark: '#264f7840', hc: '#ADD6FF26' }, nls.localize(66, null));
    exports.editorHoverBackground = registerColor('editorHoverWidget.background', { light: exports.editorWidgetBackground, dark: exports.editorWidgetBackground, hc: exports.editorWidgetBackground }, nls.localize(67, null));
    exports.editorHoverBorder = registerColor('editorHoverWidget.border', { light: exports.editorWidgetBorder, dark: exports.editorWidgetBorder, hc: exports.editorWidgetBorder }, nls.localize(68, null));
    /**
     * Editor link colors
     */
    exports.editorActiveLinkForeground = registerColor('editorLink.activeForeground', { dark: '#4E94CE', light: color_1.Color.blue, hc: color_1.Color.cyan }, nls.localize(69, null));
    /**
     * Diff Editor Colors
     */
    exports.defaultInsertColor = color_1.Color.fromRGBA(new color_1.RGBA(155, 185, 85, 255 * 0.2));
    exports.defaultRemoveColor = color_1.Color.fromRGBA(new color_1.RGBA(255, 0, 0, 255 * 0.2));
    exports.diffInserted = registerColor('diffEditor.insertedTextBackground', { dark: exports.defaultInsertColor, light: exports.defaultInsertColor, hc: null }, nls.localize(70, null));
    exports.diffRemoved = registerColor('diffEditor.removedTextBackground', { dark: exports.defaultRemoveColor, light: exports.defaultRemoveColor, hc: null }, nls.localize(71, null));
    exports.diffInsertedOutline = registerColor('diffEditor.insertedTextBorder', { dark: null, light: null, hc: '#33ff2eff' }, nls.localize(72, null));
    exports.diffRemovedOutline = registerColor('diffEditor.removedTextBorder', { dark: null, light: null, hc: '#FF008F' }, nls.localize(73, null));
    /**
     * Merge-conflict colors
     */
    var headerTransparency = 0.5;
    var currentBaseColor = color_1.Color.fromHex('#40C8AE').transparent(headerTransparency);
    var incomingBaseColor = color_1.Color.fromHex('#40A6FF').transparent(headerTransparency);
    var commonBaseColor = color_1.Color.fromHex('#606060').transparent(0.4);
    var contentTransparency = 0.4;
    var rulerTransparency = 1;
    exports.mergeCurrentHeaderBackground = registerColor('merge.currentHeaderBackground', { dark: currentBaseColor, light: currentBaseColor, hc: null }, nls.localize(74, null));
    exports.mergeCurrentContentBackground = registerColor('merge.currentContentBackground', { dark: transparent(exports.mergeCurrentHeaderBackground, contentTransparency), light: transparent(exports.mergeCurrentHeaderBackground, contentTransparency), hc: transparent(exports.mergeCurrentHeaderBackground, contentTransparency) }, nls.localize(75, null));
    exports.mergeIncomingHeaderBackground = registerColor('merge.incomingHeaderBackground', { dark: incomingBaseColor, light: incomingBaseColor, hc: null }, nls.localize(76, null));
    exports.mergeIncomingContentBackground = registerColor('merge.incomingContentBackground', { dark: transparent(exports.mergeIncomingHeaderBackground, contentTransparency), light: transparent(exports.mergeIncomingHeaderBackground, contentTransparency), hc: transparent(exports.mergeIncomingHeaderBackground, contentTransparency) }, nls.localize(77, null));
    exports.mergeCommonHeaderBackground = registerColor('merge.commonHeaderBackground', { dark: commonBaseColor, light: commonBaseColor, hc: null }, nls.localize(78, null));
    exports.mergeCommonContentBackground = registerColor('merge.commonContentBackground', { dark: transparent(exports.mergeCommonHeaderBackground, contentTransparency), light: transparent(exports.mergeCommonHeaderBackground, contentTransparency), hc: transparent(exports.mergeCommonHeaderBackground, contentTransparency) }, nls.localize(79, null));
    exports.mergeBorder = registerColor('merge.border', { dark: null, light: null, hc: '#C3DF6F' }, nls.localize(80, null));
    exports.overviewRulerCurrentContentForeground = registerColor('editorOverviewRuler.currentContentForeground', { dark: transparent(exports.mergeCurrentHeaderBackground, rulerTransparency), light: transparent(exports.mergeCurrentHeaderBackground, rulerTransparency), hc: exports.mergeBorder }, nls.localize(81, null));
    exports.overviewRulerIncomingContentForeground = registerColor('editorOverviewRuler.incomingContentForeground', { dark: transparent(exports.mergeIncomingHeaderBackground, rulerTransparency), light: transparent(exports.mergeIncomingHeaderBackground, rulerTransparency), hc: exports.mergeBorder }, nls.localize(82, null));
    exports.overviewRulerCommonContentForeground = registerColor('editorOverviewRuler.commonContentForeground', { dark: transparent(exports.mergeCommonHeaderBackground, rulerTransparency), light: transparent(exports.mergeCommonHeaderBackground, rulerTransparency), hc: exports.mergeBorder }, nls.localize(83, null));
    // ----- color functions
    function darken(colorValue, factor) {
        return function (theme) {
            var color = resolveColorValue(colorValue, theme);
            if (color) {
                return color.darken(factor);
            }
            return null;
        };
    }
    exports.darken = darken;
    function lighten(colorValue, factor) {
        return function (theme) {
            var color = resolveColorValue(colorValue, theme);
            if (color) {
                return color.lighten(factor);
            }
            return null;
        };
    }
    exports.lighten = lighten;
    function transparent(colorValue, factor) {
        return function (theme) {
            var color = resolveColorValue(colorValue, theme);
            if (color) {
                return color.transparent(factor);
            }
            return null;
        };
    }
    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 null;
        };
    }
    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 null;
        };
    }
    // ----- implementation
    /**
     * @param colorValue Resolve a color value in the context of a theme
     */
    function resolveColorValue(colorValue, theme) {
        if (colorValue === null) {
            return null;
        }
        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 null;
    }
});
// 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[137/*vs/platform/theme/common/styler*/], __M([1/*require*/,0/*exports*/,23/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, colorRegistry_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function attachStyler(themeService, optionsMapping, widgetOrCallback) {
        function applyStyles(theme) {
            var styles = Object.create(null);
            for (var key in optionsMapping) {
                var value = optionsMapping[key];
                if (typeof value === 'string') {
                    styles[key] = theme.getColor(value);
                }
                else if (typeof value === 'function') {
                    styles[key] = value(theme);
                }
            }
            if (typeof widgetOrCallback === 'function') {
                widgetOrCallback(styles);
            }
            else {
                widgetOrCallback.style(styles);
            }
        }
        applyStyles(themeService.getTheme());
        return themeService.onThemeChange(applyStyles);
    }
    exports.attachStyler = attachStyler;
    function attachCheckboxStyler(widget, themeService, style) {
        return attachStyler(themeService, {
            inputActiveOptionBorder: (style && style.inputActiveOptionBorderColor) || colorRegistry_1.inputActiveOptionBorder
        }, widget);
    }
    exports.attachCheckboxStyler = attachCheckboxStyler;
    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 attachInputBoxStyler(widget, themeService, style) {
        return attachStyler(themeService, {
            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,
            inputValidationWarningBorder: (style && style.inputValidationWarningBorder) || colorRegistry_1.inputValidationWarningBorder,
            inputValidationWarningBackground: (style && style.inputValidationWarningBackground) || colorRegistry_1.inputValidationWarningBackground,
            inputValidationErrorBorder: (style && style.inputValidationErrorBorder) || colorRegistry_1.inputValidationErrorBorder,
            inputValidationErrorBackground: (style && style.inputValidationErrorBackground) || colorRegistry_1.inputValidationErrorBackground
        }, widget);
    }
    exports.attachInputBoxStyler = attachInputBoxStyler;
    function attachSelectBoxStyler(widget, themeService, style) {
        return attachStyler(themeService, {
            selectBackground: (style && style.selectBackground) || colorRegistry_1.selectBackground,
            selectForeground: (style && style.selectForeground) || colorRegistry_1.selectForeground,
            selectBorder: (style && style.selectBorder) || colorRegistry_1.selectBorder
        }, widget);
    }
    exports.attachSelectBoxStyler = attachSelectBoxStyler;
    function attachFindInputBoxStyler(widget, themeService, style) {
        return attachStyler(themeService, {
            inputBackground: (style && style.inputBackground) || colorRegistry_1.inputBackground,
            inputForeground: (style && style.inputForeground) || colorRegistry_1.inputForeground,
            inputBorder: (style && style.inputBorder) || colorRegistry_1.inputBorder,
            inputActiveOptionBorder: (style && style.inputActiveOptionBorder) || colorRegistry_1.inputActiveOptionBorder,
            inputValidationInfoBorder: (style && style.inputValidationInfoBorder) || colorRegistry_1.inputValidationInfoBorder,
            inputValidationInfoBackground: (style && style.inputValidationInfoBackground) || colorRegistry_1.inputValidationInfoBackground,
            inputValidationWarningBorder: (style && style.inputValidationWarningBorder) || colorRegistry_1.inputValidationWarningBorder,
            inputValidationWarningBackground: (style && style.inputValidationWarningBackground) || colorRegistry_1.inputValidationWarningBackground,
            inputValidationErrorBorder: (style && style.inputValidationErrorBorder) || colorRegistry_1.inputValidationErrorBorder,
            inputValidationErrorBackground: (style && style.inputValidationErrorBackground) || colorRegistry_1.inputValidationErrorBackground
        }, widget);
    }
    exports.attachFindInputBoxStyler = attachFindInputBoxStyler;
    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,
            inputValidationWarningBorder: (style && style.inputValidationWarningBorder) || colorRegistry_1.inputValidationWarningBorder,
            inputValidationWarningBackground: (style && style.inputValidationWarningBackground) || colorRegistry_1.inputValidationWarningBackground,
            inputValidationErrorBorder: (style && style.inputValidationErrorBorder) || colorRegistry_1.inputValidationErrorBorder,
            inputValidationErrorBackground: (style && style.inputValidationErrorBackground) || colorRegistry_1.inputValidationErrorBackground,
            listFocusBackground: (style && style.listFocusBackground) || colorRegistry_1.listFocusBackground,
            listFocusForeground: (style && style.listFocusForeground) || colorRegistry_1.listFocusForeground,
            listActiveSelectionBackground: (style && style.listActiveSelectionBackground) || colorRegistry_1.lighten(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,
            listInactiveFocusForeground: (style && style.listInactiveFocusForeground) || colorRegistry_1.listInactiveFocusForeground,
            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, style) {
        return attachStyler(themeService, {
            listFocusBackground: (style && style.listFocusBackground) || colorRegistry_1.listFocusBackground,
            listFocusForeground: (style && style.listFocusForeground) || colorRegistry_1.listFocusForeground,
            listActiveSelectionBackground: (style && style.listActiveSelectionBackground) || colorRegistry_1.lighten(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,
            listInactiveFocusForeground: (style && style.listInactiveFocusForeground) || colorRegistry_1.listInactiveFocusForeground,
            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,
            listInactiveFocusOutline: style && style.listInactiveFocusOutline // not defined by default, only opt-in
        }, widget);
    }
    exports.attachListStyler = attachListStyler;
    function attachButtonStyler(widget, themeService, style) {
        return attachStyler(themeService, {
            buttonForeground: (style && style.buttonForeground) || colorRegistry_1.buttonForeground,
            buttonBackground: (style && style.buttonBackground) || colorRegistry_1.buttonBackground,
            buttonHoverBackground: (style && style.buttonHoverBackground) || colorRegistry_1.buttonHoverBackground,
            buttonBorder: colorRegistry_1.contrastBorder
        }, widget);
    }
    exports.attachButtonStyler = attachButtonStyler;
    function attachProgressBarStyler(widget, themeService, style) {
        return attachStyler(themeService, {
            progressBarBackground: (style && style.progressBarBackground) || colorRegistry_1.progressBarBackground
        }, widget);
    }
    exports.attachProgressBarStyler = attachProgressBarStyler;
    function attachStylerCallback(themeService, colors, callback) {
        return attachStyler(themeService, colors, callback);
    }
    exports.attachStylerCallback = attachStylerCallback;
});

define(__m[483/*vs/editor/standalone/browser/quickOpen/quickOpenEditorWidget*/], __M([1/*require*/,0/*exports*/,52/*vs/base/browser/builder*/,301/*vs/base/parts/quickopen/browser/quickOpenWidget*/,25/*vs/editor/browser/editorBrowser*/,137/*vs/platform/theme/common/styler*/]), function (require, exports, builder_1, quickOpenWidget_1, editorBrowser_1, styler_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var QuickOpenEditorWidget = (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 = builder_1.$().div().getHTMLElement();
            this.quickOpenWidget = new quickOpenWidget_1.QuickOpenWidget(this.domNode, {
                onOk: onOk,
                onCancel: onCancel,
                onType: onType
            }, {
                inputPlaceHolder: null,
                inputAriaLabel: configuration.inputAriaLabel,
                keyboardSupport: true
            }, null);
            this.styler = styler_1.attachQuickOpenStyler(this.quickOpenWidget, this.themeService);
            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.isVisible = function () {
            return this.visible;
        };
        QuickOpenEditorWidget.prototype.show = function (value) {
            this.visible = true;
            var editorLayout = this.codeEditor.getLayoutInfo();
            if (editorLayout) {
                this.quickOpenWidget.layout(new builder_1.Dimension(editorLayout.width, editorLayout.height));
            }
            this.quickOpenWidget.show(value);
            this.codeEditor.layoutOverlayWidget(this);
        };
        QuickOpenEditorWidget.prototype.hide = function () {
            this.visible = false;
            this.quickOpenWidget.hide();
            this.codeEditor.layoutOverlayWidget(this);
        };
        QuickOpenEditorWidget.prototype.getPosition = function () {
            if (this.visible) {
                return {
                    preference: editorBrowser_1.OverlayWidgetPositionPreference.TOP_CENTER
                };
            }
            return null;
        };
        QuickOpenEditorWidget.ID = 'editor.contrib.quickOpenEditorWidget';
        return QuickOpenEditorWidget;
    }());
    exports.QuickOpenEditorWidget = QuickOpenEditorWidget;
});

define(__m[14/*vs/platform/theme/common/themeService*/], __M([1/*require*/,0/*exports*/,16/*vs/platform/instantiation/common/instantiation*/,44/*vs/platform/registry/common/platform*/,11/*vs/base/common/event*/]), function (require, exports, instantiation_1, platform, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IThemeService = instantiation_1.createDecorator('themeService');
    // base themes
    exports.DARK = 'dark';
    exports.LIGHT = 'light';
    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 = (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 {
                dispose: function () {
                    var idx = _this.themingParticipants.indexOf(participant);
                    _this.themingParticipants.splice(idx, 1);
                }
            };
        };
        Object.defineProperty(ThemingRegistry.prototype, "onThemingParticipantAdded", {
            get: function () {
                return this.onThemingParticipantAddedEmitter.event;
            },
            enumerable: true,
            configurable: true
        });
        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;
    /**
     * Tag function for strings containing css rules
     */
    function cssRule(literals) {
        var placeholders = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            placeholders[_i - 1] = arguments[_i];
        }
        var result = '';
        for (var i = 0; i < placeholders.length; i++) {
            result += literals[i];
            var placeholder = placeholders[i];
            if (placeholder === null) {
                result += 'transparent';
            }
            else {
                result += placeholder.toString();
            }
        }
        result += literals[literals.length - 1];
        return result;
    }
    exports.cssRule = cssRule;
});




















define(__m[485/*vs/editor/browser/services/codeEditorServiceImpl*/], __M([1/*require*/,0/*exports*/,9/*vs/base/common/strings*/,24/*vs/base/common/uri*/,4/*vs/base/browser/dom*/,20/*vs/editor/common/editorCommon*/,210/*vs/editor/common/services/abstractCodeEditorService*/,3/*vs/base/common/lifecycle*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, strings, uri_1, dom, editorCommon_1, abstractCodeEditorService_1, lifecycle_1, themeService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CodeEditorServiceImpl = (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
                };
                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 = (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 = (function () {
        function DecorationTypeOptionsProvider(themeService, providerArgs) {
            var _this = this;
            this.refCount = 0;
            this._disposables = [];
            var createCSSRules = function (type) {
                var rules = new DecorationCSSRules(type, providerArgs, themeService);
                if (rules.hasContent) {
                    _this._disposables.push(rules);
                    return rules.className;
                }
                return void 0;
            };
            this.className = createCSSRules(0 /* ClassName */);
            this.inlineClassName = createCSSRules(1 /* InlineClassName */);
            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 || editorCommon_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;',
        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};',
        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 = (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;
            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();
                });
            }
        }
        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, "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, ['textDecoration', 'cursor', 'color', 'letterSpacing'], cssTextArr);
            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 === 'string') {
                    cssTextArr.push(strings.format(_CSS_MAP.contentIconPath, uri_1.default.file(opts.contentIconPath).toString().replace(/'/g, '%27')));
                }
                else if (opts.contentIconPath instanceof uri_1.default) {
                    cssTextArr.push(strings.format(_CSS_MAP.contentIconPath, 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, ['textDecoration', 'color', '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') {
                if (typeof opts.gutterIconPath === 'string') {
                    cssTextArr.push(strings.format(_CSS_MAP.gutterIconPath, uri_1.default.file(opts.gutterIconPath).toString()));
                }
                else {
                    cssTextArr.push(strings.format(_CSS_MAP.gutterIconPath, 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 ModelDecorationCSSRuleType;
    (function (ModelDecorationCSSRuleType) {
        ModelDecorationCSSRuleType[ModelDecorationCSSRuleType["ClassName"] = 0] = "ClassName";
        ModelDecorationCSSRuleType[ModelDecorationCSSRuleType["InlineClassName"] = 1] = "InlineClassName";
        ModelDecorationCSSRuleType[ModelDecorationCSSRuleType["GlyphMarginClassName"] = 2] = "GlyphMarginClassName";
        ModelDecorationCSSRuleType[ModelDecorationCSSRuleType["BeforeContentClassName"] = 3] = "BeforeContentClassName";
        ModelDecorationCSSRuleType[ModelDecorationCSSRuleType["AfterContentClassName"] = 4] = "AfterContentClassName";
    })(ModelDecorationCSSRuleType || (ModelDecorationCSSRuleType = {}));
    var CSSNameHelper = (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;
    }());
});











define(__m[486/*vs/editor/browser/viewParts/editorScrollbar/editorScrollbar*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,63/*vs/base/browser/ui/scrollbar/scrollableElement*/,35/*vs/editor/browser/view/viewPart*/,27/*vs/base/browser/fastDomNode*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, dom, scrollableElement_1, viewPart_1, fastDomNode_1, themeService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var EditorScrollbar = (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,
            };
            _this.scrollbar = _this._register(new scrollableElement_1.ScrollableElement(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.getScrollTop() + deltaTop;
                        domNode.scrollTop = 0;
                    }
                }
                if (lookAtScrollLeft) {
                    var deltaLeft = domNode.scrollLeft;
                    if (deltaLeft) {
                        newScrollPosition.scrollLeft = _this._context.viewLayout.getScrollLeft() + deltaLeft;
                        domNode.scrollLeft = 0;
                    }
                }
                _this._context.viewLayout.setScrollPosition(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); }));
            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);
            this.scrollbarDomNode.setWidth(layoutInfo.contentWidth + layoutInfo.minimapWidth);
            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);
        };
        EditorScrollbar.prototype.delegateSliderMouseDown = function (e, onDragFinished) {
            this.scrollbar.delegateSliderMouseDown(e, onDragFinished);
        };
        // --- 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
                };
                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;
});











define(__m[185/*vs/editor/browser/viewParts/lines/viewLine*/], __M([1/*require*/,0/*exports*/,28/*vs/base/browser/browser*/,15/*vs/base/common/platform*/,9/*vs/base/common/strings*/,27/*vs/base/browser/fastDomNode*/,138/*vs/editor/common/viewLayout/lineDecorations*/,106/*vs/editor/common/viewLayout/viewLineRenderer*/,214/*vs/editor/browser/viewParts/lines/rangeUtil*/,78/*vs/editor/common/view/renderingContext*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, browser, platform, strings, fastDomNode_1, lineDecorations_1, viewLineRenderer_1, rangeUtil_1, renderingContext_1, themeService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var 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 = (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 = (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.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.lineHeight === other.lineHeight
                && this.stopRenderingLineAfter === other.stopRenderingLineAfter
                && this.fontLigatures === other.fontLigatures);
        };
        return ViewLineOptions;
    }());
    exports.ViewLineOptions = ViewLineOptions;
    var ViewLine = (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) {
            if (this._isMaybeInvalid === false) {
                // it appears that nothing relevant has changed
                return null;
            }
            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, len = selections.length; i < len; i++) {
                    var selection = selections[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', false));
                    }
                }
            }
            var renderLineInput = new viewLineRenderer_1.RenderLineInput(options.useMonospaceOptimizations, lineData.content, lineData.mightContainRTL, 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 null;
            }
            var output = viewLineRenderer_1.renderViewLine(renderLineInput);
            var renderedViewLine = null;
            if (canUseFastRenderedViewLine && options.useMonospaceOptimizations && !output.containsForeignElements) {
                var isRegularASCII = true;
                if (lineData.mightContainNonBasicASCII) {
                    isRegularASCII = strings.isBasicASCII(lineData.content);
                }
                if (isRegularASCII && lineData.content.length < 1000) {
                    // 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...
                    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 "<div style=\"top:" + deltaTop + "px;height:" + this._options.lineHeight + "px;\" class=\"" + ViewLine.CLASS_NAME + "\">" + output.html + "</div>";
        };
        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.getVisibleRangesForRange = function (startColumn, endColumn, context) {
            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));
            return this._renderedViewLine.getVisibleRangesForRange(startColumn, endColumn, context);
        };
        ViewLine.prototype.getColumnOfNodeOffset = function (lineNumber, spanNode, offset) {
            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 = (function () {
        function FastRenderedViewLine(domNode, renderLineInput, characterMapping) {
            this.domNode = domNode;
            this.input = renderLineInput;
            this._characterMapping = characterMapping;
            this._charWidth = renderLineInput.spaceWidth;
            this._charOffset = null;
        }
        FastRenderedViewLine._createCharOffset = function (characterMapping) {
            var partLengths = characterMapping.getPartLengths();
            var len = characterMapping.length;
            var result = new Uint32Array(len);
            var currentPartIndex = 0;
            var currentPartOffset = 0;
            for (var ch = 0; ch < len; ch++) {
                var partData = characterMapping.charOffsetToPartData(ch);
                var partIndex = viewLineRenderer_1.CharacterMapping.getPartIndex(partData);
                var charIndex = viewLineRenderer_1.CharacterMapping.getCharIndex(partData);
                while (currentPartIndex < partIndex) {
                    currentPartOffset += partLengths[currentPartIndex];
                    currentPartIndex++;
                }
                result[ch] = currentPartOffset + charIndex;
            }
            return result;
        };
        FastRenderedViewLine.prototype._getOrCreateCharOffset = function () {
            if (this._charOffset === null) {
                this._charOffset = FastRenderedViewLine._createCharOffset(this._characterMapping);
            }
            return this._charOffset;
        };
        FastRenderedViewLine.prototype.getWidth = function () {
            var charOffset = this._getOrCreateCharOffset();
            return this._getCharPosition(charOffset.length);
        };
        FastRenderedViewLine.prototype.getVisibleRangesForRange = function (startColumn, endColumn, context) {
            startColumn = startColumn | 0; // @perf
            endColumn = endColumn | 0; // @perf
            var stopRenderingLineAfter = this.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;
            }
            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._getOrCreateCharOffset();
            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 = (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(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;
        };
        /**
         * Visible ranges for a model range
         */
        RenderedViewLine.prototype.getVisibleRangesForRange = function (startColumn, endColumn, context) {
            startColumn = startColumn | 0; // @perf
            endColumn = endColumn | 0; // @perf
            var stopRenderingLineAfter = this.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;
            }
            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) {
                    // We can assume the line is really empty
                    return 0;
                }
            }
            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) {
                // 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 = (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)
            // This is an attempt to patch things up
            // Find position of previous column
            var beforeEndPixelOffset = this._readPixelOffset(endColumn - 1, context);
            // Find position of last column
            var endPixelOffset = this._readPixelOffset(endColumn, context);
            if (beforeEndPixelOffset !== -1 && endPixelOffset !== -1) {
                var isLTR = (beforeEndPixelOffset <= endPixelOffset);
                var lastRange = output[output.length - 1];
                if (isLTR && 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);
    }
});











define(__m[186/*vs/editor/browser/controller/mouseTarget*/], __M([1/*require*/,0/*exports*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,25/*vs/editor/browser/editorBrowser*/,114/*vs/editor/browser/editorDom*/,28/*vs/base/browser/browser*/,35/*vs/editor/browser/view/viewPart*/,185/*vs/editor/browser/viewParts/lines/viewLine*/]), function (require, exports, position_1, range_1, editorBrowser_1, editorDom_1, browser, viewPart_1, viewLine_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MouseTarget = (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 === editorBrowser_1.MouseTargetType.TEXTAREA) {
                return 'TEXTAREA';
            }
            if (type === editorBrowser_1.MouseTargetType.GUTTER_GLYPH_MARGIN) {
                return 'GUTTER_GLYPH_MARGIN';
            }
            if (type === editorBrowser_1.MouseTargetType.GUTTER_LINE_NUMBERS) {
                return 'GUTTER_LINE_NUMBERS';
            }
            if (type === editorBrowser_1.MouseTargetType.GUTTER_LINE_DECORATIONS) {
                return 'GUTTER_LINE_DECORATIONS';
            }
            if (type === editorBrowser_1.MouseTargetType.GUTTER_VIEW_ZONE) {
                return 'GUTTER_VIEW_ZONE';
            }
            if (type === editorBrowser_1.MouseTargetType.CONTENT_TEXT) {
                return 'CONTENT_TEXT';
            }
            if (type === editorBrowser_1.MouseTargetType.CONTENT_EMPTY) {
                return 'CONTENT_EMPTY';
            }
            if (type === editorBrowser_1.MouseTargetType.CONTENT_VIEW_ZONE) {
                return 'CONTENT_VIEW_ZONE';
            }
            if (type === editorBrowser_1.MouseTargetType.CONTENT_WIDGET) {
                return 'CONTENT_WIDGET';
            }
            if (type === editorBrowser_1.MouseTargetType.OVERVIEW_RULER) {
                return 'OVERVIEW_RULER';
            }
            if (type === editorBrowser_1.MouseTargetType.SCROLLBAR) {
                return 'SCROLLBAR';
            }
            if (type === editorBrowser_1.MouseTargetType.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 = (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.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 = (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) {
            // The target is either a view zone or the empty space after the last view-line
            var viewZoneWhitespace = this._context.viewLayout.getWhitespaceAtVerticalOffset(mouseVerticalOffset);
            if (viewZoneWhitespace) {
                var viewZoneMiddle = viewZoneWhitespace.verticalOffset + viewZoneWhitespace.height / 2, lineCount = this._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, this._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.getScrollTop = function () {
            return this._context.viewLayout.getScrollTop();
        };
        HitTestContext.prototype.getScrollLeft = function () {
            return this._context.viewLayout.getScrollLeft();
        };
        return HitTestContext;
    }());
    var BareHitTestRequest = (function () {
        function BareHitTestRequest(ctx, editorPos, pos) {
            this.editorPos = editorPos;
            this.pos = pos;
            this.mouseVerticalOffset = Math.max(0, ctx.getScrollTop() + pos.y - editorPos.y);
            this.mouseContentHorizontalOffset = ctx.getScrollLeft() + pos.x - editorPos.x - ctx.layoutInfo.contentLeft;
            this.isInMarginArea = (pos.x - editorPos.x < ctx.layoutInfo.contentLeft);
            this.isInContentArea = !this.isInMarginArea;
            this.mouseColumn = Math.max(0, MouseTargetFactory._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth));
        }
        return BareHitTestRequest;
    }());
    var HitTestRequest = (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 MouseTargetFactory = (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(editorBrowser_1.MouseTargetType.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(editorBrowser_1.MouseTargetType.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);
            }
            var result = null;
            result = result || MouseTargetFactory._hitTestContentWidget(ctx, request);
            result = result || MouseTargetFactory._hitTestOverlayWidget(ctx, request);
            result = result || MouseTargetFactory._hitTestMinimap(ctx, request);
            result = result || MouseTargetFactory._hitTestScrollbarSlider(ctx, request);
            result = result || MouseTargetFactory._hitTestViewZone(ctx, request);
            result = result || MouseTargetFactory._hitTestMargin(ctx, request);
            result = result || MouseTargetFactory._hitTestViewCursor(ctx, request);
            result = result || MouseTargetFactory._hitTestTextArea(ctx, request);
            result = result || MouseTargetFactory._hitTestViewLines(ctx, request, domHitTestExecuted);
            result = result || MouseTargetFactory._hitTestScrollbar(ctx, request);
            return (result || request.fulfill(editorBrowser_1.MouseTargetType.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(editorBrowser_1.MouseTargetType.CONTENT_WIDGET, null, null, widgetId);
                }
                else {
                    return request.fulfill(editorBrowser_1.MouseTargetType.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(editorBrowser_1.MouseTargetType.OVERLAY_WIDGET, null, null, widgetId);
                }
                else {
                    return request.fulfill(editorBrowser_1.MouseTargetType.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, len = lastViewCursorsRenderData.length; i < len; i++) {
                    var d = lastViewCursorsRenderData[i];
                    if (request.target === d.domNode) {
                        return request.fulfill(editorBrowser_1.MouseTargetType.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 i = 0, len = lastViewCursorsRenderData.length; i < len; i++) {
                    var d = lastViewCursorsRenderData[i];
                    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(editorBrowser_1.MouseTargetType.CONTENT_TEXT, d.position);
                    }
                }
            }
            return null;
        };
        MouseTargetFactory._hitTestViewZone = function (ctx, request) {
            var viewZoneData = ctx.getZoneAtCoord(request.mouseVerticalOffset);
            if (viewZoneData) {
                var mouseTargetType = (request.isInContentArea ? editorBrowser_1.MouseTargetType.CONTENT_VIEW_ZONE : editorBrowser_1.MouseTargetType.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(editorBrowser_1.MouseTargetType.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);
                if (offset <= ctx.layoutInfo.glyphMarginWidth) {
                    // On the glyph margin
                    return request.fulfill(editorBrowser_1.MouseTargetType.GUTTER_GLYPH_MARGIN, pos, res.range, res.isAfterLines);
                }
                offset -= ctx.layoutInfo.glyphMarginWidth;
                if (offset <= ctx.layoutInfo.lineNumbersWidth) {
                    // On the line numbers
                    return request.fulfill(editorBrowser_1.MouseTargetType.GUTTER_LINE_NUMBERS, pos, res.range, res.isAfterLines);
                }
                offset -= ctx.layoutInfo.lineNumbersWidth;
                // On the line decorations
                return request.fulfill(editorBrowser_1.MouseTargetType.GUTTER_LINE_DECORATIONS, pos, res.range, res.isAfterLines);
            }
            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(editorBrowser_1.MouseTargetType.CONTENT_EMPTY, new position_1.Position(lineCount, maxLineColumn));
            }
            if (domHitTestExecuted) {
                // We have already executed hit test...
                return request.fulfill(editorBrowser_1.MouseTargetType.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(editorBrowser_1.MouseTargetType.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(editorBrowser_1.MouseTargetType.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(editorBrowser_1.MouseTargetType.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.getScrollLeft() + 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
                    return request.fulfill(editorBrowser_1.MouseTargetType.CONTENT_EMPTY, new position_1.Position(lineNumber, ctx.model.getLineMaxColumn(lineNumber)));
                }
                return request.fulfill(editorBrowser_1.MouseTargetType.CONTENT_EMPTY, pos);
            }
            var visibleRange = ctx.visibleRangeForPosition2(lineNumber, column);
            if (!visibleRange) {
                return request.fulfill(editorBrowser_1.MouseTargetType.UNKNOWN, pos);
            }
            var columnHorizontalOffset = visibleRange.left;
            if (request.mouseContentHorizontalOffset === columnHorizontalOffset) {
                return request.fulfill(editorBrowser_1.MouseTargetType.CONTENT_TEXT, pos);
            }
            var mouseIsBetween;
            if (column > 1) {
                var prevColumnHorizontalOffset = visibleRange.left;
                mouseIsBetween = false;
                mouseIsBetween = mouseIsBetween || (prevColumnHorizontalOffset < request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset < columnHorizontalOffset); // LTR case
                mouseIsBetween = mouseIsBetween || (columnHorizontalOffset < request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset < prevColumnHorizontalOffset); // RTL case
                if (mouseIsBetween) {
                    var rng = new range_1.Range(lineNumber, column, lineNumber, column - 1);
                    return request.fulfill(editorBrowser_1.MouseTargetType.CONTENT_TEXT, pos, rng);
                }
            }
            var lineMaxColumn = ctx.model.getLineMaxColumn(lineNumber);
            if (column < lineMaxColumn) {
                var nextColumnVisibleRange = ctx.visibleRangeForPosition2(lineNumber, column + 1);
                if (nextColumnVisibleRange) {
                    var nextColumnHorizontalOffset = nextColumnVisibleRange.left;
                    mouseIsBetween = false;
                    mouseIsBetween = mouseIsBetween || (columnHorizontalOffset < request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset < nextColumnHorizontalOffset); // LTR case
                    mouseIsBetween = mouseIsBetween || (nextColumnHorizontalOffset < request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset < columnHorizontalOffset); // RTL case
                    if (mouseIsBetween) {
                        var rng = new range_1.Range(lineNumber, column, lineNumber, column + 1);
                        return request.fulfill(editorBrowser_1.MouseTargetType.CONTENT_TEXT, pos, rng);
                    }
                }
            }
            return request.fulfill(editorBrowser_1.MouseTargetType.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;
            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;
});











define(__m[489/*vs/editor/browser/controller/mouseHandler*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,15/*vs/base/common/platform*/,28/*vs/base/browser/browser*/,4/*vs/base/browser/dom*/,12/*vs/editor/common/core/position*/,22/*vs/editor/common/core/selection*/,82/*vs/editor/common/viewModel/viewEventHandler*/,186/*vs/editor/browser/controller/mouseTarget*/,25/*vs/editor/browser/editorBrowser*/,18/*vs/base/common/async*/,114/*vs/editor/browser/editorDom*/,47/*vs/base/browser/mouseEvent*/,135/*vs/editor/common/config/editorZoom*/]), function (require, exports, lifecycle_1, platform, browser, dom, position_1, selection_1, viewEventHandler_1, mouseTarget_1, editorBrowser, async_1, editorDom_1, mouseEvent_1, editorZoom_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * 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 = (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) {
                if (!_this._context.configuration.editor.viewInfo.mouseWheelZoom) {
                    return;
                }
                var e = new mouseEvent_1.StandardMouseWheelEvent(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._register(dom.addDisposableListener(_this.viewHelper.viewDomNode, 'DOMMouseScroll', 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 === editorBrowser.MouseTargetType.CONTENT_TEXT || t.type === editorBrowser.MouseTargetType.CONTENT_EMPTY);
            var targetIsGutter = (t.type === editorBrowser.MouseTargetType.GUTTER_GLYPH_MARGIN || t.type === editorBrowser.MouseTargetType.GUTTER_LINE_NUMBERS || t.type === editorBrowser.MouseTargetType.GUTTER_LINE_DECORATIONS);
            var targetIsLineNumbers = (t.type === editorBrowser.MouseTargetType.GUTTER_LINE_NUMBERS);
            var selectOnLineNumbers = this._context.configuration.editor.viewInfo.selectOnLineNumbers;
            var targetIsViewZone = (t.type === editorBrowser.MouseTargetType.CONTENT_VIEW_ZONE || t.type === editorBrowser.MouseTargetType.GUTTER_VIEW_ZONE);
            var targetIsWidget = (t.type === editorBrowser.MouseTargetType.CONTENT_WIDGET);
            var shouldHandle = e.leftButton;
            if (platform.isMacintosh && 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 = (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 === editorBrowser.MouseTargetType.GUTTER_LINE_NUMBERS);
            this._mouseState.setModifiers(e);
            var position = this._findMousePosition(e, true);
            if (!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
                && 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 () {
                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 aboveLineNumber = viewLayout.getLineNumberAtVerticalOffset(Math.max(viewLayout.getScrollTop() - (editorContent.y - e.posy), 0));
                return new mouseTarget_1.MouseTarget(null, editorBrowser.MouseTargetType.OUTSIDE_EDITOR, mouseColumn, new position_1.Position(aboveLineNumber, 1));
            }
            if (e.posy > editorContent.y + editorContent.height) {
                var belowLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getScrollTop() + (e.posy - editorContent.y));
                return new mouseTarget_1.MouseTarget(null, editorBrowser.MouseTargetType.OUTSIDE_EDITOR, mouseColumn, new position_1.Position(belowLineNumber, model.getLineMaxColumn(belowLineNumber)));
            }
            var possibleLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getScrollTop() + (e.posy - editorContent.y));
            if (e.posx < editorContent.x) {
                return new mouseTarget_1.MouseTarget(null, editorBrowser.MouseTargetType.OUTSIDE_EDITOR, mouseColumn, new position_1.Position(possibleLineNumber, 1));
            }
            if (e.posx > editorContent.x + editorContent.width) {
                return new mouseTarget_1.MouseTarget(null, editorBrowser.MouseTargetType.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 === editorBrowser.MouseTargetType.CONTENT_VIEW_ZONE || t.type === editorBrowser.MouseTargetType.GUTTER_VIEW_ZONE) {
                // 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 viewZoneData = t.detail;
                var positionBefore = viewZoneData.positionBefore;
                var positionAfter = viewZoneData.positionAfter;
                if (positionBefore && positionAfter) {
                    if (positionBefore.isBefore(selectionStart)) {
                        return new mouseTarget_1.MouseTarget(t.element, t.type, t.mouseColumn, positionBefore, null, t.detail);
                    }
                    else {
                        return new mouseTarget_1.MouseTarget(t.element, t.type, t.mouseColumn, positionAfter, null, t.detail);
                    }
                }
            }
            return t;
        };
        MouseDownOperation.prototype._dispatchMouse = function (position, inSelectionMode) {
            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,
            });
        };
        return MouseDownOperation;
    }(lifecycle_1.Disposable));
    var MouseDownState = (function () {
        function MouseDownState() {
            this._altKey = false;
            this._ctrlKey = false;
            this._metaKey = false;
            this._shiftKey = 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, "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.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;
    }());
});











define(__m[490/*vs/editor/browser/controller/pointerHandler*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,74/*vs/base/browser/touch*/,489/*vs/editor/browser/controller/mouseHandler*/,114/*vs/editor/browser/editorDom*/]), function (require, exports, dom, touch_1, mouseHandler_1, editorDom_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    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 = (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) {
            var viewLayout = this._context.viewLayout;
            viewLayout.setScrollPosition({
                scrollLeft: viewLayout.getScrollLeft() - e.translationX,
                scrollTop: viewLayout.getScrollTop() - 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 = (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) {
            var viewLayout = this._context.viewLayout;
            viewLayout.setScrollPosition({
                scrollLeft: viewLayout.getScrollLeft() - e.translationX,
                scrollTop: viewLayout.getScrollTop() - e.translationY,
            });
        };
        StandardPointerHandler.prototype.dispose = function () {
            window.clearTimeout(this._installGestureHandlerTimeout);
            _super.prototype.dispose.call(this);
        };
        return StandardPointerHandler;
    }(mouseHandler_1.MouseHandler));
    var TouchHandler = (function (_super) {
        __extends(TouchHandler, _super);
        function TouchHandler(context, viewController, viewHelper) {
            var _this = _super.call(this, context, viewController, viewHelper) || this;
            _this.gesture = new touch_1.Gesture(_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 () {
            this.gesture.dispose();
            _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) {
            var viewLayout = this._context.viewLayout;
            viewLayout.setScrollPosition({
                scrollLeft: viewLayout.getScrollLeft() - e.translationX,
                scrollTop: viewLayout.getScrollTop() - e.translationY,
            });
        };
        return TouchHandler;
    }(mouseHandler_1.MouseHandler));
    var PointerHandler = (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) {
                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;
});











define(__m[491/*vs/editor/browser/view/viewOutgoingEvents*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,186/*vs/editor/browser/controller/mouseTarget*/,11/*vs/base/common/event*/]), function (require, exports, lifecycle_1, mouseTarget_1, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ViewOutgoingEvents = (function (_super) {
        __extends(ViewOutgoingEvents, _super);
        function ViewOutgoingEvents(viewModel) {
            var _this = _super.call(this) || this;
            _this._onDidScroll = _this._register(new event_1.Emitter());
            _this.onDidScroll = _this._onDidScroll.event;
            _this._onDidGainFocus = _this._register(new event_1.Emitter());
            _this.onDidGainFocus = _this._onDidGainFocus.event;
            _this._onDidLoseFocus = _this._register(new event_1.Emitter());
            _this.onDidLoseFocus = _this._onDidLoseFocus.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._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._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._viewModel = viewModel;
            return _this;
        }
        ViewOutgoingEvents.prototype.emitScrollChanged = function (e) {
            this._onDidScroll.fire(e);
        };
        ViewOutgoingEvents.prototype.emitViewFocusGained = function () {
            this._onDidGainFocus.fire();
        };
        ViewOutgoingEvents.prototype.emitViewFocusLost = function () {
            this._onDidLoseFocus.fire();
        };
        ViewOutgoingEvents.prototype.emitKeyDown = function (e) {
            this._onKeyDown.fire(e);
        };
        ViewOutgoingEvents.prototype.emitKeyUp = function (e) {
            this._onKeyUp.fire(e);
        };
        ViewOutgoingEvents.prototype.emitContextMenu = function (e) {
            this._onContextMenu.fire(this._convertViewToModelMouseEvent(e));
        };
        ViewOutgoingEvents.prototype.emitMouseMove = function (e) {
            this._onMouseMove.fire(this._convertViewToModelMouseEvent(e));
        };
        ViewOutgoingEvents.prototype.emitMouseLeave = function (e) {
            this._onMouseLeave.fire(this._convertViewToModelMouseEvent(e));
        };
        ViewOutgoingEvents.prototype.emitMouseUp = function (e) {
            this._onMouseUp.fire(this._convertViewToModelMouseEvent(e));
        };
        ViewOutgoingEvents.prototype.emitMouseDown = function (e) {
            this._onMouseDown.fire(this._convertViewToModelMouseEvent(e));
        };
        ViewOutgoingEvents.prototype.emitMouseDrag = function (e) {
            this._onMouseDrag.fire(this._convertViewToModelMouseEvent(e));
        };
        ViewOutgoingEvents.prototype.emitMouseDrop = function (e) {
            this._onMouseDrop.fire(this._convertViewToModelMouseEvent(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 = (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;
    }());
});











define(__m[492/*vs/editor/browser/viewParts/lines/viewLines*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/async*/,2/*vs/editor/common/core/range*/,12/*vs/editor/common/core/position*/,112/*vs/editor/browser/view/viewLayer*/,185/*vs/editor/browser/viewParts/lines/viewLine*/,66/*vs/editor/browser/config/configuration*/,78/*vs/editor/common/view/renderingContext*/,35/*vs/editor/browser/view/viewPart*/,57/*vs/editor/common/view/viewEvents*/,286/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/]), function (require, exports, async_1, range_1, position_1, viewLayer_1, viewLine_1, configuration_1, renderingContext_1, viewPart_1, viewEvents) {
    /*---------------------------------------------------------------------------------------------
     *  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 LastRenderedData = (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 ViewLines = (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._updateLineWidths();
            }, 200);
            _this._lastRenderedData = new LastRenderedData();
            _this._lastCursorRevealRangeHorizontallyEvent = 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) {
            var newScrollTop = this._computeScrollTopToRevealRange(this._context.viewLayout.getCurrentViewport(), e.range, e.verticalType);
            if (e.revealHorizontal) {
                this._lastCursorRevealRangeHorizontallyEvent = e;
            }
            this._context.viewLayout.setScrollPosition({
                scrollTop: newScrollTop
            });
            return true;
        };
        ViewLines.prototype.onScrollChanged = function (e) {
            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) {
            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;
            range = range_1.Range.intersectRanges(range, this._lastRenderedData.getCurrentVisibleRange());
            if (!range) {
                return null;
            }
            var visibleRanges = [];
            var domReadingContext = new viewLine_1.DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
            var nextLineModelLineNumber;
            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.push(new renderingContext_1.LineVisibleRanges(lineNumber, visibleRangesForLine));
            }
            if (visibleRanges.length === 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;
            }
            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;
        };
        // --- implementation
        ViewLines.prototype._updateLineWidths = function () {
            var rendStartLineNumber = this._visibleLines.getStartLineNumber();
            var rendEndLineNumber = this._visibleLines.getEndLineNumber();
            var localMaxLineWidth = 1;
            for (var lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
                var widthInPx = this._visibleLines.getVisibleLine(lineNumber).getWidth();
                localMaxLineWidth = Math.max(localMaxLineWidth, widthInPx);
            }
            if (rendStartLineNumber === 1 && rendEndLineNumber === this._context.model.getLineCount()) {
                // we know the max line width for all the lines
                this._maxLineWidth = 0;
            }
            this._ensureMaxLineWidth(localMaxLineWidth);
        };
        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._lastCursorRevealRangeHorizontallyEvent) {
                var revealHorizontalRange = this._lastCursorRevealRangeHorizontallyEvent.range;
                this._lastCursorRevealRangeHorizontallyEvent = null;
                // allow `visibleRangesForRange2` to work
                this.onDidRender();
                // compute new scroll position
                var newScrollLeft = this._computeScrollLeftToRevealRange(revealHorizontalRange);
                var isViewportWrapping = this._isViewportWrapping;
                if (!isViewportWrapping) {
                    // ensure `scrollWidth` is large enough
                    this._ensureMaxLineWidth(newScrollLeft.maxHorizontalOffset);
                }
                // set `scrollLeft`
                this._context.viewLayout.setScrollPosition({
                    scrollLeft: newScrollLeft.scrollLeft
                });
            }
            // (3) handle scrolling
            this._linesContent.setLayerHinting(this._canUseLayerHinting);
            var adjustedScrollTop = this._context.viewLayout.getScrollTop() - viewportData.bigNumbersDelta;
            this._linesContent.setTop(-adjustedScrollTop);
            this._linesContent.setLeft(-this._context.viewLayout.getScrollLeft());
            // Update max line width (not so important, it is just so the horizontal scrollbar doesn't get too small)
            this._asyncUpdateLineWidths.schedule();
        };
        // --- 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 (range) {
            var maxHorizontalOffset = 0;
            if (range.startLineNumber !== range.endLineNumber) {
                // Two or more lines? => scroll to base (That's how you see most of the two lines)
                return {
                    scrollLeft: 0,
                    maxHorizontalOffset: maxHorizontalOffset
                };
            }
            var viewport = this._context.viewLayout.getCurrentViewport();
            var viewportStartX = viewport.left;
            var viewportEndX = viewportStartX + viewport.width;
            var visibleRanges = this.visibleRangesForRange2(range);
            var boxStartX = Number.MAX_VALUE;
            var boxEndX = 0;
            if (!visibleRanges) {
                // Unknown
                return {
                    scrollLeft: viewportStartX,
                    maxHorizontalOffset: maxHorizontalOffset
                };
            }
            for (var i = 0; i < visibleRanges.length; i++) {
                var visibleRange = visibleRanges[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 ammount 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[493/*vs/editor/browser/viewParts/minimap/minimap*/], __M([1/*require*/,0/*exports*/,35/*vs/editor/browser/view/viewPart*/,215/*vs/editor/common/view/runtimeMinimapCharRenderer*/,4/*vs/base/browser/dom*/,111/*vs/editor/common/view/minimapCharRenderer*/,27/*vs/base/browser/fastDomNode*/,112/*vs/editor/browser/view/viewLayer*/,2/*vs/editor/common/core/range*/,57/*vs/editor/common/view/viewEvents*/,83/*vs/base/browser/globalMouseMoveMonitor*/,15/*vs/base/common/platform*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,294/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/]), function (require, exports, viewPart_1, runtimeMinimapCharRenderer_1, dom, minimapCharRenderer_1, fastDomNode_1, viewLayer_1, range_1, viewEvents, globalMouseMoveMonitor_1, platform, themeService_1, colorRegistry_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    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 || (RenderMinimap = {}));
    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 = (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.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.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 = (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 = (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 = (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 = (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 = (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._domNode.setRight(_this._context.configuration.editor.layoutInfo.verticalScrollbarWidth);
            _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._minimapCharRenderer = runtimeMinimapCharRenderer_1.getOrCreateMinimapCharRenderer();
            _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));
            });
            _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.setScrollPosition({
                                scrollTop: initialSliderState_1.scrollTop
                            });
                            return;
                        }
                        var mouseDelta = mouseMoveData.posy - initialMousePosition_1;
                        _this._context.viewLayout.setScrollPosition({
                            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.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');
                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 needed = Minimap._renderUntouchedLines(imageData, startLineNumber, endLineNumber, minimapLineHeight, this._lastRenderData);
            // 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, this._minimapCharRenderer, dy, tabSize, lineInfo.data[lineIndex]);
                }
                renderedLines[lineIndex] = new MinimapLine(dy);
                dy += minimapLineHeight;
            }
            // Finally, paint to the canvas
            var ctx = this._canvas.domNode.getContext('2d');
            ctx.putImageData(imageData, 0, 0);
            // 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 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 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);
                    }
                    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);
            }
            return 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.length; tokenIndex < tokensLen; tokenIndex++) {
                var token = tokens[tokenIndex];
                var tokenEndIndex = token.endIndex;
                var tokenColorId = token.getForeground();
                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 {
                        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;
                    }
                }
            }
        };
        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[494/*vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([1/*require*/,0/*exports*/,27/*vs/base/browser/fastDomNode*/,35/*vs/editor/browser/view/viewPart*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,300/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/]), function (require, exports, fastDomNode_1, viewPart_1, themeService_1, colorRegistry_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ScrollDecorationViewPart = (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 = layoutInfo.width - layoutInfo.minimapWidth;
            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[495/*vs/editor/browser/viewParts/selections/selections*/], __M([1/*require*/,0/*exports*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,67/*vs/editor/browser/view/dynamicViewOverlay*/,28/*vs/base/browser/browser*/,306/*vs/css!vs/editor/browser/viewParts/selections/selections*/]), function (require, exports, themeService_1, colorRegistry_1, dynamicViewOverlay_1, browser) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CornerStyle;
    (function (CornerStyle) {
        CornerStyle[CornerStyle["EXTERN"] = 0] = "EXTERN";
        CornerStyle[CornerStyle["INTERN"] = 1] = "INTERN";
        CornerStyle[CornerStyle["FLAT"] = 2] = "FLAT";
    })(CornerStyle || (CornerStyle = {}));
    var HorizontalRangeWithStyle = (function () {
        function HorizontalRangeWithStyle(other) {
            this.left = other.left;
            this.width = other.width;
            this.startStyle = null;
            this.endStyle = null;
        }
        return HorizontalRangeWithStyle;
    }());
    var LineVisibleRangesWithStyle = (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 = (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._selections = [];
            _this._renderResult = null;
            _this._context.addEventHandler(_this);
            return _this;
        }
        SelectionsOverlay.prototype.dispose = function () {
            this._context.removeEventHandler(this);
            this._context = null;
            this._selections = null;
            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;
            }
            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 (linesVisibleRanges, previousFrame) {
            var previousFrameTop = null;
            var previousFrameBottom = null;
            if (previousFrame && previousFrame.length > 0 && linesVisibleRanges.length > 0) {
                var topLineNumber = linesVisibleRanges[0].lineNumber;
                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;
                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 (curLeft === prevLeft) {
                        startStyle.top = 2 /* FLAT */;
                    }
                    else if (curLeft > prevLeft) {
                        startStyle.top = 1 /* INTERN */;
                    }
                    if (curRight === prevRight) {
                        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 (curLeft === nextLeft) {
                        startStyle.bottom = 2 /* FLAT */;
                    }
                    else if (nextLeft < curLeft && curLeft < nextRight) {
                        startStyle.bottom = 1 /* INTERN */;
                    }
                    if (curRight === nextRight) {
                        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(linesVisibleRanges, previousFrame);
            }
            // The visible ranges are sorted TOP-BOTTOM and LEFT-RIGHT
            return linesVisibleRanges;
        };
        SelectionsOverlay.prototype._createSelectionPiece = function (top, height, className, left, width) {
            return ('<div class="cslr '
                + className
                + '" style="top:'
                + top.toString()
                + 'px;left:'
                + left.toString()
                + 'px;width:'
                + width.toString()
                + 'px;height:'
                + height
                + 'px;"></div>');
        };
        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) {
                        if (visibleRange.startStyle.top === 1 /* INTERN */ || visibleRange.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 (visibleRange.startStyle.top === 1 /* INTERN */) {
                                className_1 += ' ' + SelectionsOverlay.SELECTION_TOP_RIGHT;
                            }
                            if (visibleRange.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 (visibleRange.endStyle.top === 1 /* INTERN */ || visibleRange.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 (visibleRange.endStyle.top === 1 /* INTERN */) {
                                className_2 += ' ' + SelectionsOverlay.SELECTION_TOP_LEFT;
                            }
                            if (visibleRange.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) {
                        if (visibleRange.startStyle.top === 0 /* EXTERN */) {
                            className += ' ' + SelectionsOverlay.SELECTION_TOP_LEFT;
                        }
                        if (visibleRange.startStyle.bottom === 0 /* EXTERN */) {
                            className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_LEFT;
                        }
                        if (visibleRange.endStyle.top === 0 /* EXTERN */) {
                            className += ' ' + SelectionsOverlay.SELECTION_TOP_RIGHT;
                        }
                        if (visibleRange.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.push(null);
                    continue;
                }
                var visibleRangesWithStyle = this._getVisibleRangesWithStyle(selection, ctx, this._previousFrameVisibleRangesWithStyle[i]);
                thisFrameVisibleRangesWithStyle.push(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) {
                throw new Error('Unexpected render request');
            }
            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 + "; }");
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[37/*vs/editor/common/view/editorColorRegistry*/], __M([1/*require*/,0/*exports*/,340/*vs/nls!vs/editor/common/view/editorColorRegistry*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,32/*vs/base/common/color*/]), function (require, exports, nls, colorRegistry_1, themeService_1, color_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));
    exports.editorCursorForeground = colorRegistry_1.registerColor('editorCursor.foreground', { dark: '#AEAFAD', light: color_1.Color.black, hc: color_1.Color.white }, nls.localize(3, null));
    exports.editorCursorBackground = colorRegistry_1.registerColor('editorCursor.background', null, nls.localize(4, null));
    exports.editorWhitespaces = colorRegistry_1.registerColor('editorWhitespace.foreground', { dark: '#e3e4e229', light: '#33333333', hc: '#e3e4e229' }, nls.localize(5, null));
    exports.editorIndentGuides = colorRegistry_1.registerColor('editorIndentGuide.background', { dark: exports.editorWhitespaces, light: exports.editorWhitespaces, hc: exports.editorWhitespaces }, nls.localize(6, null));
    exports.editorLineNumbers = colorRegistry_1.registerColor('editorLineNumber.foreground', { dark: '#5A5A5A', light: '#2B91AF', hc: color_1.Color.white }, nls.localize(7, null));
    exports.editorRuler = colorRegistry_1.registerColor('editorRuler.foreground', { dark: '#5A5A5A', light: color_1.Color.lightgrey, hc: color_1.Color.white }, nls.localize(8, null));
    exports.editorCodeLensForeground = colorRegistry_1.registerColor('editorCodeLens.foreground', { dark: '#999999', light: '#999999', hc: '#999999' }, nls.localize(9, null));
    exports.editorBracketMatchBackground = colorRegistry_1.registerColor('editorBracketMatch.background', { dark: '#0064001a', light: '#0064001a', hc: '#0064001a' }, nls.localize(10, null));
    exports.editorBracketMatchBorder = colorRegistry_1.registerColor('editorBracketMatch.border', { dark: '#888', light: '#B9B9B9', hc: '#fff' }, nls.localize(11, null));
    exports.editorOverviewRulerBorder = colorRegistry_1.registerColor('editorOverviewRuler.border', { dark: '#7f7f7f4d', light: '#7f7f7f4d', hc: '#7f7f7f4d' }, nls.localize(12, null));
    exports.editorGutter = colorRegistry_1.registerColor('editorGutter.background', { dark: colorRegistry_1.editorBackground, light: colorRegistry_1.editorBackground, hc: colorRegistry_1.editorBackground }, nls.localize(13, null));
    exports.editorErrorForeground = colorRegistry_1.registerColor('editorError.foreground', { dark: '#FF0000', light: '#FF0000', hc: null }, nls.localize(14, null));
    exports.editorErrorBorder = colorRegistry_1.registerColor('editorError.border', { dark: null, light: null, hc: color_1.Color.fromHex('#E47777').transparent(0.8) }, nls.localize(15, null));
    exports.editorWarningForeground = colorRegistry_1.registerColor('editorWarning.foreground', { dark: '#008000', light: '#008000', hc: null }, nls.localize(16, null));
    exports.editorWarningBorder = colorRegistry_1.registerColor('editorWarning.border', { dark: null, light: null, hc: color_1.Color.fromHex('#71B771').transparent(0.8) }, nls.localize(17, 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 outline = theme.getColor(colorRegistry_1.activeContrastBorder);
        if (outline) {
            collector.addRule(".monaco-editor .rangeHighlight { border: 1px dotted " + outline + "; }; }");
        }
        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[497/*vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([1/*require*/,0/*exports*/,67/*vs/editor/browser/view/dynamicViewOverlay*/,14/*vs/platform/theme/common/themeService*/,37/*vs/editor/common/view/editorColorRegistry*/,274/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/]), function (require, exports, dynamicViewOverlay_1, themeService_1, editorColorRegistry_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CurrentLineHighlightOverlay = (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._readOnly = _this._context.configuration.editor.readOnly;
            _this._renderLineHighlight = _this._context.configuration.editor.viewInfo.renderLineHighlight;
            _this._selectionIsEmpty = true;
            _this._primaryCursorIsInEditableRange = 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);
            this._context = null;
            _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.readOnly) {
                this._readOnly = this._context.configuration.editor.readOnly;
            }
            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;
            if (this._primaryCursorIsInEditableRange !== e.isInEditableRange) {
                this._primaryCursorIsInEditableRange = e.isInEditableRange;
                hasChanged = true;
            }
            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;
                hasChanged = true;
                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()) {
                    return ('<div class="current-line" style="width:'
                        + String(Math.max(this._scrollWidth, this._contentWidth))
                        + 'px; height:'
                        + String(this._lineHeight)
                        + 'px;"></div>');
                }
                else {
                    return '';
                }
            }
            return '';
        };
        CurrentLineHighlightOverlay.prototype._shouldShowCurrentLine = function () {
            return (this._renderLineHighlight === 'line' || this._renderLineHighlight === 'all') &&
                this._selectionIsEmpty &&
                this._primaryCursorIsInEditableRange;
        };
        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[498/*vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight*/], __M([1/*require*/,0/*exports*/,67/*vs/editor/browser/view/dynamicViewOverlay*/,14/*vs/platform/theme/common/themeService*/,37/*vs/editor/common/view/editorColorRegistry*/,277/*vs/css!vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight*/]), function (require, exports, dynamicViewOverlay_1, themeService_1, editorColorRegistry_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CurrentLineMarginHighlightOverlay = (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._primaryCursorIsInEditableRange = 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);
            this._context = null;
            _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;
            if (this._primaryCursorIsInEditableRange !== e.isInEditableRange) {
                this._primaryCursorIsInEditableRange = e.isInEditableRange;
                hasChanged = true;
            }
            var primaryCursorLineNumber = e.selections[0].positionLineNumber;
            if (this._primaryCursorLineNumber !== primaryCursorLineNumber) {
                this._primaryCursorLineNumber = primaryCursorLineNumber;
                hasChanged = 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) {
                if (this._shouldShowCurrentLine()) {
                    return ('<div class="current-line-margin" style="width:'
                        + String(this._contentLeft)
                        + 'px; height:'
                        + String(this._lineHeight)
                        + 'px;"></div>');
                }
                else {
                    return '';
                }
            }
            return '';
        };
        CurrentLineMarginHighlightOverlay.prototype._shouldShowCurrentLine = function () {
            return (this._renderLineHighlight === 'gutter' || this._renderLineHighlight === 'all') && this._primaryCursorIsInEditableRange;
        };
        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[499/*vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([1/*require*/,0/*exports*/,67/*vs/editor/browser/view/dynamicViewOverlay*/,14/*vs/platform/theme/common/themeService*/,37/*vs/editor/common/view/editorColorRegistry*/,4/*vs/base/browser/dom*/,12/*vs/editor/common/core/position*/,280/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/]), function (require, exports, dynamicViewOverlay_1, themeService_1, editorColorRegistry_1, dom, position_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var IndentGuidesOverlay = (function (_super) {
        __extends(IndentGuidesOverlay, _super);
        function IndentGuidesOverlay(context) {
            var _this = _super.call(this) || this;
            _this._context = context;
            _this._lineHeight = _this._context.configuration.editor.lineHeight;
            _this._spaceWidth = _this._context.configuration.editor.fontInfo.spaceWidth;
            _this._enabled = _this._context.configuration.editor.viewInfo.renderIndentGuides;
            _this._renderResult = null;
            _this._context.addEventHandler(_this);
            return _this;
        }
        IndentGuidesOverlay.prototype.dispose = function () {
            this._context.removeEventHandler(this);
            this._context = null;
            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;
            }
            return true;
        };
        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;
        };
        // --- 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 tabSize = this._context.model.getTabSize();
            var tabWidth = tabSize * this._spaceWidth;
            var lineHeight = this._lineHeight;
            var indentGuideWidth = dom.computeScreenAwareSize(1);
            var output = [];
            for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
                var lineIndex = lineNumber - visibleStartLineNumber;
                var indent = this._context.model.getLineIndentGuide(lineNumber);
                var result = '';
                var leftMostVisiblePosition = ctx.visibleRangeForPosition(new position_1.Position(lineNumber, 1));
                var left = leftMostVisiblePosition ? leftMostVisiblePosition.left : 0;
                for (var i = 0; i < indent; i++) {
                    result += "<div class=\"cigr\" style=\"left:" + left + "px;height:" + lineHeight + "px;width:" + indentGuideWidth + "px\"></div>";
                    left += tabWidth;
                }
                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) {
                throw new Error('Unexpected render request');
            }
            return this._renderResult[lineIndex];
        };
        return IndentGuidesOverlay;
    }(dynamicViewOverlay_1.DynamicViewOverlay));
    exports.IndentGuidesOverlay = IndentGuidesOverlay;
    themeService_1.registerThemingParticipant(function (theme, collector) {
        var editorGuideColor = theme.getColor(editorColorRegistry_1.editorIndentGuides);
        if (editorGuideColor) {
            collector.addRule(".monaco-editor .lines-content .cigr { background-color: " + editorGuideColor + "; }");
        }
    });
});

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










define(__m[188/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([1/*require*/,0/*exports*/,37/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,15/*vs/base/common/platform*/,67/*vs/editor/browser/view/dynamicViewOverlay*/,12/*vs/editor/common/core/position*/,283/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/]), function (require, exports, editorColorRegistry_1, themeService_1, platform, dynamicViewOverlay_1, position_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var LineNumbersOverlay = (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._renderRelativeLineNumbers = config.viewInfo.renderRelativeLineNumbers;
            this._lineNumbersLeft = config.layoutInfo.lineNumbersLeft;
            this._lineNumbersWidth = config.layoutInfo.lineNumbersWidth;
        };
        LineNumbersOverlay.prototype.dispose = function () {
            this._context.removeEventHandler(this);
            this._context = null;
            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._renderRelativeLineNumbers) {
                return true;
            }
            return false;
        };
        LineNumbersOverlay.prototype.onFlushed = function (e) {
            return true;
        };
        LineNumbersOverlay.prototype.onLinesChanged = function (e) {
            return true;
        };
        LineNumbersOverlay.prototype.onLinesDeleted = function (e) {
            return true;
        };
        LineNumbersOverlay.prototype.onLinesInserted = function (e) {
            return true;
        };
        LineNumbersOverlay.prototype.onScrollChanged = function (e) {
            return e.scrollTopChanged;
        };
        LineNumbersOverlay.prototype.onZonesChanged = function (e) {
            return true;
        };
        // --- end event handlers
        LineNumbersOverlay.prototype._getLineRenderLineNumber = function (viewLineNumber) {
            var modelPosition = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(viewLineNumber, 1));
            if (modelPosition.column !== 1) {
                return '';
            }
            var modelLineNumber = modelPosition.lineNumber;
            if (this._renderCustomLineNumbers) {
                return this._renderCustomLineNumbers(modelLineNumber);
            }
            if (this._renderRelativeLineNumbers) {
                var diff = Math.abs(this._lastCursorModelPosition.lineNumber - modelLineNumber);
                if (diff === 0) {
                    return '<span class="relative-current-line-number">' + modelLineNumber + '</span>';
                }
                return String(diff);
            }
            return String(modelLineNumber);
        };
        LineNumbersOverlay.prototype.prepareRender = function (ctx) {
            if (!this._renderLineNumbers) {
                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 = '<div class="' + LineNumbersOverlay.CLASS_NAME + lineHeightClassName + '" style="left:' + this._lineNumbersLeft.toString() + 'px;width:' + this._lineNumbersWidth.toString() + 'px;">';
            var output = [];
            for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
                var lineIndex = lineNumber - visibleStartLineNumber;
                var renderLineNumber = this._getLineRenderLineNumber(lineNumber);
                if (renderLineNumber) {
                    output[lineIndex] = (common
                        + renderLineNumber
                        + '</div>');
                }
                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) {
                throw new Error('Unexpected render request');
            }
            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 + "; }");
        }
    });
});











define(__m[501/*vs/editor/browser/controller/textAreaHandler*/], __M([1/*require*/,0/*exports*/,15/*vs/base/common/platform*/,28/*vs/base/browser/browser*/,154/*vs/editor/browser/controller/textAreaInput*/,151/*vs/editor/browser/controller/textAreaState*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,12/*vs/editor/common/core/position*/,66/*vs/editor/browser/config/configuration*/,57/*vs/editor/common/view/viewEvents*/,27/*vs/base/browser/fastDomNode*/,35/*vs/editor/browser/view/viewPart*/,182/*vs/editor/browser/viewParts/margin/margin*/,188/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/,270/*vs/css!vs/editor/browser/controller/textAreaHandler*/]), function (require, exports, platform, browser, textAreaInput_1, textAreaState_1, range_1, selection_1, position_1, configuration_1, viewEvents, fastDomNode_1, viewPart_1, margin_1, lineNumbers_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var VisibleTextAreaData = (function () {
        function VisibleTextAreaData(top, left, width) {
            this.top = top;
            this.left = left;
            this.width = width;
        }
        VisibleTextAreaData.prototype.setWidth = function (width) {
            return new VisibleTextAreaData(this.top, this.left, width);
        };
        return VisibleTextAreaData;
    }());
    var canUseZeroSizeTextarea = (browser.isEdgeOrIE || browser.isFirefox);
    var TextAreaHandler = (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._pixelRatio = conf.pixelRatio;
            _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._visibleTextArea = null;
            _this._selections = [new selection_1.Selection(1, 1, 1, 1)];
            _this._lastCopiedValue = null;
            _this._lastCopiedValueIsFromEmptySelection = false;
            // 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 whatToCopy = _this._context.model.getPlainTextToCopy(_this._selections, _this._emptySelectionClipboard);
                    if (_this._emptySelectionClipboard) {
                        if (browser.isFirefox) {
                            // When writing "LINE\r\n" to the clipboard and then pasting,
                            // Firefox pastes "LINE\n", so let's work around this quirk
                            _this._lastCopiedValue = whatToCopy.replace(/\r\n/g, '\n');
                        }
                        else {
                            _this._lastCopiedValue = whatToCopy;
                        }
                        var selections = _this._selections;
                        _this._lastCopiedValueIsFromEmptySelection = (selections.length === 1 && selections[0].isEmpty());
                    }
                    return whatToCopy;
                },
                getHTMLToCopy: function () {
                    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
                        return textAreaState_1.TextAreaState.EMPTY;
                    }
                    return textAreaState_1.PagedScreenReaderStrategy.fromEditorSelection(currentState, simpleModel, _this._selections[0]);
                }
            };
            _this._textAreaInput = _this._register(new textAreaInput_1.TextAreaInput(textAreaInputHost, _this.textArea));
            _this._register(_this._textAreaInput.onKeyDown(function (e) {
                _this._viewController.emitKeyDown(e);
            }));
            _this._register(_this._textAreaInput.onKeyUp(function (e) {
                _this._viewController.emitKeyUp(e);
            }));
            _this._register(_this._textAreaInput.onPaste(function (e) {
                var pasteOnNewLine = false;
                if (_this._emptySelectionClipboard) {
                    pasteOnNewLine = (e.text === _this._lastCopiedValue && _this._lastCopiedValueIsFromEmptySelection);
                }
                _this._viewController.paste('keyboard', e.text, pasteOnNewLine);
            }));
            _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.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));
                // 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);
        };
        // --- 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.pixelRatio) {
                this._pixelRatio = conf.pixelRatio;
            }
            if (e.accessibilitySupport) {
                this._accessibilitySupport = conf.accessibilitySupport;
                this._textAreaInput.writeScreenReaderContent('strategy changed');
            }
            if (e.emptySelectionClipboard) {
                this._emptySelectionClipboard = conf.emptySelectionClipboard;
            }
            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.setAriaActiveDescendant = function (id) {
            if (id) {
                this.textArea.setAttribute('role', 'combobox');
                if (this.textArea.getAttribute('aria-activedescendant') !== id) {
                    this.textArea.setAttribute('aria-haspopup', 'true');
                    this.textArea.setAttribute('aria-activedescendant', id);
                }
            }
            else {
                this.textArea.setAttribute('role', 'textbox');
                this.textArea.removeAttribute('aria-activedescendant');
                this.textArea.removeAttribute('aria-haspopup');
            }
        };
        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 textare 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.CLASS_NAME);
            }
            else {
                if (this._context.configuration.editor.viewInfo.renderLineNumbers) {
                    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[502/*vs/editor/browser/viewParts/rulers/rulers*/], __M([1/*require*/,0/*exports*/,27/*vs/base/browser/fastDomNode*/,35/*vs/editor/browser/view/viewPart*/,14/*vs/platform/theme/common/themeService*/,37/*vs/editor/common/view/editorColorRegistry*/,4/*vs/base/browser/dom*/,299/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/]), function (require, exports, fastDomNode_1, viewPart_1, themeService_1, editorColorRegistry_1, dom) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var Rulers = (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._height = _this._context.configuration.editor.layoutInfo.contentHeight;
            _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._height = this._context.configuration.editor.layoutInfo.contentHeight;
                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 rulerWidth = dom.computeScreenAwareSize(1);
                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 { background-color: " + rulerColor + "; }");
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  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/viewCursors/viewCursors*/], __M([1/*require*/,0/*exports*/,35/*vs/editor/browser/view/viewPart*/,444/*vs/editor/browser/viewParts/viewCursors/viewCursor*/,27/*vs/base/browser/fastDomNode*/,18/*vs/base/common/async*/,14/*vs/platform/theme/common/themeService*/,37/*vs/editor/common/view/editorColorRegistry*/,49/*vs/editor/common/config/editorOptions*/,307/*vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors*/]), function (require, exports, viewPart_1, viewCursor_1, fastDomNode_1, async_1, themeService_1, editorColorRegistry_1, editorOptions_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ViewCursors = (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._selectionIsEmpty = true;
            _this._primaryCursor = new viewCursor_1.ViewCursor(_this._context, false);
            _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._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, isInEditableRange) {
            this._primaryCursor.onCursorPositionChanged(position, isInEditableRange);
            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, true);
                    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], isInEditableRange);
            }
        };
        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), e.isInEditableRange);
            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; i < this._secondaryCursors.length; i++) {
                if (shouldRender(this._secondaryCursors[i].getPosition())) {
                    return true;
                }
            }
            return false;
        };
        ViewCursors.prototype.onZonesChanged = function (e) {
            return true;
        };
        // --- end event handlers
        ViewCursors.prototype.getPosition = function () {
            return this._primaryCursor.getPosition();
        };
        // ---- blinking logic
        ViewCursors.prototype._getCursorBlinking = function () {
            if (!this._editorHasFocus) {
                return editorOptions_1.TextEditorCursorBlinkingStyle.Hidden;
            }
            if (this._readOnly || !this._primaryCursor.getIsInEditableRange()) {
                return editorOptions_1.TextEditorCursorBlinkingStyle.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 === editorOptions_1.TextEditorCursorBlinkingStyle.Hidden);
            var isSolid = (blinkingStyle === editorOptions_1.TextEditorCursorBlinkingStyle.Solid);
            if (isHidden) {
                this._hide();
            }
            else {
                this._show();
            }
            this._blinkingEnabled = false;
            this._updateDomClassName();
            if (!isHidden && !isSolid) {
                if (blinkingStyle === editorOptions_1.TextEditorCursorBlinkingStyle.Blink) {
                    // flat blinking is handled by JavaScript to save battery life due to Chromium step timing issue https://bugs.chromium.org/p/chromium/issues/detail?id=361587
                    this._cursorFlatBlinkInterval.cancelAndSet(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 editorOptions_1.TextEditorCursorBlinkingStyle.Blink:
                        result += ' cursor-blink';
                        break;
                    case editorOptions_1.TextEditorCursorBlinkingStyle.Smooth:
                        result += ' cursor-smooth';
                        break;
                    case editorOptions_1.TextEditorCursorBlinkingStyle.Phase:
                        result += ' cursor-phase';
                        break;
                    case editorOptions_1.TextEditorCursorBlinkingStyle.Expand:
                        result += ' cursor-expand';
                        break;
                    case editorOptions_1.TextEditorCursorBlinkingStyle.Solid:
                        result += ' cursor-solid';
                        break;
                    default:
                        result += ' cursor-solid';
                }
            }
            else {
                result += ' cursor-solid';
            }
            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) {
            this._renderData = [];
            this._renderData.push(this._primaryCursor.render(ctx));
            for (var i = 0, len = this._secondaryCursors.length; i < len; i++) {
                this._renderData.push(this._secondaryCursors[i].render(ctx));
            }
            // Keep only data of cursors that are visible
            this._renderData = this._renderData.filter(function (d) { return !!d; });
        };
        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 + "; }");
            }
        }
    });
});

















define(__m[504/*vs/editor/browser/widget/diffReview*/], __M([1/*require*/,0/*exports*/,303/*vs/nls!vs/editor/browser/widget/diffReview*/,3/*vs/base/common/lifecycle*/,4/*vs/base/browser/dom*/,27/*vs/base/browser/fastDomNode*/,106/*vs/editor/common/viewLayout/viewLineRenderer*/,90/*vs/editor/common/core/viewLineToken*/,66/*vs/editor/browser/config/configuration*/,12/*vs/editor/common/core/position*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,63/*vs/base/browser/ui/scrollbar/scrollableElement*/,37/*vs/editor/common/view/editorColorRegistry*/,75/*vs/base/browser/ui/actionbar/actionbar*/,53/*vs/base/common/actions*/,13/*vs/editor/common/editorCommonExtensions*/,19/*vs/platform/contextkey/common/contextkey*/,42/*vs/editor/common/services/codeEditorService*/,309/*vs/css!vs/editor/browser/widget/media/diffReview*/]), function (require, exports, nls, lifecycle_1, dom, fastDomNode_1, viewLineRenderer_1, viewLineToken_1, configuration_1, position_1, themeService_1, colorRegistry_1, scrollableElement_1, editorColorRegistry_1, actionbar_1, actions_1, editorCommonExtensions_1, contextkey_1, codeEditorService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var DIFF_LINES_PADDING = 3;
    var DiffEntryType;
    (function (DiffEntryType) {
        DiffEntryType[DiffEntryType["Equal"] = 0] = "Equal";
        DiffEntryType[DiffEntryType["Insert"] = 1] = "Insert";
        DiffEntryType[DiffEntryType["Delete"] = 2] = "Delete";
    })(DiffEntryType || (DiffEntryType = {}));
    var DiffEntry = (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 = (function () {
        function Diff(entries) {
            this.entries = entries;
        }
        return Diff;
    }());
    var DiffReview = (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 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().onDidFocusEditor(function () {
                if (_this._isVisible) {
                    _this.hide();
                }
            }));
            _this._register(diffEditor.getModifiedEditor().onDidFocusEditor(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));
            }
        };
        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 pos = this._diffEditor.getPosition();
            var diffIndex = this._findDiffIndex(pos);
            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';
            cell.appendChild(document.createTextNode(diffIndex + 1 + "/" + this._diffs.length + ": @@ -" + minOriginalLine + "," + (maxOriginalLine - minOriginalLine + 1) + " +" + minModifiedLine + "," + (maxModifiedLine - minModifiedLine + 1) + " @@"));
            header.setAttribute('data-line', String(minModifiedLine));
            header.setAttribute('aria-label', nls.localize(1, null, (diffIndex + 1), this._diffs.length, minOriginalLine, maxOriginalLine - minOriginalLine + 1, minModifiedLine, maxModifiedLine - minModifiedLine + 1));
            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 = '&nbsp;';
                }
                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 = '&nbsp;';
                }
                cell.appendChild(modifiedLineNumber);
                var spacer = document.createElement('span');
                spacer.className = spacerClassName;
                spacer.innerHTML = '&nbsp;&nbsp;';
                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(2, null);
                }
                var ariaLabel = void 0;
                switch (type) {
                    case 0 /* Equal */:
                        ariaLabel = nls.localize(3, null, originalLine, modifiedLine, lineContent);
                        break;
                    case 1 /* Insert */:
                        ariaLabel = nls.localize(4, null, modifiedLine, lineContent);
                        break;
                    case 2 /* Delete */:
                        ariaLabel = nls.localize(5, 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 r = viewLineRenderer_1.renderViewLine(new viewLineRenderer_1.RenderLineInput((config.fontInfo.isMonospace && !config.viewInfo.disableMonospaceOptimizations), lineContent, model.mightContainRTL(), 0, [new viewLineToken_1.ViewLineToken(lineContent.length, defaultMetadata)], [], 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 = (function (_super) {
        __extends(DiffReviewNext, _super);
        function DiffReviewNext() {
            return _super.call(this, {
                id: 'editor.action.diffReview.next',
                label: nls.localize(6, null),
                alias: 'Go to Next Difference',
                precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
                kbOpts: {
                    kbExpr: null,
                    primary: 65 /* F7 */
                }
            }) || this;
        }
        DiffReviewNext.prototype.run = function (accessor, editor) {
            var diffEditor = findFocusedDiffEditor(accessor);
            if (diffEditor) {
                diffEditor.diffReviewNext();
            }
        };
        DiffReviewNext = __decorate([
            editorCommonExtensions_1.editorAction
        ], DiffReviewNext);
        return DiffReviewNext;
    }(editorCommonExtensions_1.EditorAction));
    var DiffReviewPrev = (function (_super) {
        __extends(DiffReviewPrev, _super);
        function DiffReviewPrev() {
            return _super.call(this, {
                id: 'editor.action.diffReview.prev',
                label: nls.localize(7, null),
                alias: 'Go to Previous Difference',
                precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
                kbOpts: {
                    kbExpr: null,
                    primary: 1024 /* Shift */ | 65 /* F7 */
                }
            }) || this;
        }
        DiffReviewPrev.prototype.run = function (accessor, editor) {
            var diffEditor = findFocusedDiffEditor(accessor);
            if (diffEditor) {
                diffEditor.diffReviewPrev();
            }
        };
        DiffReviewPrev = __decorate([
            editorCommonExtensions_1.editorAction
        ], DiffReviewPrev);
        return DiffReviewPrev;
    }(editorCommonExtensions_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;
    }
});

define(__m[140/*vs/editor/common/view/overviewZoneManager*/], __M([1/*require*/,0/*exports*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, themeService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ColorZone = (function () {
        function ColorZone(from, to, colorId, position) {
            this.from = from | 0;
            this.to = to | 0;
            this.colorId = colorId | 0;
            this.position = position | 0;
        }
        return ColorZone;
    }());
    exports.ColorZone = ColorZone;
    /**
     * A zone in the overview ruler
     */
    var OverviewRulerZone = (function () {
        function OverviewRulerZone(startLineNumber, endLineNumber, position, forceHeight, color, darkColor, hcColor) {
            this.startLineNumber = startLineNumber;
            this.endLineNumber = endLineNumber;
            this.position = position;
            this.forceHeight = forceHeight;
            this._color = color;
            this._darkColor = darkColor;
            this._hcColor = hcColor;
            this._colorZones = null;
        }
        OverviewRulerZone.prototype.getColor = function (themeType) {
            switch (themeType) {
                case themeService_1.HIGH_CONTRAST:
                    return this._hcColor;
                case themeService_1.DARK:
                    return this._darkColor;
            }
            return this._color;
        };
        OverviewRulerZone.prototype.equals = function (other) {
            return (this.startLineNumber === other.startLineNumber
                && this.endLineNumber === other.endLineNumber
                && this.position === other.position
                && this.forceHeight === other.forceHeight
                && this._color === other._color
                && this._darkColor === other._darkColor
                && this._hcColor === other._hcColor);
        };
        OverviewRulerZone.prototype.compareTo = function (other) {
            if (this.startLineNumber === other.startLineNumber) {
                if (this.endLineNumber === other.endLineNumber) {
                    if (this.forceHeight === other.forceHeight) {
                        if (this.position === other.position) {
                            if (this._darkColor === other._darkColor) {
                                if (this._color === other._color) {
                                    if (this._hcColor === other._hcColor) {
                                        return 0;
                                    }
                                    return this._hcColor < other._hcColor ? -1 : 1;
                                }
                                return this._color < other._color ? -1 : 1;
                            }
                            return this._darkColor < other._darkColor ? -1 : 1;
                        }
                        return this.position - other.position;
                    }
                    return this.forceHeight - other.forceHeight;
                }
                return this.endLineNumber - other.endLineNumber;
            }
            return this.startLineNumber - other.startLineNumber;
        };
        OverviewRulerZone.prototype.setColorZones = function (colorZones) {
            this._colorZones = colorZones;
        };
        OverviewRulerZone.prototype.getColorZones = function () {
            return this._colorZones;
        };
        return OverviewRulerZone;
    }());
    exports.OverviewRulerZone = OverviewRulerZone;
    var OverviewZoneManager = (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._maximumHeight = 0;
            this._minimumHeight = 0;
            this._themeType = themeService_1.LIGHT;
            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) {
            newZones.sort(function (a, b) { return a.compareTo(b); });
            var oldZones = this._zones;
            var oldIndex = 0;
            var oldLength = this._zones.length;
            var newIndex = 0;
            var newLength = newZones.length;
            var result = [];
            while (newIndex < newLength) {
                var newZone = newZones[newIndex];
                if (oldIndex >= oldLength) {
                    result.push(newZone);
                    newIndex++;
                }
                else {
                    var oldZone = oldZones[oldIndex];
                    var cmp = oldZone.compareTo(newZone);
                    if (cmp < 0) {
                        oldIndex++;
                    }
                    else if (cmp > 0) {
                        result.push(newZone);
                        newIndex++;
                    }
                    else {
                        // cmp === 0
                        result.push(oldZone);
                        oldIndex++;
                        newIndex++;
                    }
                }
            }
            this._zones = result;
        };
        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.setMaximumHeight = function (maximumHeight) {
            if (this._maximumHeight === maximumHeight) {
                return false;
            }
            this._maximumHeight = maximumHeight;
            this._colorZonesInvalid = true;
            return true;
        };
        OverviewZoneManager.prototype.setMinimumHeight = function (minimumHeight) {
            if (this._minimumHeight === minimumHeight) {
                return false;
            }
            this._minimumHeight = minimumHeight;
            this._colorZonesInvalid = true;
            return true;
        };
        OverviewZoneManager.prototype.setThemeType = function (themeType) {
            if (this._themeType === themeType) {
                return false;
            }
            this._themeType = themeType;
            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 maximumHeight = Math.floor(this._maximumHeight * this._pixelRatio); // @perf
            var minimumHeight = Math.floor(this._minimumHeight * this._pixelRatio); // @perf
            var themeType = this._themeType; // @perf
            var outerHeight = Math.floor(this._outerHeight); // @perf
            var heightRatio = totalHeight / outerHeight;
            var allColorZones = [];
            for (var i = 0, len = this._zones.length; i < len; i++) {
                var zone = this._zones[i];
                if (!colorZonesInvalid) {
                    var colorZones_1 = zone.getColorZones();
                    if (colorZones_1) {
                        for (var j = 0, lenJ = colorZones_1.length; j < lenJ; j++) {
                            allColorZones.push(colorZones_1[j]);
                        }
                        continue;
                    }
                }
                var colorZones = [];
                if (zone.forceHeight) {
                    var forcedHeight = Math.floor(zone.forceHeight * this._pixelRatio);
                    var y1 = Math.floor(this._getVerticalOffsetForLine(zone.startLineNumber));
                    y1 = Math.floor(y1 * heightRatio);
                    var y2 = y1 + forcedHeight;
                    colorZones.push(this.createZone(totalHeight, y1, y2, forcedHeight, forcedHeight, zone.getColor(themeType), zone.position));
                }
                else {
                    var y1 = Math.floor(this._getVerticalOffsetForLine(zone.startLineNumber));
                    var y2 = Math.floor(this._getVerticalOffsetForLine(zone.endLineNumber)) + lineHeight;
                    y1 = Math.floor(y1 * heightRatio);
                    y2 = Math.floor(y2 * heightRatio);
                    // Figure out if we can render this in one continuous zone
                    var zoneLineNumbers = zone.endLineNumber - zone.startLineNumber + 1;
                    var zoneMaximumHeight = zoneLineNumbers * maximumHeight;
                    if (y2 - y1 > zoneMaximumHeight) {
                        // We need to draw one zone per line
                        for (var lineNumber = zone.startLineNumber; lineNumber <= zone.endLineNumber; lineNumber++) {
                            y1 = Math.floor(this._getVerticalOffsetForLine(lineNumber));
                            y2 = y1 + lineHeight;
                            y1 = Math.floor(y1 * heightRatio);
                            y2 = Math.floor(y2 * heightRatio);
                            colorZones.push(this.createZone(totalHeight, y1, y2, minimumHeight, maximumHeight, zone.getColor(themeType), zone.position));
                        }
                    }
                    else {
                        colorZones.push(this.createZone(totalHeight, y1, y2, minimumHeight, zoneMaximumHeight, zone.getColor(themeType), zone.position));
                    }
                }
                zone.setColorZones(colorZones);
                for (var j = 0, lenJ = colorZones.length; j < lenJ; j++) {
                    allColorZones.push(colorZones[j]);
                }
            }
            this._colorZonesInvalid = false;
            var sortFunc = 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;
            };
            allColorZones.sort(sortFunc);
            return allColorZones;
        };
        OverviewZoneManager.prototype.createZone = function (totalHeight, y1, y2, minimumHeight, maximumHeight, color, position) {
            totalHeight = Math.floor(totalHeight); // @perf
            y1 = Math.floor(y1); // @perf
            y2 = Math.floor(y2); // @perf
            minimumHeight = Math.floor(minimumHeight); // @perf
            maximumHeight = Math.floor(maximumHeight); // @perf
            var ycenter = Math.floor((y1 + y2) / 2);
            var halfHeight = (y2 - ycenter);
            if (halfHeight > maximumHeight / 2) {
                halfHeight = maximumHeight / 2;
            }
            if (halfHeight < minimumHeight / 2) {
                halfHeight = minimumHeight / 2;
            }
            if (ycenter - halfHeight < 0) {
                ycenter = halfHeight;
            }
            if (ycenter + halfHeight > totalHeight) {
                ycenter = totalHeight - halfHeight;
            }
            var colorId = this._color2Id[color];
            if (!colorId) {
                colorId = (++this._lastAssignedId);
                this._color2Id[color] = colorId;
                this._id2Color[colorId] = color;
            }
            return new ColorZone(ycenter - halfHeight, ycenter + halfHeight, colorId, position);
        };
        return OverviewZoneManager;
    }());
    exports.OverviewZoneManager = OverviewZoneManager;
});

define(__m[190/*vs/editor/browser/viewParts/overviewRuler/overviewRulerImpl*/], __M([1/*require*/,0/*exports*/,27/*vs/base/browser/fastDomNode*/,20/*vs/editor/common/editorCommon*/,140/*vs/editor/common/view/overviewZoneManager*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, fastDomNode_1, editorCommon_1, overviewZoneManager_1, themeService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var OverviewRulerImpl = (function () {
        function OverviewRulerImpl(canvasLeftOffset, cssClassName, scrollHeight, lineHeight, pixelRatio, minimumHeight, maximumHeight, getVerticalOffsetForLine) {
            this._canvasLeftOffset = canvasLeftOffset;
            this._domNode = fastDomNode_1.createFastDomNode(document.createElement('canvas'));
            this._domNode.setClassName(cssClassName);
            this._domNode.setPosition('absolute');
            this._domNode.setLayerHinting(true);
            this._lanesCount = 3;
            this._background = null;
            this._zoneManager = new overviewZoneManager_1.OverviewZoneManager(getVerticalOffsetForLine);
            this._zoneManager.setMinimumHeight(minimumHeight);
            this._zoneManager.setMaximumHeight(maximumHeight);
            this._zoneManager.setThemeType(themeService_1.LIGHT);
            this._zoneManager.setDOMWidth(0);
            this._zoneManager.setDOMHeight(0);
            this._zoneManager.setOuterHeight(scrollHeight);
            this._zoneManager.setLineHeight(lineHeight);
            this._zoneManager.setPixelRatio(pixelRatio);
        }
        OverviewRulerImpl.prototype.dispose = function () {
            this._zoneManager = null;
        };
        OverviewRulerImpl.prototype.setLayout = function (position, render) {
            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();
                if (render) {
                    this.render(true);
                }
            }
        };
        OverviewRulerImpl.prototype.getLanesCount = function () {
            return this._lanesCount;
        };
        OverviewRulerImpl.prototype.setLanesCount = function (newLanesCount, render) {
            this._lanesCount = newLanesCount;
            if (render) {
                this.render(true);
            }
        };
        OverviewRulerImpl.prototype.setThemeType = function (themeType, render) {
            this._zoneManager.setThemeType(themeType);
            if (render) {
                this.render(true);
            }
        };
        OverviewRulerImpl.prototype.setUseBackground = function (background, render) {
            this._background = background;
            if (render) {
                this.render(true);
            }
        };
        OverviewRulerImpl.prototype.getDomNode = function () {
            return this._domNode.domNode;
        };
        OverviewRulerImpl.prototype.getPixelWidth = function () {
            return this._zoneManager.getCanvasWidth();
        };
        OverviewRulerImpl.prototype.getPixelHeight = function () {
            return this._zoneManager.getCanvasHeight();
        };
        OverviewRulerImpl.prototype.setScrollHeight = function (scrollHeight, render) {
            this._zoneManager.setOuterHeight(scrollHeight);
            if (render) {
                this.render(true);
            }
        };
        OverviewRulerImpl.prototype.setLineHeight = function (lineHeight, render) {
            this._zoneManager.setLineHeight(lineHeight);
            if (render) {
                this.render(true);
            }
        };
        OverviewRulerImpl.prototype.setPixelRatio = function (pixelRatio, render) {
            this._zoneManager.setPixelRatio(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();
            if (render) {
                this.render(true);
            }
        };
        OverviewRulerImpl.prototype.setZones = function (zones, render) {
            this._zoneManager.setZones(zones);
            if (render) {
                this.render(false);
            }
        };
        OverviewRulerImpl.prototype.render = function (forceRender) {
            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');
            if (this._background === null) {
                ctx.clearRect(0, 0, width, height);
            }
            else {
                ctx.fillStyle = this._background.toRGBHex();
                ctx.fillRect(0, 0, width, height);
            }
            if (colorZones.length > 0) {
                var remainingWidth = width - this._canvasLeftOffset;
                if (this._lanesCount >= 3) {
                    this._renderThreeLanes(ctx, colorZones, id2Color, remainingWidth);
                }
                else if (this._lanesCount === 2) {
                    this._renderTwoLanes(ctx, colorZones, id2Color, remainingWidth);
                }
                else if (this._lanesCount === 1) {
                    this._renderOneLane(ctx, colorZones, id2Color, remainingWidth);
                }
            }
            return true;
        };
        OverviewRulerImpl.prototype._renderOneLane = function (ctx, colorZones, id2Color, w) {
            this._renderVerticalPatch(ctx, colorZones, id2Color, editorCommon_1.OverviewRulerLane.Left | editorCommon_1.OverviewRulerLane.Center | editorCommon_1.OverviewRulerLane.Right, this._canvasLeftOffset, w);
        };
        OverviewRulerImpl.prototype._renderTwoLanes = function (ctx, colorZones, id2Color, w) {
            var leftWidth = Math.floor(w / 2);
            var rightWidth = w - leftWidth;
            var leftOffset = this._canvasLeftOffset;
            var rightOffset = this._canvasLeftOffset + leftWidth;
            this._renderVerticalPatch(ctx, colorZones, id2Color, editorCommon_1.OverviewRulerLane.Left | editorCommon_1.OverviewRulerLane.Center, leftOffset, leftWidth);
            this._renderVerticalPatch(ctx, colorZones, id2Color, editorCommon_1.OverviewRulerLane.Right, rightOffset, rightWidth);
        };
        OverviewRulerImpl.prototype._renderThreeLanes = function (ctx, colorZones, id2Color, w) {
            var leftWidth = Math.floor(w / 3);
            var rightWidth = Math.floor(w / 3);
            var centerWidth = w - leftWidth - rightWidth;
            var leftOffset = this._canvasLeftOffset;
            var centerOffset = this._canvasLeftOffset + leftWidth;
            var rightOffset = this._canvasLeftOffset + leftWidth + centerWidth;
            this._renderVerticalPatch(ctx, colorZones, id2Color, editorCommon_1.OverviewRulerLane.Left, leftOffset, leftWidth);
            this._renderVerticalPatch(ctx, colorZones, id2Color, editorCommon_1.OverviewRulerLane.Center, centerOffset, centerWidth);
            this._renderVerticalPatch(ctx, colorZones, id2Color, editorCommon_1.OverviewRulerLane.Right, rightOffset, rightWidth);
        };
        OverviewRulerImpl.prototype._renderVerticalPatch = function (ctx, colorZones, id2Color, laneMask, xpos, width) {
            var currentColorId = 0;
            var currentFrom = 0;
            var currentTo = 0;
            for (var i = 0, len = colorZones.length; i < len; i++) {
                var zone = colorZones[i];
                if (!(zone.position & laneMask)) {
                    continue;
                }
                var zoneColorId = zone.colorId;
                var zoneFrom = zone.from;
                var zoneTo = zone.to;
                if (zoneColorId !== currentColorId) {
                    ctx.fillRect(xpos, 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(xpos, currentFrom, width, currentTo - currentFrom);
                        currentFrom = zoneFrom;
                        currentTo = zoneTo;
                    }
                }
            }
            ctx.fillRect(xpos, currentFrom, width, currentTo - currentFrom);
        };
        return OverviewRulerImpl;
    }());
    exports.OverviewRulerImpl = OverviewRulerImpl;
});











define(__m[507/*vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler*/], __M([1/*require*/,0/*exports*/,20/*vs/editor/common/editorCommon*/,35/*vs/editor/browser/view/viewPart*/,190/*vs/editor/browser/viewParts/overviewRuler/overviewRulerImpl*/,17/*vs/editor/common/modes*/,140/*vs/editor/common/view/overviewZoneManager*/,37/*vs/editor/common/view/editorColorRegistry*/,32/*vs/base/common/color*/]), function (require, exports, editorCommon, viewPart_1, overviewRulerImpl_1, modes_1, overviewZoneManager_1, editorColorRegistry_1, color_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var DecorationsOverviewRuler = (function (_super) {
        __extends(DecorationsOverviewRuler, _super);
        function DecorationsOverviewRuler(context) {
            var _this = _super.call(this, context) || this;
            _this._overviewRuler = new overviewRulerImpl_1.OverviewRulerImpl(1, 'decorationsOverviewRuler', _this._context.viewLayout.getScrollHeight(), _this._context.configuration.editor.lineHeight, _this._context.configuration.editor.pixelRatio, DecorationsOverviewRuler.MIN_DECORATION_HEIGHT, DecorationsOverviewRuler.MAX_DECORATION_HEIGHT, function (lineNumber) { return _this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber); });
            _this._overviewRuler.setLanesCount(_this._context.configuration.editor.viewInfo.overviewRulerLanes, false);
            _this._overviewRuler.setLayout(_this._context.configuration.editor.layoutInfo.overviewRuler, false);
            _this._renderBorder = _this._context.configuration.editor.viewInfo.overviewRulerBorder;
            _this._updateColors();
            _this._updateBackground(false);
            _this._tokensColorTrackerListener = modes_1.TokenizationRegistry.onDidChange(function (e) {
                if (e.changedColorMap) {
                    _this._updateBackground(true);
                }
            });
            _this._shouldUpdateDecorations = true;
            _this._zonesFromDecorations = [];
            _this._shouldUpdateCursorPosition = true;
            _this._hideCursor = _this._context.configuration.editor.viewInfo.hideCursorInOverviewRuler;
            _this._zonesFromCursors = [];
            _this._cursorPositions = [];
            return _this;
        }
        DecorationsOverviewRuler.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this._overviewRuler.dispose();
            this._tokensColorTrackerListener.dispose();
        };
        DecorationsOverviewRuler.prototype._updateBackground = function (render) {
            var minimapEnabled = this._context.configuration.editor.viewInfo.minimap.enabled;
            this._overviewRuler.setUseBackground((minimapEnabled ? modes_1.TokenizationRegistry.getDefaultBackground() : null), render);
        };
        // ---- begin view event handlers
        DecorationsOverviewRuler.prototype.onConfigurationChanged = function (e) {
            var prevLanesCount = this._overviewRuler.getLanesCount();
            var newLanesCount = this._context.configuration.editor.viewInfo.overviewRulerLanes;
            if (prevLanesCount !== newLanesCount) {
                this._overviewRuler.setLanesCount(newLanesCount, false);
            }
            if (e.lineHeight) {
                this._overviewRuler.setLineHeight(this._context.configuration.editor.lineHeight, false);
            }
            if (e.pixelRatio) {
                this._overviewRuler.setPixelRatio(this._context.configuration.editor.pixelRatio, false);
            }
            if (e.viewInfo) {
                this._renderBorder = this._context.configuration.editor.viewInfo.overviewRulerBorder;
                this._hideCursor = this._context.configuration.editor.viewInfo.hideCursorInOverviewRuler;
                this._shouldUpdateCursorPosition = true;
                this._updateBackground(false);
            }
            if (e.layoutInfo) {
                this._overviewRuler.setLayout(this._context.configuration.editor.layoutInfo.overviewRuler, false);
            }
            return true;
        };
        DecorationsOverviewRuler.prototype.onCursorStateChanged = function (e) {
            this._shouldUpdateCursorPosition = true;
            this._cursorPositions = [];
            for (var i = 0, len = e.selections.length; i < len; i++) {
                this._cursorPositions[i] = e.selections[i].getPosition();
            }
            return true;
        };
        DecorationsOverviewRuler.prototype.onDecorationsChanged = function (e) {
            this._shouldUpdateDecorations = true;
            return true;
        };
        DecorationsOverviewRuler.prototype.onFlushed = function (e) {
            this._shouldUpdateCursorPosition = true;
            this._shouldUpdateDecorations = true;
            return true;
        };
        DecorationsOverviewRuler.prototype.onScrollChanged = function (e) {
            this._overviewRuler.setScrollHeight(e.scrollHeight, false);
            return _super.prototype.onScrollChanged.call(this, e) || e.scrollHeightChanged;
        };
        DecorationsOverviewRuler.prototype.onZonesChanged = function (e) {
            return true;
        };
        DecorationsOverviewRuler.prototype.onThemeChanged = function (e) {
            this._updateColors();
            this._shouldUpdateDecorations = true;
            this._shouldUpdateCursorPosition = true;
            return true;
        };
        // ---- end view event handlers
        DecorationsOverviewRuler.prototype.getDomNode = function () {
            return this._overviewRuler.getDomNode();
        };
        DecorationsOverviewRuler.prototype._updateColors = function () {
            var borderColor = this._context.theme.getColor(editorColorRegistry_1.editorOverviewRulerBorder);
            this._borderColor = borderColor ? borderColor.toString() : null;
            var cursorColor = this._context.theme.getColor(editorColorRegistry_1.editorCursorForeground);
            this._cursorColor = cursorColor ? cursorColor.transparent(0.7).toString() : null;
            this._overviewRuler.setThemeType(this._context.theme.type, false);
        };
        DecorationsOverviewRuler.prototype._createZonesFromDecorations = function () {
            var decorations = this._context.model.getAllOverviewRulerDecorations();
            var zones = [];
            for (var i = 0, len = decorations.length; i < len; i++) {
                var dec = decorations[i];
                var overviewRuler = dec.source.options.overviewRuler;
                zones.push(new overviewZoneManager_1.OverviewRulerZone(dec.range.startLineNumber, dec.range.endLineNumber, overviewRuler.position, 0, this.resolveRulerColor(overviewRuler.color), this.resolveRulerColor(overviewRuler.darkColor), this.resolveRulerColor(overviewRuler.hcColor)));
            }
            return zones;
        };
        DecorationsOverviewRuler.prototype.resolveRulerColor = function (color) {
            if (editorCommon.isThemeColor(color)) {
                var c = this._context.theme.getColor(color.id) || color_1.Color.transparent;
                return c.toString();
            }
            return color;
        };
        DecorationsOverviewRuler.prototype._createZonesFromCursors = function () {
            var zones = [];
            for (var i = 0, len = this._cursorPositions.length; i < len; i++) {
                var cursor = this._cursorPositions[i];
                zones.push(new overviewZoneManager_1.OverviewRulerZone(cursor.lineNumber, cursor.lineNumber, editorCommon.OverviewRulerLane.Full, 2, this._cursorColor, this._cursorColor, this._cursorColor));
            }
            return zones;
        };
        DecorationsOverviewRuler.prototype.prepareRender = function (ctx) {
            // Nothing to read
        };
        DecorationsOverviewRuler.prototype.render = function (ctx) {
            if (this._shouldUpdateDecorations || this._shouldUpdateCursorPosition) {
                if (this._shouldUpdateDecorations) {
                    this._shouldUpdateDecorations = false;
                    this._zonesFromDecorations = this._createZonesFromDecorations();
                }
                if (this._shouldUpdateCursorPosition) {
                    this._shouldUpdateCursorPosition = false;
                    if (this._hideCursor) {
                        this._zonesFromCursors = [];
                    }
                    else {
                        this._zonesFromCursors = this._createZonesFromCursors();
                    }
                }
                var allZones = [];
                allZones = allZones.concat(this._zonesFromCursors);
                allZones = allZones.concat(this._zonesFromDecorations);
                this._overviewRuler.setZones(allZones, false);
            }
            var hasRendered = this._overviewRuler.render(false);
            if (hasRendered && this._renderBorder && this._borderColor && this._overviewRuler.getLanesCount() > 0 && (this._zonesFromDecorations.length > 0 || this._zonesFromCursors.length > 0)) {
                var ctx2 = this._overviewRuler.getDomNode().getContext('2d');
                ctx2.beginPath();
                ctx2.lineWidth = 1;
                ctx2.strokeStyle = this._borderColor;
                ctx2.moveTo(0, 0);
                ctx2.lineTo(0, this._overviewRuler.getPixelHeight());
                ctx2.stroke();
                ctx2.moveTo(0, 0);
                ctx2.lineTo(this._overviewRuler.getPixelWidth(), 0);
                ctx2.stroke();
            }
        };
        DecorationsOverviewRuler.MIN_DECORATION_HEIGHT = 6;
        DecorationsOverviewRuler.MAX_DECORATION_HEIGHT = 60;
        return DecorationsOverviewRuler;
    }(viewPart_1.ViewPart));
    exports.DecorationsOverviewRuler = DecorationsOverviewRuler;
});











define(__m[508/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/], __M([1/*require*/,0/*exports*/,82/*vs/editor/common/viewModel/viewEventHandler*/,190/*vs/editor/browser/viewParts/overviewRuler/overviewRulerImpl*/]), function (require, exports, viewEventHandler_1, overviewRulerImpl_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var OverviewRuler = (function (_super) {
        __extends(OverviewRuler, _super);
        function OverviewRuler(context, cssClassName, minimumHeight, maximumHeight) {
            var _this = _super.call(this) || this;
            _this._context = context;
            _this._overviewRuler = new overviewRulerImpl_1.OverviewRulerImpl(0, cssClassName, _this._context.viewLayout.getScrollHeight(), _this._context.configuration.editor.lineHeight, _this._context.configuration.editor.pixelRatio, minimumHeight, maximumHeight, function (lineNumber) { return _this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber); });
            _this._context.addEventHandler(_this);
            return _this;
        }
        OverviewRuler.prototype.dispose = function () {
            this._context.removeEventHandler(this);
            this._overviewRuler.dispose();
            _super.prototype.dispose.call(this);
        };
        // ---- begin view event handlers
        OverviewRuler.prototype.onConfigurationChanged = function (e) {
            if (e.lineHeight) {
                this._overviewRuler.setLineHeight(this._context.configuration.editor.lineHeight, true);
            }
            if (e.pixelRatio) {
                this._overviewRuler.setPixelRatio(this._context.configuration.editor.pixelRatio, true);
            }
            return true;
        };
        OverviewRuler.prototype.onFlushed = function (e) {
            return true;
        };
        OverviewRuler.prototype.onScrollChanged = function (e) {
            this._overviewRuler.setScrollHeight(e.scrollHeight, true);
            return _super.prototype.onScrollChanged.call(this, e) || e.scrollHeightChanged;
        };
        OverviewRuler.prototype.onZonesChanged = function (e) {
            return true;
        };
        // ---- end view event handlers
        OverviewRuler.prototype.getDomNode = function () {
            return this._overviewRuler.getDomNode();
        };
        OverviewRuler.prototype.setLayout = function (position) {
            this._overviewRuler.setLayout(position, true);
        };
        OverviewRuler.prototype.setZones = function (zones) {
            this._overviewRuler.setZones(zones, true);
        };
        return OverviewRuler;
    }(viewEventHandler_1.ViewEventHandler));
    exports.OverviewRuler = OverviewRuler;
});











define(__m[509/*vs/editor/browser/view/viewImpl*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,4/*vs/base/browser/dom*/,27/*vs/base/browser/fastDomNode*/,2/*vs/editor/common/core/range*/,82/*vs/editor/common/viewModel/viewEventHandler*/,501/*vs/editor/browser/controller/textAreaHandler*/,490/*vs/editor/browser/controller/pointerHandler*/,449/*vs/editor/browser/view/viewController*/,217/*vs/editor/common/view/viewEventDispatcher*/,443/*vs/editor/browser/view/viewOverlays*/,230/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/,497/*vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/,498/*vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight*/,231/*vs/editor/browser/viewParts/decorations/decorations*/,113/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/,188/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/,499/*vs/editor/browser/viewParts/indentGuides/indentGuides*/,492/*vs/editor/browser/viewParts/lines/viewLines*/,182/*vs/editor/browser/viewParts/margin/margin*/,233/*vs/editor/browser/viewParts/linesDecorations/linesDecorations*/,235/*vs/editor/browser/viewParts/marginDecorations/marginDecorations*/,236/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/,507/*vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler*/,508/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/,502/*vs/editor/browser/viewParts/rulers/rulers*/,494/*vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/,495/*vs/editor/browser/viewParts/selections/selections*/,503/*vs/editor/browser/viewParts/viewCursors/viewCursors*/,237/*vs/editor/browser/viewParts/viewZones/viewZones*/,35/*vs/editor/browser/view/viewPart*/,216/*vs/editor/common/view/viewContext*/,78/*vs/editor/common/view/renderingContext*/,491/*vs/editor/browser/view/viewOutgoingEvents*/,221/*vs/editor/common/viewLayout/viewLinesViewportData*/,486/*vs/editor/browser/viewParts/editorScrollbar/editorScrollbar*/,493/*vs/editor/browser/viewParts/minimap/minimap*/,57/*vs/editor/common/view/viewEvents*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, errors_1, dom, fastDomNode_1, range_1, viewEventHandler_1, textAreaHandler_1, pointerHandler_1, viewController_1, viewEventDispatcher_1, viewOverlays_1, contentWidgets_1, currentLineHighlight_1, currentLineMarginHighlight_1, decorations_1, glyphMargin_1, lineNumbers_1, indentGuides_1, viewLines_1, margin_1, linesDecorations_1, marginDecorations_1, overlayWidgets_1, decorationsOverviewRuler_1, overviewRuler_1, rulers_1, scrollDecoration_1, selections_1, viewCursors_1, viewZones_1, viewPart_1, viewContext_1, renderingContext_1, viewOutgoingEvents_1, viewLinesViewportData_1, editorScrollbar_1, minimap_1, viewEvents, themeService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var View = (function (_super) {
        __extends(View, _super);
        function View(commandService, configuration, themeService, model, cursor, execCoreEditorCommandFunc) {
            var _this = _super.call(this) || this;
            _this._isDisposed = false;
            _this._cursor = cursor;
            _this._renderAnimationFrame = null;
            _this.outgoingEvents = new viewOutgoingEvents_1.ViewOutgoingEvents(model);
            var viewController = new viewController_1.ViewController(configuration, model, execCoreEditorCommandFunc, _this.outgoingEvents, commandService);
            // 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 decorations_1.DecorationsOverlay(this._context));
            contentViewOverlays.addDynamicOverlay(new indentGuides_1.IndentGuidesOverlay(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();
                    var visibleRanges = _this.viewLines.visibleRangesForRange2(new range_1.Range(lineNumber, column, lineNumber, column));
                    if (!visibleRanges) {
                        return null;
                    }
                    return visibleRanges[0];
                },
                getLineWidth: function (lineNumber) {
                    _this._flushAccumulatedAndRenderNow();
                    return _this.viewLines.getLineWidth(lineNumber);
                }
            };
        };
        View.prototype.createTextAreaHandlerHelper = function () {
            var _this = this;
            return {
                visibleRangeForPositionRelativeToEditor: function (lineNumber, column) {
                    _this._flushAccumulatedAndRenderNow();
                    var visibleRanges = _this.viewLines.visibleRangesForRange2(new range_1.Range(lineNumber, column, lineNumber, column));
                    if (!visibleRanges) {
                        return null;
                    }
                    return visibleRanges[0];
                }
            };
        };
        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 () {
            return this._context.configuration.editor.editorClassName + ' ' + themeService_1.getThemeTypeSelector(this._context.theme.type);
        };
        // --- 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.toggleClassName('focused', 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 () {
            this._isDisposed = true;
            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 = [];
            for (var i = 0, len = this.viewParts.length; i < len; i++) {
                var viewPart = this.viewParts[i];
                if (viewPart.shouldRender()) {
                    result.push(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.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.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 visibleRanges = this.viewLines.visibleRangesForRange2(new range_1.Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column));
            if (!visibleRanges) {
                return -1;
            }
            return visibleRanges[0].left;
        };
        View.prototype.getTargetAtClientPoint = function (clientX, clientY) {
            return this.pointerHandler.getTargetAtClientPoint(clientX, clientY);
        };
        View.prototype.getInternalEventBus = function () {
            return this.outgoingEvents;
        };
        View.prototype.createOverviewRuler = function (cssClassName, minimumHeight, maximumHeight) {
            return new overviewRuler_1.OverviewRuler(this._context, cssClassName, minimumHeight, maximumHeight);
        };
        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 = null;
                changeAccessor.removeZone = null;
                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.setAriaActiveDescendant = function (id) {
            this._textAreaHandler.setAriaActiveDescendant(id);
        };
        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 newPreference = widgetData.position ? widgetData.position.preference : null;
            this.contentWidgets.setWidgetPosition(widgetData.widget, newPosition, 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);
        }
    }
});




















define(__m[191/*vs/editor/browser/widget/codeEditorWidget*/], __M([1/*require*/,0/*exports*/,10/*vs/base/common/errors*/,4/*vs/base/browser/dom*/,16/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/commands/common/commands*/,19/*vs/platform/contextkey/common/contextkey*/,447/*vs/editor/common/commonCodeEditor*/,2/*vs/editor/common/core/range*/,42/*vs/editor/common/services/codeEditorService*/,66/*vs/editor/browser/config/configuration*/,509/*vs/editor/browser/view/viewImpl*/,3/*vs/base/common/lifecycle*/,11/*vs/base/common/event*/,149/*vs/editor/common/editorAction*/,14/*vs/platform/theme/common/themeService*/,37/*vs/editor/common/view/editorColorRegistry*/,310/*vs/css!vs/editor/browser/widget/media/editor*/,312/*vs/css!vs/editor/browser/widget/media/tokens*/]), function (require, exports, errors_1, dom, instantiation_1, commands_1, contextkey_1, commonCodeEditor_1, range_1, codeEditorService_1, configuration_1, viewImpl_1, lifecycle_1, event_1, editorAction_1, themeService_1, editorColorRegistry_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CodeEditorWidget = (function (_super) {
        __extends(CodeEditorWidget, _super);
        function CodeEditorWidget(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, themeService) {
            var _this = _super.call(this, domElement, options, instantiationService, contextKeyService) || this;
            _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._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._codeEditorService = codeEditorService;
            _this._commandService = commandService;
            _this._themeService = themeService;
            _this._focusTracker = new CodeEditorWidgetFocusTracker(domElement);
            _this._focusTracker.onChange(function () {
                var hasFocus = _this._focusTracker.hasFocus();
                if (hasFocus) {
                    _this._onDidFocusEditor.fire();
                }
                else {
                    _this._onDidBlurEditor.fire();
                }
            });
            _this.contentWidgets = {};
            _this.overlayWidgets = {};
            var contributions = _this._getContributions();
            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);
                }
            }
            _this._getActions().forEach(function (action) {
                var internalAction = new editorAction_1.InternalEditorAction(action.id, action.label, action.alias, action.precondition, function () {
                    return _this._instantiationService.invokeFunction(function (accessor) {
                        return action.runEditorCommand(accessor, _this, null);
                    });
                }, _this._contextKeyService);
                _this._actions[internalAction.id] = internalAction;
            });
            _this._codeEditorService.addCodeEditor(_this);
            return _this;
        }
        CodeEditorWidget.prototype._createConfiguration = function (options) {
            return new configuration_1.Configuration(options, this.domElement);
        };
        CodeEditorWidget.prototype.dispose = function () {
            this._codeEditorService.removeCodeEditor(this);
            this.contentWidgets = {};
            this.overlayWidgets = {};
            this._focusTracker.dispose();
            _super.prototype.dispose.call(this);
        };
        CodeEditorWidget.prototype.createOverviewRuler = function (cssClassName, minimumHeight, maximumHeight) {
            return this._view.createOverviewRuler(cssClassName, minimumHeight, maximumHeight);
        };
        CodeEditorWidget.prototype.getDomNode = function () {
            if (!this.hasView) {
                return null;
            }
            return this._view.domNode.domNode;
        };
        CodeEditorWidget.prototype.getCompletelyVisibleLinesRangeInViewport = function () {
            if (!this.hasView) {
                return null;
            }
            var viewRange = this.viewModel.getCompletelyVisibleViewRange();
            return this.viewModel.coordinatesConverter.convertViewRangeToModelRange(viewRange);
        };
        CodeEditorWidget.prototype.delegateVerticalScrollbarMouseDown = function (browserEvent) {
            if (!this.hasView) {
                return;
            }
            this._view.delegateVerticalScrollbarMouseDown(browserEvent);
        };
        CodeEditorWidget.prototype.layout = function (dimension) {
            this._configuration.observeReferenceElement(dimension);
            this.render();
        };
        CodeEditorWidget.prototype.focus = function () {
            if (!this.hasView) {
                return;
            }
            this._view.focus();
        };
        CodeEditorWidget.prototype.isFocused = function () {
            return this.hasView && this._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.hasView) {
                this._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.hasView) {
                    this._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.hasView) {
                    this._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.hasView) {
                this._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.hasView) {
                    this._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.hasView) {
                    this._view.removeOverlayWidget(widgetData);
                }
            }
        };
        CodeEditorWidget.prototype.changeViewZones = function (callback) {
            if (!this.hasView) {
                return;
            }
            var hasChanges = this._view.change(callback);
            if (hasChanges) {
                this._onDidChangeViewZones.fire();
            }
        };
        CodeEditorWidget.prototype.getWhitespaces = function () {
            if (!this.hasView) {
                return [];
            }
            return this.viewModel.viewLayout.getWhitespaces();
        };
        CodeEditorWidget.prototype._getVerticalOffsetForPosition = function (modelLineNumber, modelColumn) {
            var modelPosition = this.model.validatePosition({
                lineNumber: modelLineNumber,
                column: modelColumn
            });
            var viewPosition = this.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
            return this.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
        };
        CodeEditorWidget.prototype.getTopForLineNumber = function (lineNumber) {
            if (!this.hasView) {
                return -1;
            }
            return this._getVerticalOffsetForPosition(lineNumber, 1);
        };
        CodeEditorWidget.prototype.getTopForPosition = function (lineNumber, column) {
            if (!this.hasView) {
                return -1;
            }
            return this._getVerticalOffsetForPosition(lineNumber, column);
        };
        CodeEditorWidget.prototype.getTargetAtClientPoint = function (clientX, clientY) {
            if (!this.hasView) {
                return null;
            }
            return this._view.getTargetAtClientPoint(clientX, clientY);
        };
        CodeEditorWidget.prototype.getScrolledVisiblePosition = function (rawPosition) {
            if (!this.hasView) {
                return null;
            }
            var position = this.model.validatePosition(rawPosition);
            var layoutInfo = this._configuration.editor.layoutInfo;
            var top = this._getVerticalOffsetForPosition(position.lineNumber, position.column) - this.getScrollTop();
            var left = this._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.hasView) {
                return -1;
            }
            return this._view.getOffsetForColumn(lineNumber, column);
        };
        CodeEditorWidget.prototype.render = function () {
            if (!this.hasView) {
                return;
            }
            this._view.render(true, false);
        };
        CodeEditorWidget.prototype.setHiddenAreas = function (ranges) {
            if (this.viewModel) {
                this.viewModel.setHiddenAreas(ranges.map(function (r) { return range_1.Range.lift(r); }));
            }
        };
        CodeEditorWidget.prototype.setAriaActiveDescendant = function (id) {
            if (!this.hasView) {
                return;
            }
            this._view.setAriaActiveDescendant(id);
        };
        CodeEditorWidget.prototype.applyFontInfo = function (target) {
            configuration_1.Configuration.applyFontInfoSlow(target, this._configuration.editor.fontInfo);
        };
        CodeEditorWidget.prototype._attachModel = function (model) {
            this._view = null;
            _super.prototype._attachModel.call(this, model);
            if (this._view) {
                this.domElement.appendChild(this._view.domNode.domNode);
                var keys = Object.keys(this.contentWidgets);
                for (var i = 0, len = keys.length; i < len; i++) {
                    var widgetId = keys[i];
                    this._view.addContentWidget(this.contentWidgets[widgetId]);
                }
                keys = Object.keys(this.overlayWidgets);
                for (var i = 0, len = keys.length; i < len; i++) {
                    var widgetId = keys[i];
                    this._view.addOverlayWidget(this.overlayWidgets[widgetId]);
                }
                this._view.render(false, true);
                this.hasView = true;
            }
        };
        CodeEditorWidget.prototype._createView = function () {
            var _this = this;
            this._view = new viewImpl_1.View(this._commandService, this._configuration, this._themeService, this.viewModel, this.cursor, function (editorCommand, args) {
                if (!_this.cursor) {
                    return;
                }
                editorCommand.runCoreEditorCommand(_this.cursor, args);
            });
            var viewEventBus = this._view.getInternalEventBus();
            this.listenersToRemove.push(viewEventBus.onDidGainFocus(function () {
                _this._onDidFocusEditorText.fire();
                // In IE, the focus is not synchronous, so we give it a little help
                _this._onDidFocusEditor.fire();
            }));
            this.listenersToRemove.push(viewEventBus.onDidScroll(function (e) {
                _this._onDidScrollChange.fire(e);
            }));
            this.listenersToRemove.push(viewEventBus.onDidLoseFocus(function () {
                _this._onDidBlurEditorText.fire();
            }));
            this.listenersToRemove.push(viewEventBus.onContextMenu(function (e) {
                _this._onContextMenu.fire(e);
            }));
            this.listenersToRemove.push(viewEventBus.onMouseDown(function (e) {
                _this._onMouseDown.fire(e);
            }));
            this.listenersToRemove.push(viewEventBus.onMouseUp(function (e) {
                _this._onMouseUp.fire(e);
            }));
            this.listenersToRemove.push(viewEventBus.onMouseDrag(function (e) {
                _this._onMouseDrag.fire(e);
            }));
            this.listenersToRemove.push(viewEventBus.onMouseDrop(function (e) {
                _this._onMouseDrop.fire(e);
            }));
            this.listenersToRemove.push(viewEventBus.onKeyUp(function (e) {
                _this._onKeyUp.fire(e);
            }));
            this.listenersToRemove.push(viewEventBus.onMouseMove(function (e) {
                _this._onMouseMove.fire(e);
            }));
            this.listenersToRemove.push(viewEventBus.onMouseLeave(function (e) {
                _this._onMouseLeave.fire(e);
            }));
            this.listenersToRemove.push(viewEventBus.onKeyDown(function (e) {
                _this._onKeyDown.fire(e);
            }));
        };
        CodeEditorWidget.prototype._detachModel = function () {
            var removeDomNode = null;
            if (this._view) {
                this._view.dispose();
                removeDomNode = this._view.domNode.domNode;
                this._view = null;
            }
            var result = _super.prototype._detachModel.call(this);
            if (removeDomNode) {
                this.domElement.removeChild(removeDomNode);
            }
            return result;
        };
        // BEGIN decorations
        CodeEditorWidget.prototype._registerDecorationType = function (key, options, parentTypeKey) {
            this._codeEditorService.registerDecorationType(key, options, parentTypeKey);
        };
        CodeEditorWidget.prototype._removeDecorationType = function (key) {
            this._codeEditorService.removeDecorationType(key);
        };
        CodeEditorWidget.prototype._resolveDecorationOptions = function (typeKey, writable) {
            return this._codeEditorService.resolveDecorationOptions(typeKey, writable);
        };
        CodeEditorWidget = __decorate([
            __param(2, instantiation_1.IInstantiationService),
            __param(3, codeEditorService_1.ICodeEditorService),
            __param(4, commands_1.ICommandService),
            __param(5, contextkey_1.IContextKeyService),
            __param(6, themeService_1.IThemeService)
        ], CodeEditorWidget);
        return CodeEditorWidget;
    }(commonCodeEditor_1.CommonCodeEditor));
    exports.CodeEditorWidget = CodeEditorWidget;
    var CodeEditorWidgetFocusTracker = (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._domFocusTracker.addFocusListener(function () {
                _this._hasFocus = true;
                _this._onChange.fire(void 0);
            });
            _this._domFocusTracker.addBlurListener(function () {
                _this._hasFocus = false;
                _this._onChange.fire(void 0);
            });
            return _this;
        }
        CodeEditorWidgetFocusTracker.prototype.hasFocus = function () {
            return this._hasFocus;
        };
        return CodeEditorWidgetFocusTracker;
    }(lifecycle_1.Disposable));
    var squigglyStart = encodeURIComponent("<svg xmlns='http://www.w3.org/2000/svg' height='3' width='6'><g fill='");
    var squigglyEnd = encodeURIComponent("'><polygon points='5.5,0 2.5,3 1.1,3 4.1,0'/><polygon points='4,0 6,2 6,0.6 5.4,0'/><polygon points='0,2 1,3 2.4,3 0,0.6'/></g></svg>");
    function getSquigglySVGData(color) {
        return squigglyStart + encodeURIComponent(color.toString()) + squigglyEnd;
    }
    themeService_1.registerThemingParticipant(function (theme, collector) {
        var errorBorderColor = theme.getColor(editorColorRegistry_1.editorErrorBorder);
        if (errorBorderColor) {
            collector.addRule(".monaco-editor .redsquiggly { border-bottom: 4px double " + errorBorderColor + "; }");
        }
        var errorForeground = theme.getColor(editorColorRegistry_1.editorErrorForeground);
        if (errorForeground) {
            collector.addRule(".monaco-editor .redsquiggly { 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 .greensquiggly { border-bottom: 4px double " + warningBorderColor + "; }");
        }
        var warningForeground = theme.getColor(editorColorRegistry_1.editorWarningForeground);
        if (warningForeground) {
            collector.addRule(".monaco-editor .greensquiggly { background: url(\"data:image/svg+xml;utf8," + getSquigglySVGData(warningForeground) + "\") repeat-x bottom left; }");
        }
    });
});




















define(__m[141/*vs/editor/browser/codeEditor*/], __M([1/*require*/,0/*exports*/,16/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/commands/common/commands*/,19/*vs/platform/contextkey/common/contextkey*/,42/*vs/editor/common/services/codeEditorService*/,191/*vs/editor/browser/widget/codeEditorWidget*/,13/*vs/editor/common/editorCommonExtensions*/,30/*vs/editor/browser/editorBrowserExtensions*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, instantiation_1, commands_1, contextkey_1, codeEditorService_1, codeEditorWidget_1, editorCommonExtensions_1, editorBrowserExtensions_1, themeService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CodeEditor = (function (_super) {
        __extends(CodeEditor, _super);
        function CodeEditor(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, themeService) {
            return _super.call(this, domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, themeService) || this;
        }
        CodeEditor.prototype._getContributions = function () {
            return [].concat(editorBrowserExtensions_1.EditorBrowserRegistry.getEditorContributions()).concat(editorCommonExtensions_1.CommonEditorRegistry.getEditorContributions());
        };
        CodeEditor.prototype._getActions = function () {
            return editorCommonExtensions_1.CommonEditorRegistry.getEditorActions();
        };
        CodeEditor = __decorate([
            __param(2, instantiation_1.IInstantiationService),
            __param(3, codeEditorService_1.ICodeEditorService),
            __param(4, commands_1.ICommandService),
            __param(5, contextkey_1.IContextKeyService),
            __param(6, themeService_1.IThemeService)
        ], CodeEditor);
        return CodeEditor;
    }(codeEditorWidget_1.CodeEditorWidget));
    exports.CodeEditor = CodeEditor;
});

/*---------------------------------------------------------------------------------------------
 *  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/browser/widget/diffEditorWidget*/], __M([1/*require*/,0/*exports*/,302/*vs/nls!vs/editor/browser/widget/diffEditorWidget*/,18/*vs/base/common/async*/,3/*vs/base/common/lifecycle*/,26/*vs/base/common/objects*/,4/*vs/base/browser/dom*/,36/*vs/base/common/severity*/,27/*vs/base/browser/fastDomNode*/,99/*vs/base/browser/ui/sash/sash*/,16/*vs/platform/instantiation/common/instantiation*/,19/*vs/platform/contextkey/common/contextkey*/,42/*vs/editor/common/services/codeEditorService*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,61/*vs/editor/common/services/editorWorkerService*/,138/*vs/editor/common/viewLayout/lineDecorations*/,106/*vs/editor/common/viewLayout/viewLineRenderer*/,141/*vs/editor/browser/codeEditor*/,90/*vs/editor/common/core/viewLineToken*/,66/*vs/editor/browser/config/configuration*/,86/*vs/editor/common/viewModel/viewModel*/,84/*vs/platform/instantiation/common/serviceCollection*/,11/*vs/base/common/event*/,49/*vs/editor/common/config/editorOptions*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,140/*vs/editor/common/view/overviewZoneManager*/,34/*vs/editor/common/model/textModelWithDecorations*/,504/*vs/editor/browser/widget/diffReview*/,50/*vs/platform/message/common/message*/,308/*vs/css!vs/editor/browser/widget/media/diffEditor*/]), function (require, exports, nls, async_1, lifecycle_1, objects, dom, severity_1, fastDomNode_1, sash_1, instantiation_1, contextkey_1, codeEditorService_1, range_1, editorCommon, editorWorkerService_1, lineDecorations_1, viewLineRenderer_1, codeEditor_1, viewLineToken_1, configuration_1, viewModel_1, serviceCollection_1, event_1, editorOptions, themeService_1, colorRegistry_1, overviewZoneManager_1, textModelWithDecorations_1, diffReview_1, message_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var VisualEditorState = (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
            if (this._decorations.length > 0) {
                editor.changeDecorations(function (changeAccessor) {
                    changeAccessor.deltaDecorations(_this._decorations, []);
                });
            }
            this._decorations = [];
        };
        VisualEditorState.prototype.apply = function (editor, overviewRuler, newDecorations) {
            var _this = this;
            // 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;
                }
            });
            // 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 = (function (_super) {
        __extends(DiffEditorWidget, _super);
        function DiffEditorWidget(domElement, options, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, messageService) {
            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 = contextKeyService.createScoped(domElement);
            _this._contextKeyService.createKey('isInDiffEditor', true);
            _this._themeService = themeService;
            _this._messageService = messageService;
            _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._lineChanges = null;
            var services = new serviceCollection_1.ServiceCollection();
            services.set(contextkey_1.IContextKeyService, _this._contextKeyService);
            var scopedInstantiationService = instantiationService.createChild(services);
            _this._createLeftHandSideEditor(options, scopedInstantiationService);
            _this._createRightHandSideEditor(options, scopedInstantiationService);
            _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._codeEditorService.addDiffEditor(_this);
            _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);
            }));
            return _this;
        }
        Object.defineProperty(DiffEditorWidget.prototype, "ignoreTrimWhitespace", {
            get: function () {
                return this._ignoreTrimWhitespace;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DiffEditorWidget.prototype, "renderSideBySide", {
            get: function () {
                return this._renderSideBySide;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DiffEditorWidget.prototype, "renderIndicators", {
            get: function () {
                return this._renderIndicators;
            },
            enumerable: true,
            configurable: true
        });
        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();
            }
            this._originalOverviewRuler = this.originalEditor.createOverviewRuler('original diffOverviewRuler', 4, Number.MAX_VALUE);
            this._overviewDomElement.appendChild(this._originalOverviewRuler.getDomNode());
            if (this._modifiedOverviewRuler) {
                this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode());
                this._modifiedOverviewRuler.dispose();
            }
            this._modifiedOverviewRuler = this.modifiedEditor.createOverviewRuler('modified diffOverviewRuler', 4, Number.MAX_VALUE);
            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(codeEditor_1.CodeEditor, container, options);
        };
        DiffEditorWidget.prototype.destroy = function () {
            this.dispose();
        };
        DiffEditorWidget.prototype.dispose = function () {
            this._codeEditorService.removeDiffEditor(this);
            window.clearInterval(this._measureDomElementToken);
            this._cleanViewZonesAndDecorations();
            this._originalOverviewRuler.dispose();
            this._modifiedOverviewRuler.dispose();
            this.originalEditor.dispose();
            this.modifiedEditor.dispose();
            this._strategy.dispose();
            this._reviewPane.dispose();
            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 () {
            return this._lineChanges;
        };
        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.getValue = function (options) {
            if (options === void 0) { options = null; }
            return this.modifiedEditor.getValue(options);
        };
        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._lineChanges = null;
            this._diffComputationToken++;
            if (model) {
                this._recreateOverviewRulers();
                // Begin comparing
                this._beginUpdateDecorations();
            }
            else {
                this._lineChanges = 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, reveal, revealVerticalInCenter, revealHorizontal) {
            this.modifiedEditor.setPosition(position, reveal, revealVerticalInCenter, revealHorizontal);
        };
        DiffEditorWidget.prototype.revealLine = function (lineNumber) {
            this.modifiedEditor.revealLine(lineNumber);
        };
        DiffEditorWidget.prototype.revealLineInCenter = function (lineNumber) {
            this.modifiedEditor.revealLineInCenter(lineNumber);
        };
        DiffEditorWidget.prototype.revealLineInCenterIfOutsideViewport = function (lineNumber) {
            this.modifiedEditor.revealLineInCenterIfOutsideViewport(lineNumber);
        };
        DiffEditorWidget.prototype.revealPosition = function (position, revealVerticalInCenter, revealHorizontal) {
            if (revealVerticalInCenter === void 0) { revealVerticalInCenter = false; }
            if (revealHorizontal === void 0) { revealHorizontal = false; }
            this.modifiedEditor.revealPosition(position, revealVerticalInCenter, revealHorizontal);
        };
        DiffEditorWidget.prototype.revealPositionInCenter = function (position) {
            this.modifiedEditor.revealPositionInCenter(position);
        };
        DiffEditorWidget.prototype.revealPositionInCenterIfOutsideViewport = function (position) {
            this.modifiedEditor.revealPositionInCenterIfOutsideViewport(position);
        };
        DiffEditorWidget.prototype.getSelection = function () {
            return this.modifiedEditor.getSelection();
        };
        DiffEditorWidget.prototype.getSelections = function () {
            return this.modifiedEditor.getSelections();
        };
        DiffEditorWidget.prototype.setSelection = function (something, reveal, revealVerticalInCenter, revealHorizontal) {
            this.modifiedEditor.setSelection(something, reveal, revealVerticalInCenter, revealHorizontal);
        };
        DiffEditorWidget.prototype.setSelections = function (ranges) {
            this.modifiedEditor.setSelections(ranges);
        };
        DiffEditorWidget.prototype.revealLines = function (startLineNumber, endLineNumber) {
            this.modifiedEditor.revealLines(startLineNumber, endLineNumber);
        };
        DiffEditorWidget.prototype.revealLinesInCenter = function (startLineNumber, endLineNumber) {
            this.modifiedEditor.revealLinesInCenter(startLineNumber, endLineNumber);
        };
        DiffEditorWidget.prototype.revealLinesInCenterIfOutsideViewport = function (startLineNumber, endLineNumber) {
            this.modifiedEditor.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber);
        };
        DiffEditorWidget.prototype.revealRange = function (range, revealVerticalInCenter, revealHorizontal) {
            if (revealVerticalInCenter === void 0) { revealVerticalInCenter = false; }
            if (revealHorizontal === void 0) { revealHorizontal = true; }
            this.modifiedEditor.revealRange(range, revealVerticalInCenter, revealHorizontal);
        };
        DiffEditorWidget.prototype.revealRangeInCenter = function (range) {
            this.modifiedEditor.revealRangeInCenter(range);
        };
        DiffEditorWidget.prototype.revealRangeInCenterIfOutsideViewport = function (range) {
            this.modifiedEditor.revealRangeInCenterIfOutsideViewport(range);
        };
        DiffEditorWidget.prototype.revealRangeAtTop = function (range) {
            this.modifiedEditor.revealRangeAtTop(range);
        };
        DiffEditorWidget.prototype.getActions = function () {
            return this.modifiedEditor.getActions();
        };
        DiffEditorWidget.prototype.getSupportedActions = function () {
            return this.modifiedEditor.getSupportedActions();
        };
        DiffEditorWidget.prototype.getAction = function (id) {
            return this.modifiedEditor.getAction(id);
        };
        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.original) {
                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.isFocused = function () {
            return this.originalEditor.isFocused() || this.modifiedEditor.isFocused();
        };
        DiffEditorWidget.prototype.onVisible = function () {
            this._isVisible = true;
            this.originalEditor.onVisible();
            this.modifiedEditor.onVisible();
            // Begin comparing
            this._beginUpdateDecorations();
        };
        DiffEditorWidget.prototype.onHide = function () {
            this._isVisible = false;
            this.originalEditor.onHide();
            this.modifiedEditor.onHide();
            // Remove all view zones & decorations
            this._cleanViewZonesAndDecorations();
        };
        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._messageService.show(severity_1.default.Warning, 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._lineChanges = result;
                    _this._updateDecorationsRunner.schedule();
                    _this._onDidUpdateDiff.fire();
                }
            }, function (error) {
                if (currentToken === _this._diffComputationToken
                    && currentOriginalModel === _this.originalEditor.getModel()
                    && currentModifiedModel === _this.modifiedEditor.getModel()) {
                    _this._lineChanges = 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._lineChanges || [];
            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);
                this._modifiedEditorState.apply(this.modifiedEditor, this._modifiedOverviewRuler, diffDecorations.modified);
            }
            finally {
                this._currentlyChangingViewZones = false;
            }
        };
        DiffEditorWidget.prototype._adjustOptionsForSubEditor = function (options) {
            var clonedOptions = objects.clone(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._lineChanges) {
                this._updateDecorations();
            }
            // Just do a layout, the strategy might need it
            this._measureDomElement(true);
        };
        DiffEditorWidget.prototype._getLineChangeAtOrBeforeLineNumber = function (lineNumber, startLineNumberExtractor) {
            if (this._lineChanges.length === 0 || lineNumber < startLineNumberExtractor(this._lineChanges[0])) {
                // There are no changes or `lineNumber` is before the first change
                return null;
            }
            var min = 0, max = this._lineChanges.length - 1;
            while (min < max) {
                var mid = Math.floor((min + max) / 2);
                var midStart = startLineNumberExtractor(this._lineChanges[mid]);
                var midEnd = (mid + 1 <= max ? startLineNumberExtractor(this._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 this._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._lineChanges) {
                // Cannot answer that which I don't know
                return null;
            }
            return {
                equivalentLineNumber: this._getEquivalentLineForOriginalLineNumber(lineNumber)
            };
        };
        DiffEditorWidget.prototype.getDiffLineInformationForModified = function (lineNumber) {
            if (!this._lineChanges) {
                // 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, message_1.IMessageService)
        ], DiffEditorWidget);
        return DiffEditorWidget;
    }(lifecycle_1.Disposable));
    exports.DiffEditorWidget = DiffEditorWidget;
    var DiffEditorWidgetStyle = (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
                }
            };
        };
        DiffEditorWidgetStyle.prototype._getViewZones = function (lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators) {
            return null;
        };
        DiffEditorWidgetStyle.prototype._getOriginalEditorDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) {
            return null;
        };
        DiffEditorWidgetStyle.prototype._getModifiedEditorDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) {
            return null;
        };
        return DiffEditorWidgetStyle;
    }(lifecycle_1.Disposable));
    var ForeignViewZonesIterator = (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 = (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;
                    }
                    stepOriginal.push({
                        afterLineNumber: viewZoneLineNumber,
                        heightInLines: modifiedForeignVZ.current.heightInLines,
                        domNode: null
                    });
                    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
            }
            var ensureDomNode = function (z) {
                if (!z.domNode) {
                    z.domNode = createFakeLinesDiv();
                }
            };
            result.original.forEach(ensureDomNode);
            result.modified.forEach(ensureDomNode);
            return result;
        };
        return ViewZonesComputer;
    }());
    function createDecoration(startLineNumber, startColumn, endLineNumber, endColumn, options) {
        return {
            range: new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn),
            options: options
        };
    }
    var DECORATIONS = {
        charDelete: textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'char-delete'
        }),
        charDeleteWholeLine: textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'char-delete',
            isWholeLine: true
        }),
        charInsert: textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'char-insert'
        }),
        charInsertWholeLine: textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'char-insert',
            isWholeLine: true
        }),
        lineInsert: textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'line-insert',
            marginClassName: 'line-insert',
            isWholeLine: true
        }),
        lineInsertWithSign: textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'line-insert',
            linesDecorationsClassName: 'insert-sign',
            marginClassName: 'line-insert',
            isWholeLine: true
        }),
        lineDelete: textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'line-delete',
            marginClassName: 'line-delete',
            isWholeLine: true
        }),
        lineDeleteWithSign: textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'line-delete',
            linesDecorationsClassName: 'delete-sign',
            marginClassName: 'line-delete',
            isWholeLine: true
        }),
        lineDeleteMargin: textModelWithDecorations_1.ModelDecorationOptions.register({
            marginClassName: 'line-delete',
        })
    };
    var DiffEdtorWidgetSideBySide = (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.disable();
            }
            _this._sash.addListener('start', function () { return _this.onSashDragStart(); });
            _this._sash.addListener('change', function (e) { return _this.onSashDrag(e); });
            _this._sash.addListener('end', function () { return _this.onSashDragEnd(); });
            _this._sash.addListener('reset', function () { return _this.onSashReset(); });
            return _this;
        }
        DiffEdtorWidgetSideBySide.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
        };
        DiffEdtorWidgetSideBySide.prototype.setEnableSplitViewResizing = function (enableSplitViewResizing) {
            var newDisableSash = (enableSplitViewResizing === false);
            if (this._disableSash !== newDisableSash) {
                this._disableSash = newDisableSash;
                if (this._disableSash) {
                    this._sash.disable();
                }
                else {
                    this._sash.enable();
                }
            }
        };
        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 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));
                    }
                    var color = this._removeColor.toString();
                    result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber, editorCommon.OverviewRulerLane.Full, 0, color, color, color));
                    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 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));
                    }
                    var color = this._insertColor.toString();
                    result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber, editorCommon.OverviewRulerLane.Full, 0, color, color, color));
                    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 = (function (_super) {
        __extends(SideBySideViewZonesComputer, _super);
        function SideBySideViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ) {
            return _super.call(this, lineChanges, originalForeignVZ, modifiedForeignVZ) || this;
        }
        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 = (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.dispose = function () {
            _super.prototype.dispose.call(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 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
                    });
                    var color = this._removeColor.toString();
                    result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber, editorCommon.OverviewRulerLane.Full, 0, color, color, color));
                }
            }
            return result;
        };
        DiffEdtorWidgetInline.prototype._getModifiedEditorDecorations = function (lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) {
            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)
                    });
                    var color = this._insertColor.toString();
                    result.overviewZones.push(new overviewZoneManager_1.OverviewRulerZone(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber, editorCommon.OverviewRulerLane.Full, 0, color, color, color));
                    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 = (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._produceOriginalFromDiff = function (lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
            var marginDomNode = document.createElement('div');
            marginDomNode.className = 'inline-added-margin-view-zone';
            configuration_1.Configuration.applyFontInfoSlow(marginDomNode, this.modifiedEditorConfiguration.fontInfo);
            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', false));
                    }
                }
            }
            var html = [];
            var marginHTML = [];
            var lineDecorationsWidth = this.modifiedEditorConfiguration.layoutInfo.decorationsWidth;
            var lineHeight = this.modifiedEditorConfiguration.lineHeight;
            for (var lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) {
                html = html.concat(this.renderOriginalLine(lineNumber - lineChange.originalStartLineNumber, this.originalModel, this.modifiedEditorConfiguration, this.modifiedEditorTabSize, lineNumber, decorations));
                if (this.renderIndicators) {
                    var index = lineNumber - lineChange.originalStartLineNumber;
                    marginHTML = marginHTML.concat([
                        "<div class=\"delete-sign\" style=\"position:absolute;top:" + index * lineHeight + "px;width:" + lineDecorationsWidth + "px;height:" + lineHeight + "px;right:0;\"></div>"
                    ]);
                }
            }
            var domNode = document.createElement('div');
            domNode.className = 'view-lines line-delete';
            domNode.innerHTML = html.join('');
            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,
                domNode: domNode,
                marginDomNode: marginDomNode
            };
        };
        InlineViewZonesComputer.prototype.renderOriginalLine = function (count, originalModel, config, tabSize, lineNumber, decorations) {
            var lineContent = originalModel.getLineContent(lineNumber);
            var actualDecorations = lineDecorations_1.LineDecoration.filter(decorations, lineNumber, 1, lineContent.length + 1);
            var defaultMetadata = ((0 /* None */ << 11 /* FONT_STYLE_OFFSET */)
                | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */)
                | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0;
            var r = viewLineRenderer_1.renderViewLine(new viewLineRenderer_1.RenderLineInput((config.fontInfo.isMonospace && !config.viewInfo.disableMonospaceOptimizations), lineContent, originalModel.mightContainRTL(), 0, [new viewLineToken_1.ViewLineToken(lineContent.length, defaultMetadata)], actualDecorations, tabSize, config.fontInfo.spaceWidth, config.viewInfo.stopRenderingLineAfter, config.viewInfo.renderWhitespace, config.viewInfo.renderControlCharacters, config.viewInfo.fontLigatures));
            var myResult = [];
            myResult.push('<div class="view-line');
            if (decorations.length === 0) {
                // No char changes
                myResult.push(' char-delete');
            }
            myResult.push('" style="top:');
            myResult.push(String(count * config.lineHeight));
            myResult.push('px;width:1000000px;">');
            myResult = myResult.concat(r.html);
            myResult.push('</div>');
            return myResult;
        };
        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 dashed " + addedOutline + "; }");
        }
        var removedOutline = theme.getColor(colorRegistry_1.diffRemovedOutline);
        if (removedOutline) {
            collector.addRule(".monaco-editor .line-delete, .monaco-editor .char-delete { border: 1px dashed " + 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 + "; }");
        }
    });
});




















define(__m[194/*vs/editor/browser/widget/embeddedCodeEditorWidget*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/objects*/,16/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/commands/common/commands*/,19/*vs/platform/contextkey/common/contextkey*/,42/*vs/editor/common/services/codeEditorService*/,141/*vs/editor/browser/codeEditor*/,14/*vs/platform/theme/common/themeService*/]), function (require, exports, objects, instantiation_1, commands_1, contextkey_1, codeEditorService_1, codeEditor_1, themeService_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var EmbeddedCodeEditorWidget = (function (_super) {
        __extends(EmbeddedCodeEditorWidget, _super);
        function EmbeddedCodeEditorWidget(domElement, options, parentEditor, instantiationService, codeEditorService, commandService, contextKeyService, themeService) {
            var _this = _super.call(this, domElement, parentEditor.getRawConfiguration(), instantiationService, codeEditorService, commandService, contextKeyService, themeService) || 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)
        ], EmbeddedCodeEditorWidget);
        return EmbeddedCodeEditorWidget;
    }(codeEditor_1.CodeEditor));
    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[514/*vs/editor/contrib/bracketMatching/common/bracketMatching*/], __M([1/*require*/,0/*exports*/,341/*vs/nls!vs/editor/contrib/bracketMatching/common/bracketMatching*/,3/*vs/base/common/lifecycle*/,12/*vs/editor/common/core/position*/,18/*vs/base/common/async*/,20/*vs/editor/common/editorCommon*/,13/*vs/editor/common/editorCommonExtensions*/,21/*vs/editor/common/editorContextKeys*/,14/*vs/platform/theme/common/themeService*/,37/*vs/editor/common/view/editorColorRegistry*/,34/*vs/editor/common/model/textModelWithDecorations*/]), function (require, exports, nls, lifecycle_1, position_1, async_1, editorCommon, editorCommonExtensions_1, editorContextKeys_1, themeService_1, editorColorRegistry_1, textModelWithDecorations_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var SelectBracketAction = (function (_super) {
        __extends(SelectBracketAction, _super);
        function SelectBracketAction() {
            return _super.call(this, {
                id: 'editor.action.jumpToBracket',
                label: nls.localize(0, null),
                alias: 'Go to Bracket',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 88 /* US_BACKSLASH */
                }
            }) || this;
        }
        SelectBracketAction.prototype.run = function (accessor, editor) {
            var controller = BracketMatchingController.get(editor);
            if (!controller) {
                return;
            }
            controller.jumpToBracket();
        };
        SelectBracketAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], SelectBracketAction);
        return SelectBracketAction;
    }(editorCommonExtensions_1.EditorAction));
    var BracketsData = (function () {
        function BracketsData(position, brackets) {
            this.position = position;
            this.brackets = brackets;
        }
        return BracketsData;
    }());
    var BracketMatchingController = (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.onDidChangeModel(function (e) { _this._decorations = []; _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_1 = BracketMatchingController;
        BracketMatchingController.get = function (editor) {
            return editor.getContribution(BracketMatchingController_1.ID);
        };
        BracketMatchingController.prototype.getId = function () {
            return BracketMatchingController_1.ID;
        };
        BracketMatchingController.prototype.jumpToBracket = function () {
            var model = this._editor.getModel();
            if (!model) {
                return;
            }
            var selection = this._editor.getSelection();
            if (!selection.isEmpty()) {
                return;
            }
            var position = selection.getStartPosition();
            var brackets = model.matchBracket(position);
            if (!brackets) {
                return;
            }
            var resultingPosition = null;
            if (brackets[0].containsPosition(position)) {
                resultingPosition = brackets[1].getStartPosition();
            }
            else if (brackets[1].containsPosition(position)) {
                resultingPosition = brackets[0].getStartPosition();
            }
            if (resultingPosition) {
                this._editor.setPosition(resultingPosition);
                this._editor.revealPosition(resultingPosition);
            }
        };
        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_1._DECORATION_OPTIONS };
                    newDecorations[newDecorationsLen++] = { range: brackets[1], options: BracketMatchingController_1._DECORATION_OPTIONS };
                }
            }
            this._decorations = this._editor.deltaDecorations(this._decorations, newDecorations);
        };
        BracketMatchingController.prototype._recomputeBrackets = function () {
            var model = this._editor.getModel();
            if (!model) {
                // no model => no brackets!
                this._lastBracketsData = [];
                this._lastVersionId = 0;
                return;
            }
            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 = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            className: 'bracket-match'
        });
        BracketMatchingController = BracketMatchingController_1 = __decorate([
            editorCommonExtensions_1.commonEditorContribution
        ], BracketMatchingController);
        return BracketMatchingController;
        var BracketMatchingController_1;
    }(lifecycle_1.Disposable));
    exports.BracketMatchingController = BracketMatchingController;
    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 + "; }");
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  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/contrib/codelens/browser/codelensWidget*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,36/*vs/base/common/severity*/,9/*vs/base/common/strings*/,4/*vs/base/browser/dom*/,2/*vs/editor/common/core/range*/,25/*vs/editor/browser/editorBrowser*/,34/*vs/editor/common/model/textModelWithDecorations*/,37/*vs/editor/common/view/editorColorRegistry*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,315/*vs/css!vs/editor/contrib/codelens/browser/codelensWidget*/]), function (require, exports, lifecycle_1, severity_1, strings_1, dom, range_1, editorBrowser, textModelWithDecorations_1, editorColorRegistry_1, themeService_1, colorRegistry_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CodeLensViewZone = (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 = (function () {
        function CodeLensContentWidget(editor, symbolRange, commandService, messageService) {
            var _this = this;
            // Editor.IContentWidget.allowEditorOverflow
            this.allowEditorOverflow = false;
            this.suppressMouseDown = true;
            this._disposables = [];
            this._commands = Object.create(null);
            this._id = 'codeLensWidget' + (++CodeLensContentWidget._idPool);
            this._editor = editor;
            this.setSymbolRange(symbolRange);
            this._domNode = document.createElement('span');
            this._domNode.innerHTML = '&nbsp;';
            dom.addClass(this._domNode, 'codelens-decoration');
            dom.addClass(this._domNode, 'invisible-cl');
            this._updateHeight();
            this._disposables.push(this._editor.onDidChangeConfiguration(function (e) { return e.fontInfo && _this._updateHeight(); }));
            this._disposables.push(dom.addDisposableListener(this._domNode, 'click', function (e) {
                var element = e.target;
                if (element.tagName === 'A' && element.id) {
                    var command = _this._commands[element.id];
                    if (command) {
                        editor.focus();
                        commandService.executeCommand.apply(commandService, [command.id].concat(command.arguments)).done(undefined, function (err) {
                            messageService.show(severity_1.default.Error, err);
                        });
                    }
                }
            }));
            this.updateVisibility();
        }
        CodeLensContentWidget.prototype.dispose = function () {
            lifecycle_1.dispose(this._disposables);
            this._symbolRange = null;
        };
        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 * .9) + "px";
            this._domNode.innerHTML = '&nbsp;';
        };
        CodeLensContentWidget.prototype.updateVisibility = function () {
            if (this.isVisible()) {
                dom.removeClass(this._domNode, 'invisible-cl');
                dom.addClass(this._domNode, 'fadein');
            }
        };
        CodeLensContentWidget.prototype.withCommands = function (symbols) {
            this._commands = Object.create(null);
            if (!symbols || !symbols.length) {
                this._domNode.innerHTML = 'no commands';
                return;
            }
            var html = [];
            for (var i = 0; i < symbols.length; i++) {
                var command = symbols[i].command;
                var title = strings_1.escape(command.title);
                var part = void 0;
                if (command.id) {
                    part = strings_1.format('<a id={0}>{1}</a>', i, title);
                    this._commands[i] = command;
                }
                else {
                    part = strings_1.format('<span>{0}</span>', title);
                }
                html.push(part);
            }
            this._domNode.innerHTML = html.join('<span>&nbsp;|&nbsp;</span>');
            this._editor.layoutContentWidget(this);
        };
        CodeLensContentWidget.prototype.getId = function () {
            return this._id;
        };
        CodeLensContentWidget.prototype.getDomNode = function () {
            return this._domNode;
        };
        CodeLensContentWidget.prototype.setSymbolRange = function (range) {
            this._symbolRange = range;
            var lineNumber = range.startLineNumber;
            var column = this._editor.getModel().getLineFirstNonWhitespaceColumn(lineNumber);
            this._widgetPosition = {
                position: { lineNumber: lineNumber, column: column },
                preference: [editorBrowser.ContentWidgetPositionPreference.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 = (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 = (function () {
        function CodeLens(data, editor, helper, viewZoneChangeAccessor, commandService, messageService, updateCallabck) {
            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: textModelWithDecorations_1.ModelDecorationOptions.EMPTY
                }, function (id) { return _this._decorationIds[i] = id; });
                // the range contains all lenses on this line
                if (!range) {
                    range = range_1.Range.lift(codeLensData.symbol.range);
                }
                else {
                    range = range_1.Range.plusRange(range, codeLensData.symbol.range);
                }
            });
            this._contentWidget = new CodeLensContentWidget(editor, range, commandService, messageService);
            this._viewZone = new CodeLensViewZone(range.startLineNumber - 1, updateCallabck);
            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);
            this._contentWidget.dispose();
        };
        CodeLens.prototype.isValid = function () {
            var _this = this;
            return this._decorationIds.some(function (id, i) {
                var range = _this._editor.getModel().getDecorationRange(id);
                var symbol = _this._data[i].symbol;
                return range && range_1.Range.isEmpty(symbol.range) === range.isEmpty();
            });
        };
        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: textModelWithDecorations_1.ModelDecorationOptions.EMPTY
                }, function (id) { return _this._decorationIds[i] = id; });
            });
        };
        CodeLens.prototype.computeIfNecessary = function (model) {
            this._contentWidget.updateVisibility(); // trigger the fade in
            if (!this._contentWidget.isVisible()) {
                return null;
            }
            // Read editor current state
            for (var i = 0; i < this._decorationIds.length; i++) {
                this._data[i].symbol.range = model.getDecorationRange(this._decorationIds[i]);
            }
            return this._data;
        };
        CodeLens.prototype.updateCommands = function (symbols) {
            this._contentWidget.withCommands(symbols);
        };
        CodeLens.prototype.getLineNumber = function () {
            var range = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
            if (range) {
                return range.startLineNumber;
            }
            return -1;
        };
        CodeLens.prototype.update = function (viewZoneChangeAccessor) {
            if (this.isValid()) {
                var range = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
                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[516/*vs/editor/contrib/codelens/browser/codelensController*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/async*/,10/*vs/base/common/errors*/,3/*vs/base/common/lifecycle*/,7/*vs/base/common/winjs.base*/,31/*vs/platform/commands/common/commands*/,50/*vs/platform/message/common/message*/,17/*vs/editor/common/modes*/,30/*vs/editor/browser/editorBrowserExtensions*/,453/*vs/editor/contrib/codelens/browser/codelens*/,515/*vs/editor/contrib/codelens/browser/codelensWidget*/]), function (require, exports, async_1, errors_1, lifecycle_1, winjs_base_1, commands_1, message_1, modes_1, editorBrowserExtensions_1, codelens_1, codelensWidget_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var CodeLensContribution = (function () {
        function CodeLensContribution(_editor, _commandService, _messageService) {
            var _this = this;
            this._editor = _editor;
            this._commandService = _commandService;
            this._messageService = _messageService;
            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_1 = CodeLensContribution;
        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._currentFindOccPromise) {
                this._currentFindOccPromise.cancel();
                this._currentFindOccPromise = null;
            }
            this._localToDispose = lifecycle_1.dispose(this._localToDispose);
        };
        CodeLensContribution.prototype.getId = function () {
            return CodeLensContribution_1.ID;
        };
        CodeLensContribution.prototype._onModelChange = function () {
            var _this = this;
            this._localDispose();
            var model = this._editor.getModel();
            if (!model) {
                return;
            }
            if (!this._isEnabled) {
                return;
            }
            if (!modes_1.CodeLensProviderRegistry.has(model)) {
                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(model.getLanguageIdentifier().language);
            }, 500);
            var scheduler = new async_1.RunOnceScheduler(function () {
                if (_this._currentFindCodeLensSymbolsPromise) {
                    _this._currentFindCodeLensSymbolsPromise.cancel();
                }
                _this._currentFindCodeLensSymbolsPromise = codelens_1.getCodeLensData(model);
                var counterValue = ++_this._modelChangeCounter;
                _this._currentFindCodeLensSymbolsPromise.then(function (result) {
                    if (counterValue === _this._modelChangeCounter) {
                        _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 = [];
                        _this._lenses.forEach(function (lens) {
                            if (lens.isValid()) {
                                lens.update(viewAccessor);
                            }
                            else {
                                toDispose.push(lens);
                            }
                        });
                        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._detectVisibleLenses.schedule();
                }
            }));
            this._localToDispose.push(this._editor.onDidLayoutChange(function (e) {
                _this._detectVisibleLenses.schedule();
            }));
            this._localToDispose.push({
                dispose: function () {
                    if (_this._editor.getModel()) {
                        _this._editor.changeDecorations(function (changeAccessor) {
                            _this._editor.changeViewZones(function (accessor) {
                                _this._disposeAllLenses(changeAccessor, accessor);
                            });
                        });
                    }
                    else {
                        // No accessors available
                        _this._disposeAllLenses(null, null);
                    }
                }
            });
            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.getModel()) {
                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 centeredRange = this._editor.getCenteredRangeInViewport();
            var shouldRestoreCenteredRange = centeredRange && (groups.length !== this._lenses.length && this._editor.getScrollTop() !== 0);
            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, _this._commandService, _this._messageService, 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, _this._commandService, _this._messageService, function () { return _this._detectVisibleLenses.schedule(); }));
                        groupsIndex++;
                    }
                    helper.commit(changeAccessor);
                });
            });
            if (shouldRestoreCenteredRange) {
                this._editor.revealRangeInCenter(centeredRange);
            }
        };
        CodeLensContribution.prototype._onViewportChanged = function (modeId) {
            var _this = this;
            if (this._currentFindOccPromise) {
                this._currentFindOccPromise.cancel();
                this._currentFindOccPromise = 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;
            }
            var promises = toResolve.map(function (request, i) {
                var resolvedSymbols = new Array(request.length);
                var promises = request.map(function (request, i) {
                    return async_1.asWinJsPromise(function (token) {
                        return request.provider.resolveCodeLens(model, request.symbol, token);
                    }).then(function (symbol) {
                        resolvedSymbols[i] = symbol;
                    });
                });
                return winjs_base_1.TPromise.join(promises).then(function () {
                    lenses[i].updateCommands(resolvedSymbols);
                });
            });
            this._currentFindOccPromise = winjs_base_1.TPromise.join(promises).then(function () {
                _this._currentFindOccPromise = null;
            });
        };
        CodeLensContribution.ID = 'css.editor.codeLens';
        CodeLensContribution = CodeLensContribution_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, commands_1.ICommandService),
            __param(2, message_1.IMessageService)
        ], CodeLensContribution);
        return CodeLensContribution;
        var CodeLensContribution_1;
    }());
    exports.CodeLensContribution = 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[517/*vs/editor/contrib/colorPicker/browser/colorPicker*/], __M([1/*require*/,0/*exports*/,30/*vs/editor/browser/editorBrowserExtensions*/,3/*vs/base/common/lifecycle*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,17/*vs/editor/common/modes*/,7/*vs/base/common/winjs.base*/,248/*vs/editor/contrib/colorPicker/common/colorPicker*/]), function (require, exports, editorBrowserExtensions_1, lifecycle_1, themeService_1, colorRegistry_1, modes_1, winjs_base_1, colorPicker_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var ColorPicker = (function () {
        function ColorPicker(editor) {
            var _this = this;
            this.editor = editor;
            this.currentDecorations = [];
            this.listenersToRemove = [];
            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.ColorProviderRegistry.onDidChange(function (e) { return _this.onModelModeChanged(); }));
            this.timeoutPromise = null;
            this.computePromise = null;
            this.beginCompute();
        }
        ColorPicker_1 = ColorPicker;
        ColorPicker.prototype.getId = function () {
            return ColorPicker_1.ID;
        };
        ColorPicker.get = function (editor) {
            return editor.getContribution(this.ID);
        };
        ColorPicker.prototype.dispose = function () {
            this.listenersToRemove = lifecycle_1.dispose(this.listenersToRemove);
            this.stop();
        };
        ColorPicker.prototype.onModelChanged = function () {
            this.stop();
            this.beginCompute();
        };
        ColorPicker.prototype.onModelModeChanged = function () {
            this.stop();
            this.beginCompute();
        };
        ColorPicker.prototype.onChange = function () {
            var _this = this;
            if (!this.timeoutPromise) {
                this.timeoutPromise = winjs_base_1.TPromise.timeout(ColorPicker_1.RECOMPUTE_TIME);
                this.timeoutPromise.then(function () {
                    _this.timeoutPromise = null;
                    _this.beginCompute();
                });
            }
        };
        ColorPicker.prototype.beginCompute = function () {
            var _this = this;
            if (!this.editor.getModel()) {
                return;
            }
            if (!modes_1.ColorProviderRegistry.has(this.editor.getModel())) {
                return;
            }
            this.computePromise = colorPicker_1.getColors(this.editor.getModel()).then(function (colorInfos) {
                _this.updateDecorations(colorInfos);
                _this.computePromise = null;
            });
        };
        ColorPicker.prototype.stop = function () {
            if (this.timeoutPromise) {
                this.timeoutPromise.cancel();
                this.timeoutPromise = null;
            }
            if (this.computePromise) {
                this.computePromise.cancel();
                this.computePromise = null;
            }
        };
        ColorPicker.prototype.updateDecorations = function (colorInfos) {
            var _this = this;
            this.editor.changeDecorations(function (changeAccessor) {
                var newDecorations = [];
                for (var _i = 0, colorInfos_1 = colorInfos; _i < colorInfos_1.length; _i++) {
                    var c = colorInfos_1[_i];
                    var range = {
                        startLineNumber: c.range.startLineNumber,
                        startColumn: c.range.startColumn,
                        endLineNumber: c.range.endLineNumber,
                        endColumn: c.range.endColumn
                    };
                    var extraOptions = {
                        color: c.color,
                        format: c.format,
                        availableFormats: c.availableFormats
                    };
                    // TODO@Joao
                    var options = { __extraOptions: extraOptions };
                    newDecorations.push({ range: range, options: options });
                }
                _this.currentDecorations = changeAccessor.deltaDecorations(_this.currentDecorations, newDecorations);
            });
        };
        ColorPicker.ID = 'editor.contrib.colorPicker';
        ColorPicker.RECOMPUTE_TIME = 1000; // ms
        ColorPicker = ColorPicker_1 = __decorate([
            editorBrowserExtensions_1.editorContribution
        ], ColorPicker);
        return ColorPicker;
        var ColorPicker_1;
    }());
    exports.ColorPicker = ColorPicker;
    themeService_1.registerThemingParticipant(function (theme, collector) {
        var widgetBackground = theme.getColor(colorRegistry_1.editorWidgetBackground);
        collector.addRule(".monaco-editor .colorpicker-widget { background-color: " + widgetBackground + "; }");
        var widgetBorder = theme.getColor(colorRegistry_1.editorWidgetBorder);
        collector.addRule(".monaco-editor .colorpicker-widget { border: 1px solid " + widgetBorder + "; }");
        collector.addRule(".monaco-editor .colorpicker-header { border-bottom: 1px solid " + widgetBorder + "; }");
    });
});

/*---------------------------------------------------------------------------------------------
 *  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/contrib/find/browser/findOptionsWidget*/], __M([1/*require*/,0/*exports*/,4/*vs/base/browser/dom*/,41/*vs/base/browser/ui/widget*/,25/*vs/editor/browser/editorBrowser*/,121/*vs/editor/contrib/find/common/findModel*/,153/*vs/base/browser/ui/findinput/findInputCheckboxes*/,18/*vs/base/common/async*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, dom, widget_1, editorBrowser_1, findModel_1, findInputCheckboxes_1, async_1, themeService_1, colorRegistry_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var FindOptionsWidget = (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(); }, 1000));
            _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,
                onChange: function (viaKeyboard) {
                    _this._state.change({
                        matchCase: _this.caseSensitive.checked
                    }, false);
                },
                inputActiveOptionBorder: inputActiveOptionBorderColor
            }));
            _this._domNode.appendChild(_this.caseSensitive.domNode);
            _this.wholeWords = _this._register(new findInputCheckboxes_1.WholeWordsCheckbox({
                appendTitle: _this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleWholeWordCommand),
                isChecked: _this._state.wholeWord,
                onChange: function (viaKeyboard) {
                    _this._state.change({
                        wholeWord: _this.wholeWords.checked
                    }, false);
                },
                inputActiveOptionBorder: inputActiveOptionBorderColor
            }));
            _this._domNode.appendChild(_this.wholeWords.domNode);
            _this.regex = _this._register(new findInputCheckboxes_1.RegexCheckbox({
                appendTitle: _this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleRegexCommand),
                isChecked: _this._state.isRegex,
                onChange: function (viaKeyboard) {
                    _this._state.change({
                        isRegex: _this.regex.checked
                    }, false);
                },
                inputActiveOptionBorder: inputActiveOptionBorderColor
            }));
            _this._domNode.appendChild(_this.regex.domNode);
            _this._editor.addOverlayWidget(_this);
            _this._register(_this._state.addChangeListener(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: editorBrowser_1.OverlayWidgetPositionPreference.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[519/*vs/editor/contrib/find/browser/findWidget*/], __M([1/*require*/,0/*exports*/,347/*vs/nls!vs/editor/contrib/find/browser/findWidget*/,10/*vs/base/common/errors*/,15/*vs/base/common/platform*/,9/*vs/base/common/strings*/,4/*vs/base/browser/dom*/,289/*vs/base/browser/ui/findinput/findInput*/,115/*vs/base/browser/ui/inputbox/inputBox*/,41/*vs/base/browser/ui/widget*/,99/*vs/base/browser/ui/sash/sash*/,25/*vs/editor/browser/editorBrowser*/,121/*vs/editor/contrib/find/common/findModel*/,2/*vs/editor/common/core/range*/,176/*vs/editor/contrib/find/common/findController*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,327/*vs/css!vs/editor/contrib/find/browser/findWidget*/]), function (require, exports, nls, errors_1, platform, strings, dom, findInput_1, inputBox_1, widget_1, sash_1, editorBrowser_1, findModel_1, range_1, findController_1, themeService_1, colorRegistry_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);
    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 = (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 = (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._isVisible = false;
            _this._isReplaceVisible = false;
            _this._register(_this._state.addChangeListener(function (e) { return _this._onStateChanged(e); }));
            _this._buildDomNode();
            _this._updateButtons();
            var checkEditorWidth = function () {
                var editorWidth = _this._codeEditor.getConfiguration().layoutInfo.width;
                var minimapWidth = _this._codeEditor.getConfiguration().layoutInfo.minimapWidth;
                var collapsedFindWidget = false;
                var reducedFindWidget = false;
                var narrowFindWidget = false;
                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";
                }
                var findInputWidth = dom.getTotalWidth(_this._findInput.inputBox.inputElement);
                if (findInputWidth > 0) {
                    _this._replaceInputBox.inputElement.style.width = findInputWidth + "px";
                }
            };
            checkEditorWidth();
            _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) {
                    checkEditorWidth();
                }
            }));
            _this._register(_this._codeEditor.onDidChangeCursorSelection(function () {
                if (_this._isVisible) {
                    _this._updateToggleSelectionFindButton();
                }
            }));
            _this._findInputFocussed = findController_1.CONTEXT_FIND_INPUT_FOCUSSED.bindTo(contextKeyService);
            _this._focusTracker = _this._register(dom.trackFocus(_this._findInput.inputBox.inputElement));
            _this._focusTracker.addFocusListener(function () {
                _this._findInputFocussed.set(true);
                if (_this._toggleSelectionFind.checked) {
                    var selection = _this._codeEditor.getSelection();
                    if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
                        selection = selection.setEndPosition(selection.endLineNumber - 1, 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);
                        }
                    }
                }
            });
            _this._focusTracker.addBlurListener(function () {
                _this._findInputFocussed.set(false);
            });
            _this._codeEditor.addOverlayWidget(_this);
            _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 (e) {
                if (!_this._isVisible) {
                    return;
                }
                if (_this._viewZoneId === undefined) {
                    return;
                }
                _this._codeEditor.changeViewZones(function (accessor) {
                    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: editorBrowser_1.OverlayWidgetPositionPreference.TOP_RIGHT_CORNER
                };
            }
            return null;
        };
        // ----- React to state changes
        FindWidget.prototype._onStateChanged = function (e) {
            if (e.searchString) {
                this._findInput.setValue(this._state.searchString);
                this._updateButtons();
            }
            if (e.replaceString) {
                this._replaceInputBox.value = this._state.replaceString;
            }
            if (e.isRevealed) {
                if (this._state.isRevealed) {
                    this._reveal(true);
                }
                else {
                    this._hide(true);
                }
            }
            if (e.isReplaceRevealed) {
                if (this._state.isReplaceRevealed) {
                    if (!this._codeEditor.getConfiguration().readOnly && !this._isReplaceVisible) {
                        this._isReplaceVisible = true;
                        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();
            }
            if (e.searchString || e.currentMatch) {
                this._layoutViewZone();
            }
        };
        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);
            this._prevBtn.setEnabled(this._isVisible && findInputIsNonEmpty);
            this._nextBtn.setEnabled(this._isVisible && findInputIsNonEmpty);
            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 (animate) {
            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._updateButtons();
                setTimeout(function () {
                    dom.addClass(_this._domNode, 'visible');
                    _this._domNode.setAttribute('aria-hidden', 'false');
                    if (!animate) {
                        dom.addClass(_this._domNode, 'noanimation');
                        setTimeout(function () {
                            dom.removeClass(_this._domNode, 'noanimation');
                        }, 200);
                    }
                }, 0);
                this._codeEditor.layoutOverlayWidget(this);
                var adjustEditorScrollTop = true;
                if (this._codeEditor.getConfiguration().contribInfo.find.seedSearchStringFromSelection && selection) {
                    var editorCoords = dom.getDomNodePagePosition(this._codeEditor.getDomNode());
                    var startCoords = this._codeEditor.getScrolledVisiblePosition(selection.getStartPosition());
                    var startLeft = editorCoords.left + startCoords.left;
                    var startTop = startCoords.top;
                    if (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.left;
                        if (endLeft > leftOfFindWidget) {
                            adjustEditorScrollTop = false;
                        }
                    }
                }
                this._showViewZone(adjustEditorScrollTop);
            }
        };
        FindWidget.prototype._hide = function (focusTheEditor) {
            var _this = this;
            if (this._isVisible) {
                this._isVisible = false;
                this._updateButtons();
                dom.removeClass(this._domNode, 'visible');
                this._domNode.setAttribute('aria-hidden', 'true');
                if (focusTheEditor) {
                    this._codeEditor.focus();
                }
                this._codeEditor.layoutOverlayWidget(this);
                this._codeEditor.changeViewZones(function (accessor) {
                    if (_this._viewZoneId !== undefined) {
                        accessor.removeZone(_this._viewZoneId);
                        _this._viewZoneId = undefined;
                        _this._codeEditor.setScrollTop(_this._codeEditor.getScrollTop() - _this._viewZone.heightInPx);
                    }
                });
            }
        };
        FindWidget.prototype._layoutViewZone = function () {
            var _this = this;
            if (!this._isVisible) {
                return;
            }
            if (this._viewZoneId !== undefined) {
                return;
            }
            this._codeEditor.changeViewZones(function (accessor) {
                if (_this._state.isReplaceRevealed) {
                    _this._viewZone.heightInPx = FIND_REPLACE_AREA_HEIGHT;
                }
                else {
                    _this._viewZone.heightInPx = FIND_INPUT_AREA_HEIGHT;
                }
                _this._viewZoneId = accessor.addZone(_this._viewZone);
                // scroll top adjust to make sure the editor doesn't scroll when adding viewzone at the beginning.
                _this._codeEditor.setScrollTop(_this._codeEditor.getScrollTop() + _this._viewZone.heightInPx);
            });
        };
        FindWidget.prototype._showViewZone = function (adjustScroll) {
            var _this = this;
            if (adjustScroll === void 0) { adjustScroll = true; }
            if (!this._isVisible) {
                return;
            }
            this._codeEditor.changeViewZones(function (accessor) {
                var scrollAdjustment = FIND_INPUT_AREA_HEIGHT;
                if (_this._viewZoneId !== undefined) {
                    if (_this._state.isReplaceRevealed) {
                        _this._viewZone.heightInPx = FIND_REPLACE_AREA_HEIGHT;
                        scrollAdjustment = FIND_REPLACE_AREA_HEIGHT - FIND_INPUT_AREA_HEIGHT;
                    }
                    else {
                        _this._viewZone.heightInPx = FIND_INPUT_AREA_HEIGHT;
                        scrollAdjustment = FIND_INPUT_AREA_HEIGHT - FIND_REPLACE_AREA_HEIGHT;
                    }
                    accessor.removeZone(_this._viewZoneId);
                }
                else {
                    _this._viewZone.heightInPx = FIND_INPUT_AREA_HEIGHT;
                }
                _this._viewZoneId = accessor.addZone(_this._viewZone);
                if (adjustScroll) {
                    _this._codeEditor.setScrollTop(_this._codeEditor.getScrollTop() + scrollAdjustment);
                }
            });
        };
        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),
                inputValidationInfoBorder: theme.getColor(colorRegistry_1.inputValidationInfoBorder),
                inputValidationWarningBackground: theme.getColor(colorRegistry_1.inputValidationWarningBackground),
                inputValidationWarningBorder: theme.getColor(colorRegistry_1.inputValidationWarningBorder),
                inputValidationErrorBackground: theme.getColor(colorRegistry_1.inputValidationErrorBackground),
                inputValidationErrorBorder: theme.getColor(colorRegistry_1.inputValidationErrorBorder)
            };
            this._findInput.style(inputStyles);
            this._replaceInputBox.style(inputStyles);
        };
        // ----- 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._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().done(null, errors_1.onUnexpectedError);
                e.preventDefault();
                return;
            }
            if (e.equals(1024 /* Shift */ | 3 /* Enter */)) {
                this._codeEditor.getAction(findModel_1.FIND_IDS.PreviousMatchFindAction).run().done(null, 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 findInput_1.FindInput(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) {
                        return null;
                    }
                    if (!_this._findInput.getRegex()) {
                        return null;
                    }
                    try {
                        /* tslint:disable:no-unused-expression */
                        new RegExp(value);
                        /* tslint:enable:no-unused-expression */
                        return null;
                    }
                    catch (e) {
                        return { content: e.message };
                    }
                }
            }));
            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.onInput(function () {
                _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().done(null, errors_1.onUnexpectedError);
                },
                onKeyDown: function (e) { }
            }));
            // 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().done(null, errors_1.onUnexpectedError);
                },
                onKeyDown: function (e) { }
            }));
            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) {
                        var selection = _this._codeEditor.getSelection();
                        if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
                            selection = selection.setEndPosition(selection.endLineNumber - 1, 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 inputBox_1.InputBox(replaceInput, null, {
                ariaLabel: NLS_REPLACE_INPUT_LABEL,
                placeholder: NLS_REPLACE_INPUT_PLACEHOLDER
            }));
            this._register(dom.addStandardDisposableListener(this._replaceInputBox.inputElement, 'keydown', function (e) { return _this._onReplaceInputKeyDown(e); }));
            this._register(dom.addStandardDisposableListener(this._replaceInputBox.inputElement, 'input', function (e) {
                _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();
                },
                onKeyDown: function (e) { }
            }));
            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();
                },
                onKeyDown: function (e) { }
            }));
            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: sash_1.Orientation.VERTICAL });
            var originalWidth = FIND_WIDGET_INITIAL_WIDTH;
            this._register(this._resizeSash.addListener('start', function (e) {
                originalWidth = dom.getTotalWidth(_this._domNode);
            }));
            this._register(this._resizeSash.addListener('change', function (evt) {
                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.ID = 'editor.contrib.findWidget';
        return FindWidget;
    }(widget_1.Widget));
    exports.FindWidget = FindWidget;
    var SimpleCheckbox = (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 recieves 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 (e) {
                _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.focus = function () {
            this._checkbox.focus();
        };
        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 = (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;
                }
                _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) {
        function addBackgroundColorRule(selector, color) {
            if (color) {
                collector.addRule(".monaco-editor " + selector + " { background-color: " + color + "; }");
            }
        }
        addBackgroundColorRule('.findMatch', theme.getColor(colorRegistry_1.editorFindMatchHighlight));
        addBackgroundColorRule('.currentFindMatch', theme.getColor(colorRegistry_1.editorFindMatch));
        addBackgroundColorRule('.findScope', theme.getColor(colorRegistry_1.editorFindRangeHighlight));
        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 hcOutline = theme.getColor(colorRegistry_1.activeContrastBorder);
        if (hcOutline) {
            collector.addRule(".monaco-editor .findScope { border: 1px dashed " + hcOutline.transparent(0.4) + "; }");
            collector.addRule(".monaco-editor .currentFindMatch { border: 2px solid " + hcOutline + "; padding: 1px; -moz-box-sizing: border-box; box-sizing: border-box; }");
            collector.addRule(".monaco-editor .findMatch { border: 1px dotted " + hcOutline + "; -moz-box-sizing: border-box; box-sizing: border-box; }");
        }
        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 border = theme.getColor('panel.border');
        if (border) {
            collector.addRule(".monaco-editor .find-widget .monaco-sash { background-color: " + border + "; width: 3px !important; margin-left: -4px;}");
        }
    });
});




















define(__m[520/*vs/editor/contrib/find/browser/find*/], __M([1/*require*/,0/*exports*/,69/*vs/platform/contextview/browser/contextView*/,46/*vs/platform/keybinding/common/keybinding*/,19/*vs/platform/contextkey/common/contextkey*/,30/*vs/editor/browser/editorBrowserExtensions*/,519/*vs/editor/contrib/find/browser/findWidget*/,518/*vs/editor/contrib/find/browser/findOptionsWidget*/,176/*vs/editor/contrib/find/common/findController*/,14/*vs/platform/theme/common/themeService*/,76/*vs/platform/storage/common/storage*/]), function (require, exports, contextView_1, keybinding_1, contextkey_1, editorBrowserExtensions_1, findWidget_1, findOptionsWidget_1, findController_1, themeService_1, storage_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var FindController = (function (_super) {
        __extends(FindController, _super);
        function FindController(editor, contextViewService, contextKeyService, keybindingService, themeService, storageService) {
            var _this = _super.call(this, editor, contextKeyService, storageService) || this;
            _this._widget = _this._register(new findWidget_1.FindWidget(editor, _this, _this._state, contextViewService, keybindingService, contextKeyService, themeService));
            _this._findOptionsWidget = _this._register(new findOptionsWidget_1.FindOptionsWidget(editor, _this._state, keybindingService, themeService));
            return _this;
        }
        FindController.prototype._start = function (opts) {
            _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._state.isRevealed) {
                this._widget.highlightFindOptions();
            }
            else {
                this._findOptionsWidget.highlightFindOptions();
            }
        };
        FindController = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __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)
        ], FindController);
        return FindController;
    }(findController_1.CommonFindController));
    exports.FindController = FindController;
});

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









define(__m[521/*vs/editor/contrib/goToDeclaration/browser/messageController*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/async*/,3/*vs/base/common/lifecycle*/,51/*vs/base/browser/ui/aria/aria*/,2/*vs/editor/common/core/range*/,13/*vs/editor/common/editorCommonExtensions*/,25/*vs/editor/browser/editorBrowser*/,19/*vs/platform/contextkey/common/contextkey*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,335/*vs/css!vs/editor/contrib/goToDeclaration/browser/messageController*/]), function (require, exports, async_1, lifecycle_1, aria_1, range_1, editorCommonExtensions_1, editorBrowser_1, contextkey_1, themeService_1, colorRegistry_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MessageController = (function () {
        function MessageController(editor, contextKeyService) {
            this._messageListeners = [];
            this._editor = editor;
            this._visible = MessageController_1.CONTEXT_SNIPPET_MODE.bindTo(contextKeyService);
        }
        MessageController_1 = MessageController;
        MessageController.get = function (editor) {
            return editor.getContribution(MessageController_1._id);
        };
        MessageController.prototype.getId = function () {
            return MessageController_1._id;
        };
        MessageController.prototype.dispose = function () {
            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(async_1.setDisposableTimeout(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._id = 'editor.contrib.messageController';
        MessageController.CONTEXT_SNIPPET_MODE = new contextkey_1.RawContextKey('messageVisible', false);
        MessageController = MessageController_1 = __decorate([
            editorCommonExtensions_1.commonEditorContribution,
            __param(1, contextkey_1.IContextKeyService)
        ], MessageController);
        return MessageController;
        var MessageController_1;
    }());
    exports.MessageController = MessageController;
    var MessageCommand = editorCommonExtensions_1.EditorCommand.bindToContribution(MessageController.get);
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new MessageCommand({
        id: 'leaveEditorMessage',
        precondition: MessageController.CONTEXT_SNIPPET_MODE,
        handler: function (c) { return c.closeMessage(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(30),
            primary: 9 /* Escape */
        }
    }));
    var MessageWidget = (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);
            this._position = { lineNumber: lineNumber, column: 1 };
            this._domNode = document.createElement('div');
            this._domNode.style.paddingLeft = editor.getOffsetForColumn(lineNumber, column) - 6 + "px";
            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: [editorBrowser_1.ContentWidgetPositionPreference.ABOVE] };
        };
        return MessageWidget;
    }());
    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 + "; }");
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  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/contrib/gotoError/browser/gotoError*/], __M([1/*require*/,0/*exports*/,353/*vs/nls!vs/editor/contrib/gotoError/browser/gotoError*/,11/*vs/base/common/event*/,3/*vs/base/common/lifecycle*/,36/*vs/base/common/severity*/,4/*vs/base/browser/dom*/,19/*vs/platform/contextkey/common/contextkey*/,103/*vs/platform/markers/common/markers*/,58/*vs/platform/telemetry/common/telemetry*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,13/*vs/editor/common/editorCommonExtensions*/,30/*vs/editor/browser/editorBrowserExtensions*/,183/*vs/editor/contrib/zoneWidget/browser/zoneWidget*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,32/*vs/base/common/color*/,21/*vs/editor/common/editorContextKeys*/,37/*vs/editor/common/view/editorColorRegistry*/,366/*vs/css!vs/editor/contrib/gotoError/browser/gotoError*/]), function (require, exports, nls, event_1, lifecycle_1, severity_1, dom, contextkey_1, markers_1, telemetry_1, position_1, range_1, editorCommonExtensions_1, editorBrowserExtensions_1, zoneWidget_1, colorRegistry_1, themeService_1, color_1, editorContextKeys_1, editorColorRegistry_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var MarkerModel = (function () {
        function MarkerModel(editor, markers) {
            var _this = this;
            this._editor = editor;
            this._markers = null;
            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) {
                    _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) {
            // assign
            this._markers = markers || [];
            // sort markers
            this._markers.sort(function (left, right) { return severity_1.default.compare(left.severity, right.severity) || range_1.Range.compareRangesUsingStarts(left, right); });
            this._nextIdx = -1;
            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()) {
                    var word = this._editor.getModel().getWordAtPosition(range.getStartPosition());
                    if (word) {
                        range = new range_1.Range(range.startLineNumber, word.startColumn, range.startLineNumber, word.endColumn);
                    }
                }
                if (range.containsPosition(position) || position.isBeforeOrEqual(range.getStartPosition())) {
                    this._nextIdx = i + (fwd ? 0 : -1);
                    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;
            }
        };
        MarkerModel.prototype.move = function (fwd) {
            if (!this.canNavigate()) {
                this._onCurrentMarkerChanged.fire(undefined);
                return;
            }
            if (this._nextIdx === -1) {
                this._initIdx(fwd);
            }
            else if (fwd) {
                this._nextIdx += 1;
                if (this._nextIdx >= this._markers.length) {
                    this._nextIdx = 0;
                }
            }
            else {
                this._nextIdx -= 1;
                if (this._nextIdx < 0) {
                    this._nextIdx = this._markers.length - 1;
                }
            }
            var marker = this._markers[this._nextIdx];
            this._onCurrentMarkerChanged.fire(marker);
        };
        MarkerModel.prototype.canNavigate = function () {
            return this._markers.length > 0;
        };
        MarkerModel.prototype.next = function () {
            this.move(true);
        };
        MarkerModel.prototype.previous = function () {
            this.move(false);
        };
        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.reveal = function () {
            var _this = this;
            if (this._nextIdx === -1) {
                return;
            }
            this.withoutWatchingEditorPosition(function () {
                var pos = new position_1.Position(_this._markers[_this._nextIdx].startLineNumber, _this._markers[_this._nextIdx].startColumn);
                _this._editor.setPosition(pos);
                _this._editor.revealPositionInCenter(pos);
            });
        };
        MarkerModel.prototype.dispose = function () {
            this._toUnbind = lifecycle_1.dispose(this._toUnbind);
        };
        return MarkerModel;
    }());
    var MessageWidget = (function () {
        function MessageWidget(container) {
            this.lines = 0;
            this.domNode = document.createElement('div');
            this.domNode.className = 'block descriptioncontainer';
            this.domNode.setAttribute('aria-live', 'assertive');
            this.domNode.setAttribute('role', 'alert');
            container.appendChild(this.domNode);
        }
        MessageWidget.prototype.update = function (_a) {
            var _this = this;
            var source = _a.source, message = _a.message;
            this.lines = 1;
            if (source) {
                var indent_1 = new Array(source.length + 3 + 1).join(' ');
                message = "[" + source + "] " + message.replace(/\r\n|\r|\n/g, function () {
                    _this.lines += 1;
                    return '\n' + indent_1;
                });
            }
            this.domNode.innerText = message;
        };
        return MessageWidget;
    }());
    var MarkerNavigationWidget = (function (_super) {
        __extends(MarkerNavigationWidget, _super);
        function MarkerNavigationWidget(editor, _model, _themeService) {
            var _this = _super.call(this, editor, { showArrow: true, showFrame: true, isAccessible: true }) || this;
            _this._model = _model;
            _this._themeService = _themeService;
            _this._callOnDispose = [];
            _this._severity = severity_1.default.Warning;
            _this._backgroundColor = color_1.Color.white;
            _this._applyTheme(_themeService.getTheme());
            _this._callOnDispose.push(_themeService.onThemeChange(_this._applyTheme.bind(_this)));
            _this.create();
            _this._wireModelAndView();
            return _this;
        }
        MarkerNavigationWidget.prototype._applyTheme = function (theme) {
            this._backgroundColor = theme.getColor(exports.editorMarkerNavigationBackground);
            var frameColor = theme.getColor(this._severity === severity_1.default.Error ? exports.editorMarkerNavigationError : exports.editorMarkerNavigationWarning);
            this.style({
                arrowColor: frameColor,
                frameColor: frameColor
            }); // style() will trigger _applyStyles
        };
        MarkerNavigationWidget.prototype._applyStyles = function () {
            if (this._parentContainer) {
                this._parentContainer.style.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._fillContainer = function (container) {
            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._title = document.createElement('div');
            this._title.className = 'block title';
            this._container.appendChild(this._title);
            this._message = new MessageWidget(this._container);
            this.editor.applyFontInfo(this._message.domNode);
        };
        MarkerNavigationWidget.prototype.show = function (where, heightInLines) {
            _super.prototype.show.call(this, where, heightInLines);
            if (this.editor.getConfiguration().accessibilitySupport !== 1 /* Disabled */) {
                this.focus();
            }
        };
        MarkerNavigationWidget.prototype._wireModelAndView = function () {
            // listen to events
            this._model.onCurrentMarkerChanged(this.showAtMarker, this, this._callOnDispose);
            this._model.onMarkerSetChanged(this._onMarkersChanged, this, this._callOnDispose);
        };
        MarkerNavigationWidget.prototype.showAtMarker = function (marker) {
            var _this = this;
            if (!marker) {
                return;
            }
            // update:
            // * title
            // * message
            this._container.classList.remove('stale');
            this._title.innerHTML = nls.localize(0, null, this._model.indexOf(marker), this._model.total);
            this._message.update(marker);
            this._model.withoutWatchingEditorPosition(function () {
                // update frame color (only applied on 'show')
                _this._severity = marker.severity;
                _this._applyTheme(_this._themeService.getTheme());
                _this.show(new position_1.Position(marker.startLineNumber, marker.startColumn), _this.computeRequiredHeight());
            });
        };
        MarkerNavigationWidget.prototype._onMarkersChanged = function () {
            var marker = this._model.findMarkerAtPosition(this.position);
            if (marker) {
                this._container.classList.remove('stale');
                this._message.update(marker);
            }
            else {
                this._container.classList.add('stale');
            }
            this._relayout();
        };
        MarkerNavigationWidget.prototype._relayout = function () {
            _super.prototype._relayout.call(this, this.computeRequiredHeight());
        };
        MarkerNavigationWidget.prototype.computeRequiredHeight = function () {
            return 1 + this._message.lines;
        };
        return MarkerNavigationWidget;
    }(zoneWidget_1.ZoneWidget));
    var MarkerNavigationAction = (function (_super) {
        __extends(MarkerNavigationAction, _super);
        function MarkerNavigationAction(next, opts) {
            var _this = _super.call(this, opts) || this;
            _this._isNext = next;
            return _this;
        }
        MarkerNavigationAction.prototype.run = function (accessor, editor) {
            var telemetryService = accessor.get(telemetry_1.ITelemetryService);
            var controller = MarkerController.get(editor);
            if (!controller) {
                return;
            }
            var model = controller.getOrCreateModel();
            telemetryService.publicLog('zoneWidgetShown', __assign({ mode: 'go to error' }, editor.getTelemetryData()));
            if (model) {
                if (this._isNext) {
                    model.next();
                }
                else {
                    model.previous();
                }
                model.reveal();
            }
        };
        return MarkerNavigationAction;
    }(editorCommonExtensions_1.EditorAction));
    var MarkerController = (function () {
        function MarkerController(editor, _markerService, _contextKeyService, _themeService) {
            this._markerService = _markerService;
            this._contextKeyService = _contextKeyService;
            this._themeService = _themeService;
            this._callOnClose = [];
            this._editor = editor;
            this._markersNavigationVisible = CONTEXT_MARKERS_NAVIGATION_VISIBLE.bindTo(this._contextKeyService);
        }
        MarkerController_1 = MarkerController;
        MarkerController.get = function (editor) {
            return editor.getContribution(MarkerController_1.ID);
        };
        MarkerController.prototype.getId = function () {
            return MarkerController_1.ID;
        };
        MarkerController.prototype.dispose = function () {
            this._cleanUp();
        };
        MarkerController.prototype._cleanUp = function () {
            this._markersNavigationVisible.reset();
            this._callOnClose = lifecycle_1.dispose(this._callOnClose);
            this._zone = null;
            this._model = null;
        };
        MarkerController.prototype.getOrCreateModel = function () {
            var _this = this;
            if (this._model) {
                return this._model;
            }
            var markers = this._getMarkers();
            this._model = new MarkerModel(this._editor, markers);
            this._zone = new MarkerNavigationWidget(this._editor, this._model, this._themeService);
            this._markersNavigationVisible.set(true);
            this._callOnClose.push(this._model);
            this._callOnClose.push(this._zone);
            this._callOnClose.push(this._editor.onDidChangeModel(function () { return _this._cleanUp(); }));
            this._model.onCurrentMarkerChanged(function (marker) { return !marker && _this._cleanUp(); }, undefined, this._callOnClose);
            this._markerService.onMarkerChanged(this._onMarkerChanged, this, this._callOnClose);
            return this._model;
        };
        MarkerController.prototype.closeMarkersNavigation = function () {
            this._cleanUp();
            this._editor.focus();
        };
        MarkerController.prototype._onMarkerChanged = function (changedResources) {
            var _this = this;
            if (!changedResources.some(function (r) { return _this._editor.getModel().uri.toString() === r.toString(); })) {
                return;
            }
            this._model.setMarkers(this._getMarkers());
        };
        MarkerController.prototype._getMarkers = function () {
            return this._markerService.read({ resource: this._editor.getModel().uri });
        };
        MarkerController.ID = 'editor.contrib.markerController';
        MarkerController = MarkerController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, markers_1.IMarkerService),
            __param(2, contextkey_1.IContextKeyService),
            __param(3, themeService_1.IThemeService)
        ], MarkerController);
        return MarkerController;
        var MarkerController_1;
    }());
    var NextMarkerAction = (function (_super) {
        __extends(NextMarkerAction, _super);
        function NextMarkerAction() {
            return _super.call(this, true, {
                id: 'editor.action.marker.next',
                label: nls.localize(1, null),
                alias: 'Go to Next Error or Warning',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 66 /* F8 */
                }
            }) || this;
        }
        NextMarkerAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], NextMarkerAction);
        return NextMarkerAction;
    }(MarkerNavigationAction));
    var PrevMarkerAction = (function (_super) {
        __extends(PrevMarkerAction, _super);
        function PrevMarkerAction() {
            return _super.call(this, false, {
                id: 'editor.action.marker.prev',
                label: nls.localize(2, null),
                alias: 'Go to Previous Error or Warning',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 1024 /* Shift */ | 66 /* F8 */
                }
            }) || this;
        }
        PrevMarkerAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], PrevMarkerAction);
        return PrevMarkerAction;
    }(MarkerNavigationAction));
    var CONTEXT_MARKERS_NAVIGATION_VISIBLE = new contextkey_1.RawContextKey('markersNavigationVisible', false);
    var MarkerCommand = editorCommonExtensions_1.EditorCommand.bindToContribution(MarkerController.get);
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new MarkerCommand({
        id: 'closeMarkersNavigation',
        precondition: CONTEXT_MARKERS_NAVIGATION_VISIBLE,
        handler: function (x) { return x.closeMarkersNavigation(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(50),
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 9 /* Escape */,
            secondary: [1024 /* Shift */ | 9 /* Escape */]
        }
    }));
    // theming
    var errorDefault = colorRegistry_1.oneOf(editorColorRegistry_1.editorErrorForeground, editorColorRegistry_1.editorErrorBorder);
    var warningDefault = colorRegistry_1.oneOf(editorColorRegistry_1.editorWarningForeground, editorColorRegistry_1.editorWarningBorder);
    exports.editorMarkerNavigationError = colorRegistry_1.registerColor('editorMarkerNavigationError.background', { dark: errorDefault, light: errorDefault, hc: errorDefault }, nls.localize(3, null));
    exports.editorMarkerNavigationWarning = colorRegistry_1.registerColor('editorMarkerNavigationWarning.background', { dark: warningDefault, light: warningDefault, hc: warningDefault }, nls.localize(4, null));
    exports.editorMarkerNavigationBackground = colorRegistry_1.registerColor('editorMarkerNavigation.background', { dark: '#2D2D30', light: color_1.Color.white, hc: '#0C141F' }, nls.localize(5, 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[523/*vs/editor/contrib/hover/browser/hover*/], __M([1/*require*/,0/*exports*/,354/*vs/nls!vs/editor/contrib/hover/browser/hover*/,40/*vs/base/common/keyCodes*/,15/*vs/base/common/platform*/,71/*vs/platform/opener/common/opener*/,88/*vs/editor/common/services/modeService*/,2/*vs/editor/common/core/range*/,13/*vs/editor/common/editorCommonExtensions*/,25/*vs/editor/browser/editorBrowser*/,30/*vs/editor/browser/editorBrowserExtensions*/,463/*vs/editor/contrib/hover/browser/modesContentHover*/,425/*vs/editor/contrib/hover/browser/modesGlyphHover*/,3/*vs/base/common/lifecycle*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,21/*vs/editor/common/editorContextKeys*/,388/*vs/css!vs/editor/contrib/hover/browser/hover*/]), function (require, exports, nls, keyCodes_1, platform, opener_1, modeService_1, range_1, editorCommonExtensions_1, editorBrowser_1, editorBrowserExtensions_1, modesContentHover_1, modesGlyphHover_1, lifecycle_1, themeService_1, colorRegistry_1, editorContextKeys_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ModesHoverController = (function () {
        function ModesHoverController(editor, openerService, modeService) {
            var _this = this;
            this._editor = editor;
            this._toUnhook = [];
            this._isMouseDown = false;
            if (editor.getConfiguration().contribInfo.hover) {
                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.onMouseLeave(function (e) { return _this._hideWidgets(); }));
                this._toUnhook.push(this._editor.onKeyDown(function (e) { return _this._onKeyDown(e); }));
                this._toUnhook.push(this._editor.onDidChangeModel(function () { return _this._hideWidgets(); }));
                this._toUnhook.push(this._editor.onDidChangeModelDecorations(function () { return _this._onModelDecorationsChanged(); }));
                this._toUnhook.push(this._editor.onDidScrollChange(function (e) {
                    if (e.scrollTopChanged || e.scrollLeftChanged) {
                        _this._hideWidgets();
                    }
                }));
                this._contentWidget = new modesContentHover_1.ModesContentHoverWidget(editor, openerService, modeService);
                this._glyphWidget = new modesGlyphHover_1.ModesGlyphHoverWidget(editor, openerService, modeService);
            }
        }
        ModesHoverController_1 = ModesHoverController;
        ModesHoverController.get = function (editor) {
            return editor.getContribution(ModesHoverController_1.ID);
        };
        ModesHoverController.prototype._onModelDecorationsChanged = function () {
            this._contentWidget.onModelDecorationsChanged();
            this._glyphWidget.onModelDecorationsChanged();
        };
        ModesHoverController.prototype._onEditorMouseDown = function (mouseEvent) {
            this._isMouseDown = true;
            var targetType = mouseEvent.target.type;
            if (targetType === editorBrowser_1.MouseTargetType.CONTENT_WIDGET && mouseEvent.target.detail === modesContentHover_1.ModesContentHoverWidget.ID) {
                this._hoverClicked = true;
                // mouse down on top of content hover widget
                return;
            }
            if (targetType === editorBrowser_1.MouseTargetType.OVERLAY_WIDGET && mouseEvent.target.detail === modesGlyphHover_1.ModesGlyphHoverWidget.ID) {
                // mouse down on top of overlay hover widget
                return;
            }
            if (targetType !== editorBrowser_1.MouseTargetType.OVERLAY_WIDGET && mouseEvent.target.detail !== modesGlyphHover_1.ModesGlyphHoverWidget.ID) {
                this._hoverClicked = false;
            }
            this._hideWidgets();
        };
        ModesHoverController.prototype._onEditorMouseUp = function (mouseEvent) {
            this._isMouseDown = false;
        };
        ModesHoverController.prototype._onEditorMouseMove = function (mouseEvent) {
            var targetType = mouseEvent.target.type;
            var stopKey = platform.isMacintosh ? 'metaKey' : 'ctrlKey';
            if (this._isMouseDown && this._hoverClicked && this._contentWidget.isColorPickerVisible()) {
                return;
            }
            if (targetType === editorBrowser_1.MouseTargetType.CONTENT_WIDGET && mouseEvent.target.detail === modesContentHover_1.ModesContentHoverWidget.ID && !mouseEvent.event[stopKey]) {
                // mouse moved on top of content hover widget
                return;
            }
            if (targetType === editorBrowser_1.MouseTargetType.OVERLAY_WIDGET && mouseEvent.target.detail === modesGlyphHover_1.ModesGlyphHoverWidget.ID && !mouseEvent.event[stopKey]) {
                // mouse moved on top of overlay hover widget
                return;
            }
            if (this._editor.getConfiguration().contribInfo.hover && targetType === editorBrowser_1.MouseTargetType.CONTENT_TEXT) {
                this._glyphWidget.hide();
                this._contentWidget.startShowingAt(mouseEvent.target.range, false);
            }
            else if (targetType === editorBrowser_1.MouseTargetType.GUTTER_GLYPH_MARGIN) {
                this._contentWidget.hide();
                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 */) {
                // Do not hide hover when Ctrl/Meta is pressed
                this._hideWidgets();
            }
        };
        ModesHoverController.prototype._hideWidgets = function () {
            if (this._isMouseDown && this._hoverClicked && this._contentWidget.isColorPickerVisible()) {
                return;
            }
            this._glyphWidget.hide();
            this._contentWidget.hide();
        };
        ModesHoverController.prototype.showContentHover = function (range, focus) {
            this._contentWidget.startShowingAt(range, focus);
        };
        ModesHoverController.prototype.getId = function () {
            return ModesHoverController_1.ID;
        };
        ModesHoverController.prototype.dispose = function () {
            this._toUnhook = lifecycle_1.dispose(this._toUnhook);
            if (this._glyphWidget) {
                this._glyphWidget.dispose();
                this._glyphWidget = null;
            }
            if (this._contentWidget) {
                this._contentWidget.dispose();
                this._contentWidget = null;
            }
        };
        ModesHoverController.ID = 'editor.contrib.hover';
        ModesHoverController = ModesHoverController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, opener_1.IOpenerService),
            __param(2, modeService_1.IModeService)
        ], ModesHoverController);
        return ModesHoverController;
        var ModesHoverController_1;
    }());
    exports.ModesHoverController = ModesHoverController;
    var ShowHoverAction = (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.textFocus,
                    primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, 2048 /* CtrlCmd */ | 39 /* KEY_I */)
                }
            }) || this;
        }
        ShowHoverAction.prototype.run = function (accessor, editor) {
            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);
            controller.showContentHover(range, true);
        };
        ShowHoverAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], ShowHoverAction);
        return ShowHoverAction;
    }(editorCommonExtensions_1.EditorAction));
    // 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) + "; }");
        }
        var link = theme.getColor(colorRegistry_1.textLinkForeground);
        if (link) {
            collector.addRule(".monaco-editor .monaco-editor-hover a { color: " + link + "; }");
        }
        var codeBackground = theme.getColor(colorRegistry_1.textCodeBlockBackground);
        if (codeBackground) {
            collector.addRule(".monaco-editor .monaco-editor-hover code { background-color: " + codeBackground + "; }");
        }
    });
});




















define(__m[524/*vs/editor/contrib/inPlaceReplace/common/inPlaceReplace*/], __M([1/*require*/,0/*exports*/,356/*vs/nls!vs/editor/contrib/inPlaceReplace/common/inPlaceReplace*/,7/*vs/base/common/winjs.base*/,2/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,21/*vs/editor/common/editorContextKeys*/,13/*vs/editor/common/editorCommonExtensions*/,61/*vs/editor/common/services/editorWorkerService*/,262/*vs/editor/contrib/inPlaceReplace/common/inPlaceReplaceCommand*/,131/*vs/editor/common/core/editorState*/,14/*vs/platform/theme/common/themeService*/,37/*vs/editor/common/view/editorColorRegistry*/,34/*vs/editor/common/model/textModelWithDecorations*/]), function (require, exports, nls, winjs_base_1, range_1, selection_1, editorContextKeys_1, editorCommonExtensions_1, editorWorkerService_1, inPlaceReplaceCommand_1, editorState_1, themeService_1, editorColorRegistry_1, textModelWithDecorations_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var InPlaceReplaceController = (function () {
        function InPlaceReplaceController(editor, editorWorkerService) {
            this.editor = editor;
            this.editorWorkerService = editorWorkerService;
            this.requestIdPool = 0;
            this.currentRequest = winjs_base_1.TPromise.as(null);
            this.decorationRemover = winjs_base_1.TPromise.as(null);
            this.decorationIds = [];
        }
        InPlaceReplaceController_1 = InPlaceReplaceController;
        InPlaceReplaceController.get = function (editor) {
            return editor.getContribution(InPlaceReplaceController_1.ID);
        };
        InPlaceReplaceController.prototype.dispose = function () {
        };
        InPlaceReplaceController.prototype.getId = function () {
            return InPlaceReplaceController_1.ID;
        };
        InPlaceReplaceController.prototype.run = function (source, up) {
            var _this = this;
            // cancel any pending request
            this.currentRequest.cancel();
            var selection = this.editor.getSelection(), model = this.editor.getModel(), modelURI = model.uri;
            if (selection.startLineNumber !== selection.endLineNumber) {
                // Can't accept multiline selection
                return null;
            }
            var state = new editorState_1.EditorState(this.editor, 1 /* Value */ | 4 /* Position */);
            if (!this.editorWorkerService.canNavigateValueSet(modelURI)) {
                this.currentRequest = winjs_base_1.TPromise.as(null);
            }
            else {
                this.currentRequest = this.editorWorkerService.navigateValueSet(modelURI, selection, up);
                this.currentRequest = this.currentRequest.then(function (basicResult) {
                    if (basicResult && basicResult.range && basicResult.value) {
                        return basicResult;
                    }
                    return null;
                });
            }
            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), highlightRange = result.range, 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_1.DECORATION
                    }]);
                // remove decoration after delay
                _this.decorationRemover.cancel();
                _this.decorationRemover = winjs_base_1.TPromise.timeout(350);
                _this.decorationRemover.then(function () {
                    _this.editor.changeDecorations(function (accessor) {
                        _this.decorationIds = accessor.deltaDecorations(_this.decorationIds, []);
                    });
                });
            });
        };
        InPlaceReplaceController.ID = 'editor.contrib.inPlaceReplaceController';
        InPlaceReplaceController.DECORATION = textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'valueSetReplacement'
        });
        InPlaceReplaceController = InPlaceReplaceController_1 = __decorate([
            editorCommonExtensions_1.commonEditorContribution,
            __param(1, editorWorkerService_1.IEditorWorkerService)
        ], InPlaceReplaceController);
        return InPlaceReplaceController;
        var InPlaceReplaceController_1;
    }());
    var InPlaceReplaceUp = (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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 82 /* US_COMMA */
                }
            }) || this;
        }
        InPlaceReplaceUp.prototype.run = function (accessor, editor) {
            var controller = InPlaceReplaceController.get(editor);
            if (!controller) {
                return undefined;
            }
            return controller.run(this.id, true);
        };
        InPlaceReplaceUp = __decorate([
            editorCommonExtensions_1.editorAction
        ], InPlaceReplaceUp);
        return InPlaceReplaceUp;
    }(editorCommonExtensions_1.EditorAction));
    var InPlaceReplaceDown = (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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 84 /* US_DOT */
                }
            }) || this;
        }
        InPlaceReplaceDown.prototype.run = function (accessor, editor) {
            var controller = InPlaceReplaceController.get(editor);
            if (!controller) {
                return undefined;
            }
            return controller.run(this.id, false);
        };
        InPlaceReplaceDown = __decorate([
            editorCommonExtensions_1.editorAction
        ], InPlaceReplaceDown);
        return InPlaceReplaceDown;
    }(editorCommonExtensions_1.EditorAction));
    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[525/*vs/editor/contrib/links/browser/links*/], __M([1/*require*/,0/*exports*/,358/*vs/nls!vs/editor/contrib/links/browser/links*/,10/*vs/base/common/errors*/,15/*vs/base/common/platform*/,36/*vs/base/common/severity*/,7/*vs/base/common/winjs.base*/,50/*vs/platform/message/common/message*/,71/*vs/platform/opener/common/opener*/,20/*vs/editor/common/editorCommon*/,13/*vs/editor/common/editorCommonExtensions*/,17/*vs/editor/common/modes*/,61/*vs/editor/common/services/editorWorkerService*/,25/*vs/editor/browser/editorBrowser*/,401/*vs/editor/contrib/links/common/links*/,3/*vs/base/common/lifecycle*/,30/*vs/editor/browser/editorBrowserExtensions*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,34/*vs/editor/common/model/textModelWithDecorations*/,192/*vs/editor/contrib/goToDeclaration/browser/clickLinkGesture*/,389/*vs/css!vs/editor/contrib/links/browser/links*/]), function (require, exports, nls, errors_1, platform, severity_1, winjs_base_1, message_1, opener_1, editorCommon, editorCommonExtensions_1, modes_1, editorWorkerService_1, editorBrowser_1, links_1, lifecycle_1, editorBrowserExtensions_1, themeService_1, colorRegistry_1, textModelWithDecorations_1, clickLinkGesture_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var HOVER_MESSAGE_GENERAL_META = (platform.isMacintosh
        ? nls.localize(0, null)
        : nls.localize(1, null));
    var HOVER_MESSAGE_COMMAND_META = (platform.isMacintosh
        ? nls.localize(2, null)
        : nls.localize(3, null));
    var HOVER_MESSAGE_GENERAL_ALT = nls.localize(4, null);
    var HOVER_MESSAGE_COMMAND_ALT = nls.localize(5, null);
    var decoration = {
        meta: textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            inlineClassName: 'detected-link',
            hoverMessage: HOVER_MESSAGE_GENERAL_META
        }),
        metaActive: textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            inlineClassName: 'detected-link-active',
            hoverMessage: HOVER_MESSAGE_GENERAL_META
        }),
        alt: textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            inlineClassName: 'detected-link',
            hoverMessage: HOVER_MESSAGE_GENERAL_ALT
        }),
        altActive: textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            inlineClassName: 'detected-link-active',
            hoverMessage: HOVER_MESSAGE_GENERAL_ALT
        }),
        altCommand: textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            inlineClassName: 'detected-link',
            hoverMessage: HOVER_MESSAGE_COMMAND_ALT
        }),
        altCommandActive: textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            inlineClassName: 'detected-link-active',
            hoverMessage: HOVER_MESSAGE_COMMAND_ALT
        }),
        metaCommand: textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            inlineClassName: 'detected-link',
            hoverMessage: HOVER_MESSAGE_COMMAND_META
        }),
        metaCommandActive: textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            inlineClassName: 'detected-link-active',
            hoverMessage: HOVER_MESSAGE_COMMAND_META
        }),
    };
    var LinkOccurrence = (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 (/^command:/i.test(link.url)) {
                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 = (function () {
        function LinkDetector(editor, openerService, messageService, editorWorkerService) {
            var _this = this;
            this.editor = editor;
            this.openerService = openerService;
            this.messageService = messageService;
            this.editorWorkerService = editorWorkerService;
            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.timeoutPromise = null;
            this.computePromise = null;
            this.currentOccurrences = {};
            this.activeLinkDecorationId = null;
            this.beginCompute();
        }
        LinkDetector_1 = LinkDetector;
        LinkDetector.get = function (editor) {
            return editor.getContribution(LinkDetector_1.ID);
        };
        LinkDetector.prototype.getId = function () {
            return LinkDetector_1.ID;
        };
        LinkDetector.prototype.isComputing = function () {
            return winjs_base_1.TPromise.is(this.computePromise);
        };
        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;
            if (!this.timeoutPromise) {
                this.timeoutPromise = winjs_base_1.TPromise.timeout(LinkDetector_1.RECOMPUTE_TIME);
                this.timeoutPromise.then(function () {
                    _this.timeoutPromise = null;
                    _this.beginCompute();
                });
            }
        };
        LinkDetector.prototype.beginCompute = function () {
            var _this = this;
            if (!this.editor.getModel() || !this.enabled) {
                return;
            }
            if (!modes_1.LinkProviderRegistry.has(this.editor.getModel())) {
                return;
            }
            this.computePromise = links_1.getLinks(this.editor.getModel()).then(function (links) {
                _this.updateDecorations(links);
                _this.computePromise = null;
            });
        };
        LinkDetector.prototype.updateDecorations = function (links) {
            var _this = this;
            var useMetaKey = (this.editor.getConfiguration().multiCursorModifier === 'altKey');
            this.editor.changeDecorations(function (changeAccessor) {
                var oldDecorations = [];
                var keys = Object.keys(_this.currentOccurrences);
                for (var i_1 = 0, len = keys.length; i_1 < len; i_1++) {
                    var decorationId = keys[i_1];
                    var occurance_1 = _this.currentOccurrences[decorationId];
                    oldDecorations.push(occurance_1.decorationId);
                }
                var newDecorations = [];
                if (links) {
                    // Not sure why this is sometimes null
                    for (var i = 0; i < links.length; i++) {
                        newDecorations.push(LinkOccurrence.decoration(links[i], useMetaKey));
                    }
                }
                var decorations = changeAccessor.deltaDecorations(oldDecorations, newDecorations);
                _this.currentOccurrences = {};
                _this.activeLinkDecorationId = null;
                for (var i_2 = 0, len = decorations.length; i_2 < len; i_2++) {
                    var occurance = new LinkOccurrence(links[i_2], decorations[i_2]);
                    _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 = this.getLinkOccurrence(mouseEvent.target.position);
                if (occurrence) {
                    this.editor.changeDecorations(function (changeAccessor) {
                        occurrence.activate(changeAccessor, useMetaKey);
                        _this.activeLinkDecorationId = occurrence.decorationId;
                    });
                }
            }
            else {
                this.cleanUpActiveLinkDecoration();
            }
        };
        LinkDetector.prototype.cleanUpActiveLinkDecoration = function () {
            var useMetaKey = (this.editor.getConfiguration().multiCursorModifier === 'altKey');
            if (this.activeLinkDecorationId) {
                var occurrence = this.currentOccurrences[this.activeLinkDecorationId];
                if (occurrence) {
                    this.editor.changeDecorations(function (changeAccessor) {
                        occurrence.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().then(function (uri) {
                // open the uri
                return _this.openerService.open(uri, { openToSide: openToSide });
            }, function (err) {
                // different error cases
                if (err === 'invalid') {
                    _this.messageService.show(severity_1.default.Warning, nls.localize(6, null, link.url));
                }
                else if (err === 'missing') {
                    _this.messageService.show(severity_1.default.Warning, nls.localize(7, null));
                }
                else {
                    errors_1.onUnexpectedError(err);
                }
            }).done(null, errors_1.onUnexpectedError);
        };
        LinkDetector.prototype.getLinkOccurrence = function (position) {
            var decorations = this.editor.getModel().getDecorationsInRange({
                startLineNumber: position.lineNumber,
                startColumn: position.column,
                endLineNumber: position.lineNumber,
                endColumn: position.column
            }, 0, true);
            for (var i = 0; i < decorations.length; i++) {
                var decoration = decorations[i];
                var currentOccurrence = this.currentOccurrences[decoration.id];
                if (currentOccurrence) {
                    return currentOccurrence;
                }
            }
            return null;
        };
        LinkDetector.prototype.isEnabled = function (mouseEvent, withKey) {
            return (mouseEvent.target.type === editorBrowser_1.MouseTargetType.CONTENT_TEXT
                && (mouseEvent.hasTriggerModifier || (withKey && withKey.keyCodeIsTriggerKey)));
        };
        LinkDetector.prototype.stop = function () {
            if (this.timeoutPromise) {
                this.timeoutPromise.cancel();
                this.timeoutPromise = null;
            }
            if (this.computePromise) {
                this.computePromise.cancel();
                this.computePromise = null;
            }
        };
        LinkDetector.prototype.dispose = function () {
            this.listenersToRemove = lifecycle_1.dispose(this.listenersToRemove);
            this.stop();
        };
        LinkDetector.ID = 'editor.linkDetector';
        LinkDetector.RECOMPUTE_TIME = 1000; // ms
        LinkDetector = LinkDetector_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, opener_1.IOpenerService),
            __param(2, message_1.IMessageService),
            __param(3, editorWorkerService_1.IEditorWorkerService)
        ], LinkDetector);
        return LinkDetector;
        var LinkDetector_1;
    }());
    var OpenLinkAction = (function (_super) {
        __extends(OpenLinkAction, _super);
        function OpenLinkAction() {
            return _super.call(this, {
                id: 'editor.action.openLink',
                label: nls.localize(8, null),
                alias: 'Open Link',
                precondition: null
            }) || this;
        }
        OpenLinkAction.prototype.run = function (accessor, editor) {
            var linkDetector = LinkDetector.get(editor);
            if (!linkDetector) {
                return;
            }
            var link = linkDetector.getLinkOccurrence(editor.getPosition());
            if (link) {
                linkDetector.openLinkOccurrence(link, false);
            }
        };
        OpenLinkAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], OpenLinkAction);
        return OpenLinkAction;
    }(editorCommonExtensions_1.EditorAction));
    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[526/*vs/editor/contrib/parameterHints/browser/parameterHintsWidget*/], __M([1/*require*/,0/*exports*/,361/*vs/nls!vs/editor/contrib/parameterHints/browser/parameterHintsWidget*/,3/*vs/base/common/lifecycle*/,7/*vs/base/common/winjs.base*/,4/*vs/base/browser/dom*/,51/*vs/base/browser/ui/aria/aria*/,17/*vs/editor/common/modes*/,25/*vs/editor/browser/editorBrowser*/,18/*vs/base/common/async*/,10/*vs/base/common/errors*/,11/*vs/base/common/event*/,124/*vs/base/browser/event*/,19/*vs/platform/contextkey/common/contextkey*/,178/*vs/editor/contrib/parameterHints/common/parameterHints*/,63/*vs/base/browser/ui/scrollbar/scrollableElement*/,89/*vs/editor/common/core/characterClassifier*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,390/*vs/css!vs/editor/contrib/parameterHints/browser/parameterHints*/]), function (require, exports, nls, lifecycle_1, winjs_base_1, dom, aria, modes_1, editorBrowser_1, async_1, errors_1, event_1, event_2, contextkey_1, parameterHints_1, scrollableElement_1, characterClassifier_1, themeService_1, colorRegistry_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var $ = dom.$;
    var ParameterHintsModel = (function (_super) {
        __extends(ParameterHintsModel, _super);
        function ParameterHintsModel(editor) {
            var _this = _super.call(this) || this;
            _this._onHint = _this._register(new event_1.Emitter());
            _this.onHint = _this._onHint.event;
            _this._onCancel = _this._register(new event_1.Emitter());
            _this.onCancel = _this._onCancel.event;
            _this.editor = editor;
            _this.enabled = false;
            _this.triggerCharactersListeners = [];
            _this.throttledDelayer = new async_1.RunOnceScheduler(function () { return _this.doTrigger(); }, ParameterHintsModel.DELAY);
            _this.active = false;
            _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(modes_1.SignatureHelpProviderRegistry.onDidChange(_this.onModelChanged, _this));
            _this.onEditorConfigurationChange();
            _this.onModelChanged();
            return _this;
        }
        ParameterHintsModel.prototype.cancel = function (silent) {
            if (silent === void 0) { silent = false; }
            this.active = false;
            this.throttledDelayer.cancel();
            if (!silent) {
                this._onCancel.fire(void 0);
            }
        };
        ParameterHintsModel.prototype.trigger = function (delay) {
            if (delay === void 0) { delay = ParameterHintsModel.DELAY; }
            if (!modes_1.SignatureHelpProviderRegistry.has(this.editor.getModel())) {
                return;
            }
            this.cancel(true);
            return this.throttledDelayer.schedule(delay);
        };
        ParameterHintsModel.prototype.doTrigger = function () {
            var _this = this;
            parameterHints_1.provideSignatureHelp(this.editor.getModel(), this.editor.getPosition())
                .then(null, errors_1.onUnexpectedError)
                .then(function (result) {
                if (!result || !result.signatures || result.signatures.length === 0) {
                    _this.cancel();
                    _this._onCancel.fire(void 0);
                    return false;
                }
                _this.active = true;
                var event = { hints: result };
                _this._onHint.fire(event);
                return true;
            });
        };
        ParameterHintsModel.prototype.isTriggered = function () {
            return this.active || this.throttledDelayer.isScheduled();
        };
        ParameterHintsModel.prototype.onModelChanged = function () {
            var _this = this;
            if (this.active) {
                this.cancel();
            }
            this.triggerCharactersListeners = lifecycle_1.dispose(this.triggerCharactersListeners);
            var model = this.editor.getModel();
            if (!model) {
                return;
            }
            var triggerChars = new characterClassifier_1.CharacterSet();
            for (var _i = 0, _a = modes_1.SignatureHelpProviderRegistry.ordered(model); _i < _a.length; _i++) {
                var support = _a[_i];
                if (Array.isArray(support.signatureHelpTriggerCharacters)) {
                    for (var _b = 0, _c = support.signatureHelpTriggerCharacters; _b < _c.length; _b++) {
                        var ch = _c[_b];
                        triggerChars.add(ch.charCodeAt(0));
                    }
                }
            }
            this.triggerCharactersListeners.push(this.editor.onDidType(function (text) {
                if (!_this.enabled) {
                    return;
                }
                if (triggerChars.has(text.charCodeAt(text.length - 1))) {
                    _this.trigger();
                }
            }));
        };
        ParameterHintsModel.prototype.onCursorChange = function (e) {
            if (e.source === 'mouse') {
                this.cancel();
            }
            else if (this.isTriggered()) {
                this.trigger();
            }
        };
        ParameterHintsModel.prototype.onEditorConfigurationChange = function () {
            this.enabled = this.editor.getConfiguration().contribInfo.parameterHints;
            if (!this.enabled) {
                this.cancel();
            }
        };
        ParameterHintsModel.prototype.dispose = function () {
            this.cancel(true);
            this.triggerCharactersListeners = lifecycle_1.dispose(this.triggerCharactersListeners);
            _super.prototype.dispose.call(this);
        };
        ParameterHintsModel.DELAY = 120; // ms
        return ParameterHintsModel;
    }(lifecycle_1.Disposable));
    exports.ParameterHintsModel = ParameterHintsModel;
    var ParameterHintsWidget = (function () {
        function ParameterHintsWidget(editor, contextKeyService) {
            var _this = this;
            this.editor = editor;
            // Editor.IContentWidget.allowEditorOverflow
            this.allowEditorOverflow = true;
            this.model = new ParameterHintsModel(editor);
            this.keyVisible = parameterHints_1.Context.Visible.bindTo(contextKeyService);
            this.keyMultipleSignatures = parameterHints_1.Context.MultipleSignatures.bindTo(contextKeyService);
            this.visible = false;
            this.disposables = [];
            this.disposables.push(this.model.onHint(function (e) {
                _this.show();
                _this.hints = e.hints;
                _this.currentSignature = e.hints.activeSignature;
                _this.render();
            }));
            this.disposables.push(this.model.onCancel(function () {
                _this.hide();
            }));
            this.element = $('.editor-widget.parameter-hints-widget');
            var wrapper = dom.append(this.element, $('.wrapper'));
            var onClick = event_2.stop(event_2.domEvent(this.element, 'click'));
            onClick(this.next, this, this.disposables);
            var buttons = dom.append(wrapper, $('.buttons'));
            var previous = dom.append(buttons, $('.button.previous'));
            var next = dom.append(buttons, $('.button.next'));
            var onPreviousClick = event_2.stop(event_2.domEvent(previous, 'click'));
            onPreviousClick(this.previous, this, this.disposables);
            var onNextClick = event_2.stop(event_2.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.currentSignature = 0;
            this.editor.addContentWidget(this);
            this.hide();
            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_1.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;
            }
            this.keyVisible.set(true);
            this.visible = true;
            winjs_base_1.TPromise.timeout(100).done(function () { return dom.addClass(_this.element, 'visible'); });
            this.editor.layoutContentWidget(this);
        };
        ParameterHintsWidget.prototype.hide = function () {
            if (!this.model || !this.visible) {
                return;
            }
            this.keyVisible.reset();
            this.visible = false;
            this.hints = null;
            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: [editorBrowser_1.ContentWidgetPositionPreference.ABOVE, editorBrowser_1.ContentWidgetPositionPreference.BELOW]
                };
            }
            return null;
        };
        ParameterHintsWidget.prototype.render = function () {
            var multiple = this.hints.signatures.length > 1;
            dom.toggleClass(this.element, 'multiple', multiple);
            this.keyMultipleSignatures.set(multiple);
            this.signature.innerHTML = '';
            this.docs.innerHTML = '';
            var signature = this.hints.signatures[this.currentSignature];
            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, this.hints.activeParameter);
            }
            var activeParameter = signature.parameters[this.hints.activeParameter];
            if (activeParameter && activeParameter.documentation) {
                var documentation = $('span.documentation');
                documentation.textContent = activeParameter.documentation;
                dom.append(this.docs, $('p', null, documentation));
            }
            dom.toggleClass(this.signature, 'has-docs', !!signature.documentation);
            if (signature.documentation) {
                dom.append(this.docs, $('p', null, signature.documentation));
            }
            var currentOverload = String(this.currentSignature + 1);
            if (this.hints.signatures.length < 10) {
                currentOverload += "/" + this.hints.signatures.length;
            }
            this.overloads.textContent = currentOverload;
            if (activeParameter) {
                var labelToAnnounce = activeParameter.label;
                // 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 end = signature.label.length;
            var idx = 0;
            var element;
            for (var i = signature.parameters.length - 1; i >= 0; i--) {
                var parameter = signature.parameters[i];
                idx = signature.label.lastIndexOf(parameter.label, end - 1);
                var signatureLabelOffset = 0;
                var signatureLabelEnd = 0;
                if (idx >= 0) {
                    signatureLabelOffset = idx;
                    signatureLabelEnd = idx + parameter.label.length;
                }
                // non parameter part
                element = document.createElement('span');
                element.textContent = signature.label.substring(signatureLabelEnd, end);
                dom.prepend(parent, element);
                // parameter part
                element = document.createElement('span');
                element.className = "parameter " + (i === currentParameter ? 'active' : '');
                element.textContent = signature.label.substring(signatureLabelOffset, signatureLabelEnd);
                dom.prepend(parent, element);
                end = signatureLabelOffset;
            }
            // non parameter part
            element = document.createElement('span');
            element.textContent = signature.label.substring(0, end);
            dom.prepend(parent, element);
        };
        // private select(position: number): void {
        // 	const signature = this.signatureViews[position];
        // 	if (!signature) {
        // 		return;
        // 	}
        // 	this.signatures.style.height = `${ signature.height }px`;
        // 	this.signatures.scrollTop = signature.top;
        // 	let overloads = '' + (position + 1);
        // 	if (this.signatureViews.length < 10) {
        // 		overloads += '/' + this.signatureViews.length;
        // 	}
        // 	this.overloads.textContent = overloads;
        // 	if (this.hints && this.hints.signatures[position].parameters[this.hints.activeParameter]) {
        // 		const labelToAnnounce = this.hints.signatures[position].parameters[this.hints.activeParameter].label;
        // 		// 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('hint', "{0}, hint", labelToAnnounce));
        // 			this.announcedLabel = labelToAnnounce;
        // 		}
        // 	}
        // 	this.editor.layoutContentWidget(this);
        // }
        ParameterHintsWidget.prototype.next = function () {
            var length = this.hints.signatures.length;
            if (length < 2) {
                this.cancel();
                return false;
            }
            this.currentSignature = (this.currentSignature + 1) % length;
            this.render();
            return true;
        };
        ParameterHintsWidget.prototype.previous = function () {
            var length = this.hints.signatures.length;
            if (length < 2) {
                this.cancel();
                return false;
            }
            this.currentSignature = (this.currentSignature - 1 + length) % length;
            this.render();
            return true;
        };
        ParameterHintsWidget.prototype.cancel = function () {
            this.model.cancel();
        };
        ParameterHintsWidget.prototype.getDomNode = function () {
            return this.element;
        };
        ParameterHintsWidget.prototype.getId = function () {
            return ParameterHintsWidget.ID;
        };
        ParameterHintsWidget.prototype.trigger = function () {
            this.model.trigger(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.model = null;
        };
        ParameterHintsWidget.ID = 'editor.widget.parameterHintsWidget';
        ParameterHintsWidget = __decorate([
            __param(1, contextkey_1.IContextKeyService)
        ], 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 + "; }");
        }
    });
});




















define(__m[527/*vs/editor/contrib/parameterHints/browser/parameterHints*/], __M([1/*require*/,0/*exports*/,360/*vs/nls!vs/editor/contrib/parameterHints/browser/parameterHints*/,3/*vs/base/common/lifecycle*/,16/*vs/platform/instantiation/common/instantiation*/,21/*vs/editor/common/editorContextKeys*/,19/*vs/platform/contextkey/common/contextkey*/,13/*vs/editor/common/editorCommonExtensions*/,30/*vs/editor/browser/editorBrowserExtensions*/,526/*vs/editor/contrib/parameterHints/browser/parameterHintsWidget*/,178/*vs/editor/contrib/parameterHints/common/parameterHints*/]), function (require, exports, nls, lifecycle_1, instantiation_1, editorContextKeys_1, contextkey_1, editorCommonExtensions_1, editorBrowserExtensions_1, parameterHintsWidget_1, parameterHints_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var ParameterHintsController = (function () {
        function ParameterHintsController(editor, instantiationService) {
            this.editor = editor;
            this.widget = instantiationService.createInstance(parameterHintsWidget_1.ParameterHintsWidget, this.editor);
        }
        ParameterHintsController_1 = ParameterHintsController;
        ParameterHintsController.get = function (editor) {
            return editor.getContribution(ParameterHintsController_1.ID);
        };
        ParameterHintsController.prototype.getId = function () {
            return ParameterHintsController_1.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 () {
            this.widget.trigger();
        };
        ParameterHintsController.prototype.dispose = function () {
            this.widget = lifecycle_1.dispose(this.widget);
        };
        ParameterHintsController.ID = 'editor.controller.parameterHints';
        ParameterHintsController = ParameterHintsController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, instantiation_1.IInstantiationService)
        ], ParameterHintsController);
        return ParameterHintsController;
        var ParameterHintsController_1;
    }());
    var TriggerParameterHintsAction = (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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 10 /* Space */
                }
            }) || this;
        }
        TriggerParameterHintsAction.prototype.run = function (accessor, editor) {
            var controller = ParameterHintsController.get(editor);
            if (controller) {
                controller.trigger();
            }
        };
        TriggerParameterHintsAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], TriggerParameterHintsAction);
        return TriggerParameterHintsAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.TriggerParameterHintsAction = TriggerParameterHintsAction;
    var weight = editorCommonExtensions_1.CommonEditorRegistry.commandWeight(75);
    var ParameterHintsCommand = editorCommonExtensions_1.EditorCommand.bindToContribution(ParameterHintsController.get);
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new ParameterHintsCommand({
        id: 'closeParameterHints',
        precondition: parameterHints_1.Context.Visible,
        handler: function (x) { return x.cancel(); },
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
            primary: 9 /* Escape */,
            secondary: [1024 /* Shift */ | 9 /* Escape */]
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new ParameterHintsCommand({
        id: 'showPrevParameterHint',
        precondition: contextkey_1.ContextKeyExpr.and(parameterHints_1.Context.Visible, parameterHints_1.Context.MultipleSignatures),
        handler: function (x) { return x.previous(); },
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
            primary: 16 /* UpArrow */,
            secondary: [512 /* Alt */ | 16 /* UpArrow */],
            mac: { primary: 16 /* UpArrow */, secondary: [512 /* Alt */ | 16 /* UpArrow */, 256 /* WinCtrl */ | 46 /* KEY_P */] }
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new ParameterHintsCommand({
        id: 'showNextParameterHint',
        precondition: contextkey_1.ContextKeyExpr.and(parameterHints_1.Context.Visible, parameterHints_1.Context.MultipleSignatures),
        handler: function (x) { return x.next(); },
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
            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[528/*vs/editor/contrib/rename/browser/renameInputField*/], __M([1/*require*/,0/*exports*/,369/*vs/nls!vs/editor/contrib/rename/browser/renameInputField*/,10/*vs/base/common/errors*/,3/*vs/base/common/lifecycle*/,7/*vs/base/common/winjs.base*/,2/*vs/editor/common/core/range*/,25/*vs/editor/browser/editorBrowser*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,12/*vs/editor/common/core/position*/,393/*vs/css!vs/editor/contrib/rename/browser/renameInputField*/]), function (require, exports, nls_1, errors_1, lifecycle_1, winjs_base_1, range_1, editorBrowser_1, themeService_1, colorRegistry_1, position_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var RenameInputField = (function () {
        function RenameInputField(editor, themeService) {
            var _this = this;
            this.themeService = themeService;
            this._disposables = [];
            // Editor.IContentWidget.allowEditorOverflow
            this.allowEditorOverflow = true;
            this._currentAcceptInput = null;
            this._currentCancelInput = null;
            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: [editorBrowser_1.ContentWidgetPositionPreference.BELOW, editorBrowser_1.ContentWidgetPositionPreference.ABOVE] }
                : null;
        };
        RenameInputField.prototype.acceptInput = function () {
            if (this._currentAcceptInput) {
                this._currentAcceptInput();
            }
        };
        RenameInputField.prototype.cancelInput = function () {
            if (this._currentCancelInput) {
                this._currentCancelInput();
            }
        };
        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 = [], always;
            always = function () {
                lifecycle_1.dispose(disposeOnDone);
                _this._hide();
            };
            return new winjs_base_1.TPromise(function (c, e) {
                _this._currentCancelInput = function () {
                    _this._currentAcceptInput = null;
                    _this._currentCancelInput = null;
                    e(errors_1.canceled());
                    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();
                        return;
                    }
                    _this._currentAcceptInput = null;
                    _this._currentCancelInput = null;
                    c(_this._inputField.value);
                };
                var onCursorChanged = function () {
                    if (!range_1.Range.containsPosition(where, _this._editor.getPosition())) {
                        _this.cancelInput();
                    }
                };
                disposeOnDone.push(_this._editor.onDidChangeCursorSelection(onCursorChanged));
                disposeOnDone.push(_this._editor.onDidBlurEditor(function () { return _this.cancelInput(); }));
                _this._show();
            }, this._currentCancelInput).then(function (newValue) {
                always();
                return newValue;
            }, function (err) {
                always();
                return winjs_base_1.TPromise.wrapError(err);
            });
        };
        RenameInputField.prototype._show = function () {
            var _this = this;
            this._editor.revealLineInCenterIfOutsideViewport(this._position.lineNumber);
            this._visible = true;
            this._editor.layoutContentWidget(this);
            setTimeout(function () {
                _this._inputField.focus();
                _this._inputField.setSelectionRange(parseInt(_this._inputField.getAttribute('selectionStart')), parseInt(_this._inputField.getAttribute('selectionEnd')));
            }, 25);
        };
        RenameInputField.prototype._hide = function () {
            this._visible = false;
            this._editor.layoutContentWidget(this);
        };
        RenameInputField = __decorate([
            __param(1, themeService_1.IThemeService)
        ], RenameInputField);
        return RenameInputField;
    }());
    exports.default = 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[529/*vs/editor/contrib/rename/browser/rename*/], __M([1/*require*/,0/*exports*/,368/*vs/nls!vs/editor/contrib/rename/browser/rename*/,10/*vs/base/common/errors*/,36/*vs/base/common/severity*/,7/*vs/base/common/winjs.base*/,411/*vs/platform/files/common/files*/,19/*vs/platform/contextkey/common/contextkey*/,50/*vs/platform/message/common/message*/,163/*vs/platform/progress/common/progress*/,13/*vs/editor/common/editorCommonExtensions*/,30/*vs/editor/browser/editorBrowserExtensions*/,21/*vs/editor/common/editorContextKeys*/,338/*vs/editor/common/services/bulkEdit*/,528/*vs/editor/contrib/rename/browser/renameInputField*/,87/*vs/editor/common/services/resolverService*/,16/*vs/platform/instantiation/common/instantiation*/,14/*vs/platform/theme/common/themeService*/,18/*vs/base/common/async*/,17/*vs/editor/common/modes*/,51/*vs/base/browser/ui/aria/aria*/,2/*vs/editor/common/core/range*/]), function (require, exports, nls, errors_1, severity_1, winjs_base_1, files_1, contextkey_1, message_1, progress_1, editorCommonExtensions_1, editorBrowserExtensions_1, editorContextKeys_1, bulkEdit_1, renameInputField_1, resolverService_1, instantiation_1, themeService_1, async_1, modes_1, aria_1, range_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    function rename(model, position, newName) {
        var supports = modes_1.RenameProviderRegistry.ordered(model);
        var rejects = [];
        var hasResult = false;
        var factory = supports.map(function (support) {
            return function () {
                if (!hasResult) {
                    return async_1.asWinJsPromise(function (token) {
                        return support.provideRenameEdits(model, position, newName, token);
                    }).then(function (result) {
                        if (!result) {
                            // ignore
                        }
                        else if (!result.rejectReason) {
                            hasResult = true;
                            return result;
                        }
                        else {
                            rejects.push(result.rejectReason);
                        }
                        return undefined;
                    }, function (err) {
                        errors_1.onUnexpectedExternalError(err);
                        return winjs_base_1.TPromise.wrapError(new Error('provider failed'));
                    });
                }
                return undefined;
            };
        });
        return async_1.sequence(factory).then(function (values) {
            var result = values[0];
            if (rejects.length > 0) {
                return {
                    edits: undefined,
                    rejectReason: rejects.join('\n')
                };
            }
            else if (!result) {
                return {
                    edits: undefined,
                    rejectReason: nls.localize(0, null)
                };
            }
            else {
                return result;
            }
        });
    }
    exports.rename = rename;
    // ---  register actions and commands
    var CONTEXT_RENAME_INPUT_VISIBLE = new contextkey_1.RawContextKey('renameInputVisible', false);
    var RenameController = (function () {
        function RenameController(editor, _messageService, _textModelResolverService, _progressService, contextKeyService, themeService, _fileService) {
            this.editor = editor;
            this._messageService = _messageService;
            this._textModelResolverService = _textModelResolverService;
            this._progressService = _progressService;
            this._fileService = _fileService;
            this._renameInputField = new renameInputField_1.default(editor, themeService);
            this._renameInputVisible = CONTEXT_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
        }
        RenameController_1 = RenameController;
        RenameController.get = function (editor) {
            return editor.getContribution(RenameController_1.ID);
        };
        RenameController.prototype.dispose = function () {
            this._renameInputField.dispose();
        };
        RenameController.prototype.getId = function () {
            return RenameController_1.ID;
        };
        RenameController.prototype.run = function () {
            var _this = this;
            var selection = this.editor.getSelection(), word = this.editor.getModel().getWordAtPosition(selection.getStartPosition());
            if (!word) {
                return undefined;
            }
            var lineNumber = selection.startLineNumber, selectionStart = 0, selectionEnd = word.word.length, wordRange;
            wordRange = new range_1.Range(lineNumber, word.startColumn, lineNumber, word.endColumn);
            if (!selection.isEmpty() && selection.startLineNumber === selection.endLineNumber) {
                selectionStart = Math.max(0, selection.startColumn - word.startColumn);
                selectionEnd = Math.min(word.endColumn, selection.endColumn) - word.startColumn;
            }
            this._renameInputVisible.set(true);
            return this._renameInputField.getInput(wordRange, word.word, selectionStart, selectionEnd).then(function (newName) {
                _this._renameInputVisible.reset();
                _this.editor.focus();
                var renameOperation = _this._prepareRename(newName).then(function (edit) {
                    return edit.finish().then(function (selection) {
                        if (selection) {
                            _this.editor.setSelection(selection);
                        }
                        // alert
                        aria_1.alert(nls.localize(1, null, word.word, newName, edit.ariaMessage()));
                    });
                }, function (err) {
                    if (typeof err === 'string') {
                        _this._messageService.show(severity_1.default.Info, err);
                        return undefined;
                    }
                    else {
                        _this._messageService.show(severity_1.default.Error, nls.localize(2, null));
                        return winjs_base_1.TPromise.wrapError(err);
                    }
                });
                _this._progressService.showWhile(renameOperation, 250);
                return renameOperation;
            }, function (err) {
                _this._renameInputVisible.reset();
                _this.editor.focus();
                if (!errors_1.isPromiseCanceledError(err)) {
                    return winjs_base_1.TPromise.wrapError(err);
                }
                return undefined;
            });
        };
        RenameController.prototype.acceptRenameInput = function () {
            this._renameInputField.acceptInput();
        };
        RenameController.prototype.cancelRenameInput = function () {
            this._renameInputField.cancelInput();
        };
        RenameController.prototype._prepareRename = function (newName) {
            // start recording of file changes so that we can figure out if a file that
            // is to be renamed conflicts with another (concurrent) modification
            var edit = bulkEdit_1.createBulkEdit(this._textModelResolverService, this.editor, this._fileService);
            return rename(this.editor.getModel(), this.editor.getPosition(), newName).then(function (result) {
                if (result.rejectReason) {
                    return winjs_base_1.TPromise.wrapError(new Error(result.rejectReason));
                }
                edit.add(result.edits);
                return edit;
            });
        };
        RenameController.ID = 'editor.contrib.renameController';
        RenameController = RenameController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, message_1.IMessageService),
            __param(2, resolverService_1.ITextModelService),
            __param(3, progress_1.IProgressService),
            __param(4, contextkey_1.IContextKeyService),
            __param(5, themeService_1.IThemeService),
            __param(6, instantiation_1.optional(files_1.IFileService))
        ], RenameController);
        return RenameController;
        var RenameController_1;
    }());
    // ---- action implementation
    var RenameAction = (function (_super) {
        __extends(RenameAction, _super);
        function RenameAction() {
            return _super.call(this, {
                id: 'editor.action.rename',
                label: nls.localize(3, null),
                alias: 'Rename Symbol',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasRenameProvider),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 60 /* F2 */
                },
                menuOpts: {
                    group: '1_modification',
                    order: 1.1
                }
            }) || this;
        }
        RenameAction.prototype.run = function (accessor, editor) {
            var controller = RenameController.get(editor);
            if (controller) {
                return controller.run();
            }
            return undefined;
        };
        RenameAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], RenameAction);
        return RenameAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.RenameAction = RenameAction;
    var RenameCommand = editorCommonExtensions_1.EditorCommand.bindToContribution(RenameController.get);
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new RenameCommand({
        id: 'acceptRenameInput',
        precondition: CONTEXT_RENAME_INPUT_VISIBLE,
        handler: function (x) { return x.acceptRenameInput(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(99),
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 3 /* Enter */
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new RenameCommand({
        id: 'cancelRenameInput',
        precondition: CONTEXT_RENAME_INPUT_VISIBLE,
        handler: function (x) { return x.cancelRenameInput(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(99),
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 9 /* Escape */,
            secondary: [1024 /* Shift */ | 9 /* Escape */]
        }
    }));
    // ---- api bridge command
    editorCommonExtensions_1.CommonEditorRegistry.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[530/*vs/editor/contrib/suggest/browser/suggestWidget*/], __M([1/*require*/,0/*exports*/,372/*vs/nls!vs/editor/contrib/suggest/browser/suggestWidget*/,81/*vs/base/common/filters*/,9/*vs/base/common/strings*/,11/*vs/base/common/event*/,7/*vs/base/common/winjs.base*/,10/*vs/base/common/errors*/,3/*vs/base/common/lifecycle*/,4/*vs/base/browser/dom*/,110/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,234/*vs/base/browser/ui/list/listWidget*/,63/*vs/base/browser/ui/scrollbar/scrollableElement*/,46/*vs/platform/keybinding/common/keybinding*/,19/*vs/platform/contextkey/common/contextkey*/,25/*vs/editor/browser/editorBrowser*/,109/*vs/editor/contrib/suggest/browser/suggest*/,51/*vs/base/browser/ui/aria/aria*/,58/*vs/platform/telemetry/common/telemetry*/,137/*vs/platform/theme/common/styler*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,76/*vs/platform/storage/common/storage*/,395/*vs/css!vs/editor/contrib/suggest/browser/media/suggest*/]), function (require, exports, nls, filters_1, strings, event_1, winjs_base_1, errors_1, lifecycle_1, dom_1, highlightedLabel_1, listWidget_1, scrollableElement_1, keybinding_1, contextkey_1, editorBrowser_1, suggest_1, aria_1, telemetry_1, styler_1, themeService_1, colorRegistry_1, storage_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var sticky = false; // for development purposes
    var expandSuggestionDocsByDefault = false;
    var maxSuggestionsToShow = 12;
    /**
     * 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 matchesColor(text) {
        return text && text.match(colorRegExp) ? text : null;
    }
    function canExpandCompletionItem(item) {
        if (!item) {
            return false;
        }
        var suggestion = item.suggestion;
        if (suggestion.documentation) {
            return true;
        }
        return (suggestion.detail && suggestion.detail !== suggestion.label);
    }
    var Renderer = (function () {
        function Renderer(widget, editor, triggerKeybindingLabel) {
            this.widget = widget;
            this.editor = editor;
            this.triggerKeybindingLabel = triggerKeybindingLabel;
        }
        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;
            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.highlightedLabel = new highlightedLabel_1.HighlightedLabel(main);
            data.disposables.push(data.highlightedLabel);
            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 fontSizePx = fontSize + "px";
                var lineHeightPx = lineHeight + "px";
                data.root.style.fontSize = fontSizePx;
                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.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.suggestion;
            if (canExpandCompletionItem(element)) {
                data.root.setAttribute('aria-label', nls.localize(6, null, suggestion.label));
            }
            else {
                data.root.setAttribute('aria-label', nls.localize(7, null, suggestion.label));
            }
            data.icon.className = 'icon ' + suggestion.type;
            data.colorspan.style.backgroundColor = '';
            if (suggestion.type === 'color') {
                var color = matchesColor(suggestion.label) || matchesColor(suggestion.documentation);
                if (color) {
                    data.icon.className = 'icon customcolor';
                    data.colorspan.style.backgroundColor = color;
                }
            }
            data.highlightedLabel.set(suggestion.label, filters_1.createMatches(element.matches));
            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.highlightedLabel.dispose();
            templateData.disposables = lifecycle_1.dispose(templateData.disposables);
        };
        return Renderer;
    }());
    var State;
    (function (State) {
        State[State["Hidden"] = 0] = "Hidden";
        State[State["Loading"] = 1] = "Loading";
        State[State["Empty"] = 2] = "Empty";
        State[State["Open"] = 3] = "Open";
        State[State["Frozen"] = 4] = "Frozen";
        State[State["Details"] = 5] = "Details";
    })(State || (State = {}));
    var SuggestionDetails = (function () {
        function SuggestionDetails(container, widget, editor, triggerKeybindingLabel) {
            var _this = this;
            this.widget = widget;
            this.editor = editor;
            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(8, null, 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.chain(this.editor.onDidChangeConfiguration.bind(this.editor))
                .filter(function (e) { return e.fontInfo; })
                .on(this.configureFont, 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;
            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');
            this.docs.textContent = item.suggestion.documentation;
            if (item.suggestion.detail) {
                this.type.innerText = item.suggestion.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}\n{1}\n{2}', item.suggestion.label || '', item.suggestion.detail || '', item.suggestion.documentation || '');
        };
        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 fontSizePx = fontSize + "px";
            var lineHeightPx = lineHeight + "px";
            this.el.style.fontSize = fontSizePx;
            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);
        };
        return SuggestionDetails;
    }());
    var SuggestWidget = (function () {
        function SuggestWidget(editor, telemetryService, contextKeyService, themeService, storageService, keybindingService) {
            var _this = this;
            this.editor = editor;
            this.telemetryService = telemetryService;
            // Editor.IContentWidget.allowEditorOverflow
            this.allowEditorOverflow = true;
            this.ignoreFocusEvents = false;
            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.storageServiceAvailable = true;
            this.expandSuggestionDocs = false;
            var kb = keybindingService.lookupKeybinding('editor.action.triggerSuggest');
            var triggerKeybindingLabel = !kb ? '' : " (" + kb.getLabel() + ")";
            this.isAuto = false;
            this.focusedItem = null;
            this.storageService = storageService;
            if (this.expandDocsSettingFromStorage() === undefined) {
                this.storageService.store('expandSuggestionDocs', expandSuggestionDocsByDefault, storage_1.StorageScope.GLOBAL);
                if (this.expandDocsSettingFromStorage() === undefined) {
                    this.storageServiceAvailable = false;
                }
            }
            this.element = dom_1.$('.editor-widget.suggest-widget');
            if (!this.editor.getConfiguration().contribInfo.iconsInSuggestions) {
                dom_1.addClass(this.element, 'no-icons');
            }
            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, triggerKeybindingLabel);
            var renderer = new Renderer(this, this.editor, triggerKeybindingLabel);
            this.list = new listWidget_1.List(this.listElement, this, [renderer], {
                useShadows: false,
                selectOnMouseDown: true
            });
            this.toDispose = [
                styler_1.attachListStyler(this.list, themeService, {
                    listInactiveFocusBackground: exports.editorSuggestWidgetSelectedBackground,
                    listInactiveFocusOutline: colorRegistry_1.activeContrastBorder
                }),
                themeService.onThemeChange(function (t) { return _this.onThemeChange(t); }),
                editor.onDidBlurEditorText(function () { return _this.onEditorBlur(); }),
                editor.onDidLayoutChange(function () { return _this.onEditorLayoutChange(); }),
                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.suggestWidgetVisible = suggest_1.Context.Visible.bindTo(contextKeyService);
            this.suggestWidgetMultipleSuggestions = suggest_1.Context.MultipleSuggestions.bindTo(contextKeyService);
            this.suggestionSupportsAutoAccept = suggest_1.Context.AcceptOnKey.bindTo(contextKeyService);
            this.editor.addContentWidget(this);
            this.setState(0 /* Hidden */);
            this.onThemeChange(themeService.getTheme());
            // TODO@Alex: this is useful, but spammy
            // var isVisible = false;
            // this.onDidVisibilityChange((newIsVisible) => {
            // 	if (isVisible === newIsVisible) {
            // 		return;
            // 	}
            // 	isVisible = newIsVisible;
            // 	if (isVisible) {
            // 		alert(nls.localize('suggestWidgetAriaVisible', "Suggestions opened"));
            // 	} else {
            // 		alert(nls.localize('suggestWidgetAriaInvisible', "Suggestions closed"));
            // 	}
            // });
        }
        SuggestWidget.prototype.onCursorSelectionChanged = function () {
            if (this.state === 0 /* Hidden */) {
                return;
            }
            this.editor.layoutContentWidget(this);
        };
        SuggestWidget.prototype.onEditorBlur = function () {
            var _this = this;
            if (sticky) {
                return;
            }
            this.editorBlurTimeout = winjs_base_1.TPromise.timeout(150).then(function () {
                if (!_this.editor.isFocused()) {
                    _this.setState(0 /* Hidden */);
                }
            });
        };
        SuggestWidget.prototype.onEditorLayoutChange = function () {
            if ((this.state === 3 /* Open */ || this.state === 5 /* Details */) && this.expandDocsSettingFromStorage()) {
                this.expandSideOrBelow();
            }
        };
        SuggestWidget.prototype.onListSelection = function (e) {
            if (!e.elements.length) {
                return;
            }
            var item = e.elements[0];
            this.onDidSelectEmitter.fire(item);
            aria_1.alert(nls.localize(11, null, item.suggestion.label));
            this.editor.focus();
        };
        SuggestWidget.prototype._getSuggestionAriaAlertLabel = function (item) {
            if (canExpandCompletionItem(item)) {
                return nls.localize(12, null, item.suggestion.label);
            }
            else {
                return nls.localize(13, null, item.suggestion.label);
            }
        };
        SuggestWidget.prototype._ariaAlert = function (newAriaAlertLabel) {
            if (this._lastAriaAlertLabel === newAriaAlertLabel) {
                return;
            }
            this._lastAriaAlertLabel = newAriaAlertLabel;
            if (this._lastAriaAlertLabel) {
                aria_1.alert(this._lastAriaAlertLabel);
            }
        };
        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);
                // TODO@Alex: Chromium bug
                // this.editor.setAriaActiveDescendant(null);
                return;
            }
            var item = e.elements[0];
            this._ariaAlert(this._getSuggestionAriaAlertLabel(item));
            // TODO@Alex: Chromium bug
            // // TODO@Alex: the list is not done rendering...
            // setTimeout(() => {
            // 	this.editor.setAriaActiveDescendant(this.list.getElementId(e.indexes[0]));
            // }, 100);
            if (item === this.focusedItem) {
                return;
            }
            if (this.currentSuggestionDetails) {
                this.currentSuggestionDetails.cancel();
                this.currentSuggestionDetails = null;
            }
            var index = e.indexes[0];
            this.suggestionSupportsAutoAccept.set(!item.suggestion.noAutoAccept);
            var oldFocus = this.focusedItem;
            var oldFocusIndex = this.focusedItemIndex;
            this.focusedItemIndex = index;
            this.focusedItem = item;
            if (oldFocus) {
                this.ignoreFocusEvents = true;
                this.list.splice(oldFocusIndex, 1, [oldFocus]);
                this.ignoreFocusEvents = false;
            }
            this.updateListHeight();
            this.list.reveal(index);
            this.currentSuggestionDetails = item.resolve()
                .then(function () {
                _this.ignoreFocusEvents = true;
                _this.list.splice(index, 1, [item]);
                _this.ignoreFocusEvents = false;
                _this.list.setFocus([index]);
                _this.list.reveal(index);
                if (_this.expandDocsSettingFromStorage()) {
                    _this.showDetails();
                }
                else {
                    dom_1.removeClass(_this.element, 'docs-side');
                }
            })
                .then(null, function (err) { return !errors_1.isPromiseCanceledError(err) && errors_1.onUnexpectedError(err); })
                .then(function () { return _this.currentSuggestionDetails = null; });
            // emit an event
            this.onDidFocusEmitter.fire(item);
        };
        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);
                    dom_1.show(this.listElement);
                    this.hide();
                    if (stateChanged) {
                        this.list.splice(0, this.list.length);
                    }
                    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();
                    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();
                    break;
                case 3 /* Open */:
                    dom_1.hide(this.messageElement);
                    dom_1.show(this.listElement);
                    if (this.expandDocsSettingFromStorage()
                        && canExpandCompletionItem(this.list.getFocusedElements()[0])) {
                        dom_1.show(this.details.element);
                        this.expandSideOrBelow();
                    }
                    else {
                        dom_1.hide(this.details.element);
                    }
                    this.show();
                    break;
                case 4 /* Frozen */:
                    dom_1.hide(this.messageElement, this.details.element);
                    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;
            }
            if (stateChanged) {
                this.editor.layoutContentWidget(this);
            }
        };
        SuggestWidget.prototype.showTriggered = function (auto) {
            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 */);
                }, 50);
            }
        };
        SuggestWidget.prototype.showSuggestions = function (completionModel, isFrozen, isAuto) {
            if (this.loadingTimeout) {
                clearTimeout(this.loadingTimeout);
                this.loadingTimeout = null;
            }
            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 {
                var stats = this.completionModel.stats;
                stats['wasAutomaticallyTriggered'] = !!isAuto;
                this.telemetryService.publicLog('suggestWidget', __assign({}, stats, this.editor.getTelemetryData()));
                this.focusedItem = null;
                this.focusedItemIndex = null;
                this.list.splice(0, this.list.length, this.completionModel.items);
                this.list.setFocus([0]);
                this.list.reveal(0, 0);
                if (isFrozen) {
                    this.setState(4 /* Frozen */);
                }
                else {
                    this.setState(3 /* Open */);
                }
                // 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 */) {
                return this.list.getFocusedElements()[0];
            }
            return undefined;
        };
        SuggestWidget.prototype.toggleDetailsFocus = function () {
            if (this.state === 5 /* Details */) {
                this.setState(3 /* Open */);
                if (this.detailsBorderColor) {
                    this.details.element.style.borderColor = this.detailsBorderColor;
                }
            }
            else if (this.state === 3 /* Open */ && this.expandDocsSettingFromStorage()) {
                this.setState(5 /* Details */);
                if (this.detailsFocusBorderColor) {
                    this.details.element.style.borderColor = this.detailsFocusBorderColor;
                }
            }
            this.telemetryService.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);
                this.telemetryService.publicLog('suggestWidget:collapseDetails', this.editor.getTelemetryData());
            }
            else {
                if (this.state !== 3 /* Open */ && this.state !== 5 /* Details */) {
                    return;
                }
                this.updateExpandDocsSetting(true);
                this.showDetails();
                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();
            this._ariaAlert(this.details.getAriaLabel());
        };
        SuggestWidget.prototype.show = function () {
            var _this = this;
            this.updateListHeight();
            this.suggestWidgetVisible.set(true);
            this.showTimeout = winjs_base_1.TPromise.timeout(100).then(function () {
                dom_1.addClass(_this.element, 'visible');
                _this.onDidShowEmitter.fire(_this);
            });
        };
        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;
            }
            return {
                position: this.editor.getPosition(),
                preference: [editorBrowser_1.ContentWidgetPositionPreference.BELOW, editorBrowser_1.ContentWidgetPositionPreference.ABOVE]
            };
        };
        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;
                height = Math.min(suggestionCount, maxSuggestionsToShow) * this.unfocusedHeight;
            }
            this.element.style.lineHeight = this.unfocusedHeight + "px";
            this.listElement.style.height = height + "px";
            this.list.layout(height);
            this.editor.layoutContentWidget(this);
            return height;
        };
        SuggestWidget.prototype.adjustDocsPosition = function () {
            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;
            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";
            }
        };
        SuggestWidget.prototype.expandSideOrBelow = function () {
            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 {
                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 * maxSuggestionsToShow;
            },
            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';
        };
        // Monaco Editor does not have a storage service
        SuggestWidget.prototype.expandDocsSettingFromStorage = function () {
            if (this.storageServiceAvailable) {
                return this.storageService.getBoolean('expandSuggestionDocs', storage_1.StorageScope.GLOBAL);
            }
            else {
                return this.expandSuggestionDocs;
            }
        };
        // Monaco Editor does not have a storage service
        SuggestWidget.prototype.updateExpandDocsSetting = function (value) {
            if (this.storageServiceAvailable) {
                this.storageService.store('expandSuggestionDocs', value, storage_1.StorageScope.GLOBAL);
            }
            else {
                this.expandSuggestionDocs = value;
            }
        };
        SuggestWidget.prototype.dispose = function () {
            this.state = null;
            this.suggestionSupportsAutoAccept = null;
            this.currentSuggestionDetails = null;
            this.focusedItem = null;
            this.element = null;
            this.messageElement = null;
            this.listElement = null;
            this.details.dispose();
            this.details = null;
            this.list.dispose();
            this.list = null;
            this.toDispose = lifecycle_1.dispose(this.toDispose);
            if (this.loadingTimeout) {
                clearTimeout(this.loadingTimeout);
                this.loadingTimeout = null;
            }
            if (this.editorBlurTimeout) {
                this.editorBlurTimeout.cancel();
                this.editorBlurTimeout = null;
            }
            if (this.showTimeout) {
                this.showTimeout.cancel();
                this.showTimeout = null;
            }
        };
        SuggestWidget.ID = 'editor.widget.suggestWidget';
        SuggestWidget.LOADING_MESSAGE = nls.localize(9, null);
        SuggestWidget.NO_SUGGESTIONS_MESSAGE = nls.localize(10, 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)
        ], 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:not(.frozen) .monaco-highlighted-label .highlight { color: " + matchHighlight + "; }");
        }
        var foreground = theme.getColor(exports.editorSuggestWidgetForeground);
        if (foreground) {
            collector.addRule(".monaco-editor .suggest-widget { color: " + foreground + "; }");
        }
    });
});




























define(__m[531/*vs/editor/contrib/suggest/browser/suggestController*/], __M([1/*require*/,0/*exports*/,371/*vs/nls!vs/editor/contrib/suggest/browser/suggestController*/,10/*vs/base/common/errors*/,33/*vs/base/common/arrays*/,3/*vs/base/common/lifecycle*/,16/*vs/platform/instantiation/common/instantiation*/,58/*vs/platform/telemetry/common/telemetry*/,19/*vs/platform/contextkey/common/contextkey*/,31/*vs/platform/commands/common/commands*/,21/*vs/editor/common/editorContextKeys*/,13/*vs/editor/common/editorCommonExtensions*/,51/*vs/base/browser/ui/aria/aria*/,30/*vs/editor/browser/editorBrowserExtensions*/,59/*vs/editor/common/core/editOperation*/,2/*vs/editor/common/core/range*/,142/*vs/editor/contrib/snippet/browser/snippetParser*/,180/*vs/editor/contrib/snippet/browser/snippetController2*/,109/*vs/editor/contrib/suggest/browser/suggest*/,474/*vs/editor/contrib/suggest/browser/suggestModel*/,530/*vs/editor/contrib/suggest/browser/suggestWidget*/]), function (require, exports, nls, errors_1, arrays_1, lifecycle_1, instantiation_1, telemetry_1, contextkey_1, commands_1, editorContextKeys_1, editorCommonExtensions_1, aria_1, editorBrowserExtensions_1, editOperation_1, range_1, snippetParser_1, snippetController2_1, suggest_1, suggestModel_1, suggestWidget_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var AcceptOnCharacterOracle = (function () {
        function AcceptOnCharacterOracle(editor, widget, accept) {
            var _this = this;
            this._disposables = [];
            this._activeAcceptCharacters = new Set();
            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._activeItem) {
                    var ch = text[text.length - 1];
                    if (_this._activeAcceptCharacters.has(ch) && editor.getConfiguration().contribInfo.acceptSuggestionOnCommitCharacter) {
                        accept(_this._activeItem);
                    }
                }
            }));
        }
        AcceptOnCharacterOracle.prototype._onItem = function (item) {
            if (!item || arrays_1.isFalsyOrEmpty(item.suggestion.commitCharacters)) {
                this.reset();
                return;
            }
            this._activeItem = item;
            this._activeAcceptCharacters.clear();
            for (var _i = 0, _a = item.suggestion.commitCharacters; _i < _a.length; _i++) {
                var ch = _a[_i];
                if (ch.length > 0) {
                    this._activeAcceptCharacters.add(ch[0]);
                }
            }
        };
        AcceptOnCharacterOracle.prototype.reset = function () {
            this._activeItem = undefined;
        };
        AcceptOnCharacterOracle.prototype.dispose = function () {
            lifecycle_1.dispose(this._disposables);
        };
        return AcceptOnCharacterOracle;
    }());
    var SuggestController = (function () {
        function SuggestController(_editor, _commandService, _telemetryService, _contextKeyService, _instantiationService) {
            var _this = this;
            this._editor = _editor;
            this._commandService = _commandService;
            this._telemetryService = _telemetryService;
            this._toDispose = [];
            this._model = new suggestModel_1.SuggestModel(this._editor);
            this._toDispose.push(this._model.onDidTrigger(function (e) { return _this._widget.showTriggered(e.auto); }));
            this._toDispose.push(this._model.onDidSuggest(function (e) { return _this._widget.showSuggestions(e.completionModel, e.isFrozen, e.auto); }));
            this._toDispose.push(this._model.onDidCancel(function (e) { return !e.retrigger && _this._widget.hideWidget(); }));
            // 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'
                    || acceptSuggestionOnEnter === true);
            };
            this._toDispose.push(this._editor.onDidChangeConfiguration(function (e) { return updateFromConfig(); }));
            updateFromConfig();
            this._widget = _instantiationService.createInstance(suggestWidget_1.SuggestWidget, this._editor);
            this._toDispose.push(this._widget.onDidSelect(this._onDidSelectItem, this));
            // Wire up logic to accept a suggestion on certain characters
            var autoAcceptOracle = new AcceptOnCharacterOracle(_editor, this._widget, function (item) { return _this._onDidSelectItem(item); });
            this._toDispose.push(autoAcceptOracle, this._model.onDidSuggest(function (e) {
                if (e.completionModel.items.length === 0) {
                    autoAcceptOracle.reset();
                }
            }));
            var makesTextEdit = suggest_1.Context.MakesTextEdit.bindTo(_contextKeyService);
            this._toDispose.push(this._widget.onDidFocus(function (item) {
                var position = _this._editor.getPosition();
                var startColumn = item.position.column - item.suggestion.overwriteBefore;
                var endColumn = position.column;
                var value = true;
                if (_this._editor.getConfiguration().contribInfo.acceptSuggestionOnEnter === 'smart'
                    && _this._model.state === 2 /* Auto */
                    && !item.suggestion.command
                    && !item.suggestion.additionalTextEdits
                    && item.suggestion.snippetType !== 'textmate'
                    && endColumn - startColumn === item.suggestion.insertText.length) {
                    var oldText = _this._editor.getModel().getValueInRange({
                        startLineNumber: position.lineNumber,
                        startColumn: startColumn,
                        endLineNumber: position.lineNumber,
                        endColumn: endColumn
                    });
                    value = oldText !== item.suggestion.insertText;
                }
                makesTextEdit.set(value);
            }));
            this._toDispose.push({
                dispose: function () { makesTextEdit.reset(); }
            });
        }
        SuggestController_1 = SuggestController;
        SuggestController.get = function (editor) {
            return editor.getContribution(SuggestController_1.ID);
        };
        SuggestController.prototype.getId = function () {
            return SuggestController_1.ID;
        };
        SuggestController.prototype.dispose = function () {
            this._toDispose = lifecycle_1.dispose(this._toDispose);
            if (this._widget) {
                this._widget.dispose();
                this._widget = null;
            }
            if (this._model) {
                this._model.dispose();
                this._model = null;
            }
        };
        SuggestController.prototype._onDidSelectItem = function (item) {
            if (item) {
                var suggestion = item.suggestion, position = item.position;
                var columnDelta = this._editor.getPosition().column - position.column;
                if (Array.isArray(suggestion.additionalTextEdits)) {
                    this._editor.pushUndoStop();
                    this._editor.executeEdits('suggestController.additionalTextEdits', suggestion.additionalTextEdits.map(function (edit) { return editOperation_1.EditOperation.replace(range_1.Range.lift(edit.range), edit.text); }));
                    this._editor.pushUndoStop();
                }
                var insertText = suggestion.insertText;
                if (suggestion.snippetType !== 'textmate') {
                    insertText = snippetParser_1.SnippetParser.escape(insertText);
                }
                snippetController2_1.SnippetController2.get(this._editor).insert(insertText, suggestion.overwriteBefore + columnDelta, suggestion.overwriteAfter);
                if (suggestion.command) {
                    (_a = this._commandService).executeCommand.apply(_a, [suggestion.command.id].concat(suggestion.command.arguments)).done(undefined, errors_1.onUnexpectedError);
                }
                this._alertCompletionItem(item);
                this._telemetryService.publicLog('suggestSnippetInsert', __assign({}, this._editor.getTelemetryData(), { suggestionType: suggestion.type }));
            }
            this._model.cancel();
            var _a;
        };
        SuggestController.prototype._alertCompletionItem = function (_a) {
            var suggestion = _a.suggestion;
            var msg = nls.localize(0, null, suggestion.label, suggestion.insertText);
            aria_1.alert(msg);
        };
        SuggestController.prototype.triggerSuggest = function (onlyFrom) {
            this._model.trigger(false, false, onlyFrom);
            this._editor.revealLine(this._editor.getPosition().lineNumber);
            this._editor.focus();
        };
        SuggestController.prototype.acceptSelectedSuggestion = function () {
            if (this._widget) {
                var item = this._widget.getFocusedItem();
                this._onDidSelectItem(item);
            }
        };
        SuggestController.prototype.cancelSuggestWidget = function () {
            if (this._widget) {
                this._model.cancel();
                this._widget.hideWidget();
            }
        };
        SuggestController.prototype.selectNextSuggestion = function () {
            if (this._widget) {
                this._widget.selectNext();
            }
        };
        SuggestController.prototype.selectNextPageSuggestion = function () {
            if (this._widget) {
                this._widget.selectNextPage();
            }
        };
        SuggestController.prototype.selectLastSuggestion = function () {
            if (this._widget) {
                this._widget.selectLast();
            }
        };
        SuggestController.prototype.selectPrevSuggestion = function () {
            if (this._widget) {
                this._widget.selectPrevious();
            }
        };
        SuggestController.prototype.selectPrevPageSuggestion = function () {
            if (this._widget) {
                this._widget.selectPreviousPage();
            }
        };
        SuggestController.prototype.selectFirstSuggestion = function () {
            if (this._widget) {
                this._widget.selectFirst();
            }
        };
        SuggestController.prototype.toggleSuggestionDetails = function () {
            if (this._widget) {
                this._widget.toggleDetails();
            }
        };
        SuggestController.prototype.toggleSuggestionFocus = function () {
            if (this._widget) {
                this._widget.toggleDetailsFocus();
            }
        };
        SuggestController.ID = 'editor.contrib.suggestController';
        SuggestController = SuggestController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, commands_1.ICommandService),
            __param(2, telemetry_1.ITelemetryService),
            __param(3, contextkey_1.IContextKeyService),
            __param(4, instantiation_1.IInstantiationService)
        ], SuggestController);
        return SuggestController;
        var SuggestController_1;
    }());
    exports.SuggestController = SuggestController;
    var TriggerSuggestAction = (function (_super) {
        __extends(TriggerSuggestAction, _super);
        function TriggerSuggestAction() {
            return _super.call(this, {
                id: 'editor.action.triggerSuggest',
                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.textFocus,
                    primary: 2048 /* CtrlCmd */ | 10 /* Space */,
                    mac: { primary: 256 /* WinCtrl */ | 10 /* Space */ }
                }
            }) || this;
        }
        TriggerSuggestAction.prototype.run = function (accessor, editor) {
            var controller = SuggestController.get(editor);
            if (!controller) {
                return;
            }
            controller.triggerSuggest();
        };
        TriggerSuggestAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], TriggerSuggestAction);
        return TriggerSuggestAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.TriggerSuggestAction = TriggerSuggestAction;
    var weight = editorCommonExtensions_1.CommonEditorRegistry.commandWeight(90);
    var SuggestCommand = editorCommonExtensions_1.EditorCommand.bindToContribution(SuggestController.get);
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new SuggestCommand({
        id: 'acceptSelectedSuggestion',
        precondition: suggest_1.Context.Visible,
        handler: function (x) { return x.acceptSelectedSuggestion(); },
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
            primary: 2 /* Tab */
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new SuggestCommand({
        id: 'acceptSelectedSuggestionOnEnter',
        precondition: suggest_1.Context.Visible,
        handler: function (x) { return x.acceptSelectedSuggestion(); },
        kbOpts: {
            weight: weight,
            kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textFocus, suggest_1.Context.AcceptSuggestionsOnEnter, suggest_1.Context.MakesTextEdit),
            primary: 3 /* Enter */
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new SuggestCommand({
        id: 'hideSuggestWidget',
        precondition: suggest_1.Context.Visible,
        handler: function (x) { return x.cancelSuggestWidget(); },
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
            primary: 9 /* Escape */,
            secondary: [1024 /* Shift */ | 9 /* Escape */]
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.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.textFocus,
            primary: 18 /* DownArrow */,
            secondary: [2048 /* CtrlCmd */ | 18 /* DownArrow */],
            mac: { primary: 18 /* DownArrow */, secondary: [2048 /* CtrlCmd */ | 18 /* DownArrow */, 256 /* WinCtrl */ | 44 /* KEY_N */] }
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.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.textFocus,
            primary: 12 /* PageDown */,
            secondary: [2048 /* CtrlCmd */ | 12 /* PageDown */]
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new SuggestCommand({
        id: 'selectLastSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions),
        handler: function (c) { return c.selectLastSuggestion(); }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.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.textFocus,
            primary: 16 /* UpArrow */,
            secondary: [2048 /* CtrlCmd */ | 16 /* UpArrow */],
            mac: { primary: 16 /* UpArrow */, secondary: [2048 /* CtrlCmd */ | 16 /* UpArrow */, 256 /* WinCtrl */ | 46 /* KEY_P */] }
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.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.textFocus,
            primary: 11 /* PageUp */,
            secondary: [2048 /* CtrlCmd */ | 11 /* PageUp */]
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new SuggestCommand({
        id: 'selectFirstSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.MultipleSuggestions),
        handler: function (c) { return c.selectFirstSuggestion(); }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new SuggestCommand({
        id: 'toggleSuggestionDetails',
        precondition: suggest_1.Context.Visible,
        handler: function (x) { return x.toggleSuggestionDetails(); },
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
            primary: 2048 /* CtrlCmd */ | 10 /* Space */,
            mac: { primary: 256 /* WinCtrl */ | 10 /* Space */ }
        }
    }));
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new SuggestCommand({
        id: 'toggleSuggestionFocus',
        precondition: suggest_1.Context.Visible,
        handler: function (x) { return x.toggleSuggestionFocus(); },
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
            primary: 2048 /* CtrlCmd */ | 512 /* Alt */ | 10 /* Space */,
            mac: { primary: 256 /* WinCtrl */ | 512 /* Alt */ | 10 /* Space */ }
        }
    }));
});







define(__m[532/*vs/editor/contrib/wordHighlighter/common/wordHighlighter*/], __M([1/*require*/,0/*exports*/,374/*vs/nls!vs/editor/contrib/wordHighlighter/common/wordHighlighter*/,18/*vs/base/common/async*/,10/*vs/base/common/errors*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,13/*vs/editor/common/editorCommonExtensions*/,17/*vs/editor/common/modes*/,3/*vs/base/common/lifecycle*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,54/*vs/editor/common/controller/cursorEvents*/,34/*vs/editor/common/model/textModelWithDecorations*/]), function (require, exports, nls, async_1, errors_1, range_1, editorCommon, editorCommonExtensions_1, modes_1, lifecycle_1, colorRegistry_1, themeService_1, cursorEvents_1, textModelWithDecorations_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.editorWordHighlight = colorRegistry_1.registerColor('editor.wordHighlightBackground', { dark: '#575757B8', light: '#57575740', hc: null }, nls.localize(0, null));
    exports.editorWordHighlightStrong = colorRegistry_1.registerColor('editor.wordHighlightStrongBackground', { dark: '#004972B8', light: '#0e639c40', hc: null }, nls.localize(1, null));
    function getOccurrencesAtPosition(model, position) {
        var orderedByScore = modes_1.DocumentHighlightProviderRegistry.ordered(model);
        var foundResult = false;
        // in order of score ask the occurrences provider
        // until someone response with a good result
        // (good = none empty array)
        return async_1.sequence(orderedByScore.map(function (provider) {
            return function () {
                if (!foundResult) {
                    return async_1.asWinJsPromise(function (token) {
                        return provider.provideDocumentHighlights(model, position, token);
                    }).then(function (data) {
                        if (Array.isArray(data) && data.length > 0) {
                            foundResult = true;
                            return data;
                        }
                        return undefined;
                    }, function (err) {
                        errors_1.onUnexpectedExternalError(err);
                    });
                }
                return undefined;
            };
        })).then(function (values) {
            return values[0];
        });
    }
    exports.getOccurrencesAtPosition = getOccurrencesAtPosition;
    editorCommonExtensions_1.CommonEditorRegistry.registerDefaultLanguageCommand('_executeDocumentHighlights', getOccurrencesAtPosition);
    var WordHighlighter = (function () {
        function WordHighlighter(editor) {
            var _this = this;
            this.workerRequestTokenId = 0;
            this.workerRequest = null;
            this.workerRequestCompleted = false;
            this.workerRequestValue = [];
            this.lastCursorPositionChangeTime = 0;
            this.renderDecorationsTimer = -1;
            this.editor = editor;
            this.occurrencesHighlight = this.editor.getConfiguration().contribInfo.occurrencesHighlight;
            this.model = this.editor.getModel();
            this.toUnhook = [];
            this.toUnhook.push(editor.onDidChangeCursorPosition(function (e) {
                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.onDidChangeModel(function (e) {
                _this._stopAll();
                _this.model = _this.editor.getModel();
            }));
            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._lastWordRange = null;
            this._decorationIds = [];
            this.workerRequestTokenId = 0;
            this.workerRequest = null;
            this.workerRequestCompleted = false;
            this.lastCursorPositionChangeTime = 0;
            this.renderDecorationsTimer = -1;
        }
        WordHighlighter.prototype._removeDecorations = function () {
            if (this._decorationIds.length > 0) {
                // remove decorations
                this._decorationIds = this.editor.deltaDecorations(this._decorationIds, []);
            }
        };
        WordHighlighter.prototype._stopAll = function () {
            this._lastWordRange = null;
            // 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) {
            var _this = this;
            // disabled
            if (!this.occurrencesHighlight) {
                this._stopAll();
                return;
            }
            // ignore typing & other
            if (e.reason !== cursorEvents_1.CursorChangeReason.Explicit) {
                this._stopAll();
                return;
            }
            // no providers for this model
            if (!modes_1.DocumentHighlightProviderRegistry.has(this.model)) {
                this._stopAll();
                return;
            }
            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 currentWordRange = new range_1.Range(lineNumber, word.startColumn, lineNumber, word.endColumn);
            var workerRequestIsValid = this._lastWordRange && this._lastWordRange.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 = this._decorationIds.length; !workerRequestIsValid && i < len; i++) {
                var range = this.model.getDecorationRange(this._decorationIds[i]);
                if (range && range.startLineNumber === lineNumber) {
                    if (range.startColumn <= startColumn && range.endColumn >= endColumn) {
                        workerRequestIsValid = true;
                    }
                }
            }
            // 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 = ++this.workerRequestTokenId;
                this.workerRequestCompleted = false;
                this.workerRequest = getOccurrencesAtPosition(this.model, this.editor.getPosition());
                this.workerRequest.then(function (data) {
                    if (myRequestId === _this.workerRequestTokenId) {
                        _this.workerRequestCompleted = true;
                        _this.workerRequestValue = data || [];
                        _this._beginRenderDecorations();
                    }
                }).done();
            }
            this._lastWordRange = currentWordRange;
        };
        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 {
                // Asyncrhonous
                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);
        };
        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 = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            className: 'wordHighlightStrong',
            overviewRuler: {
                color: '#A0A0A0',
                darkColor: '#A0A0A0',
                position: editorCommon.OverviewRulerLane.Center
            }
        });
        WordHighlighter._TEXT_OPTIONS = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            className: 'selectionHighlight',
            overviewRuler: {
                color: '#A0A0A0',
                darkColor: '#A0A0A0',
                position: editorCommon.OverviewRulerLane.Center
            }
        });
        WordHighlighter._REGULAR_OPTIONS = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            className: 'wordHighlight',
            overviewRuler: {
                color: '#A0A0A0',
                darkColor: '#A0A0A0',
                position: editorCommon.OverviewRulerLane.Center
            }
        });
        return WordHighlighter;
    }());
    var WordHighlighterContribution = (function () {
        function WordHighlighterContribution(editor) {
            this.wordHighligher = new WordHighlighter(editor);
        }
        WordHighlighterContribution_1 = WordHighlighterContribution;
        WordHighlighterContribution.prototype.getId = function () {
            return WordHighlighterContribution_1.ID;
        };
        WordHighlighterContribution.prototype.dispose = function () {
            this.wordHighligher.dispose();
        };
        WordHighlighterContribution.ID = 'editor.contrib.wordHighlighter';
        WordHighlighterContribution = WordHighlighterContribution_1 = __decorate([
            editorCommonExtensions_1.commonEditorContribution
        ], WordHighlighterContribution);
        return WordHighlighterContribution;
        var WordHighlighterContribution_1;
    }());
    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 hcOutline = theme.getColor(colorRegistry_1.activeContrastBorder);
        if (hcOutline) {
            collector.addRule(".monaco-editor .selectionHighlight { border: 1px dotted " + hcOutline + "; box-sizing: border-box; }");
            collector.addRule(".monaco-editor .wordHighlight { border: 1px dashed " + hcOutline + "; box-sizing: border-box; }");
            collector.addRule(".monaco-editor .wordHighlightStrong { border: 1px dashed " + hcOutline + "; 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[92/*vs/editor/contrib/zoneWidget/browser/peekViewWidget*/], __M([1/*require*/,0/*exports*/,375/*vs/nls!vs/editor/contrib/zoneWidget/browser/peekViewWidget*/,53/*vs/base/common/actions*/,9/*vs/base/common/strings*/,26/*vs/base/common/objects*/,52/*vs/base/browser/builder*/,11/*vs/base/common/event*/,4/*vs/base/browser/dom*/,75/*vs/base/browser/ui/actionbar/actionbar*/,16/*vs/platform/instantiation/common/instantiation*/,42/*vs/editor/common/services/codeEditorService*/,183/*vs/editor/contrib/zoneWidget/browser/zoneWidget*/,194/*vs/editor/browser/widget/embeddedCodeEditorWidget*/,19/*vs/platform/contextkey/common/contextkey*/,32/*vs/base/common/color*/,396/*vs/css!vs/editor/contrib/zoneWidget/browser/peekViewWidget*/]), function (require, exports, nls, actions_1, strings, objects, builder_1, event_1, dom, actionbar_1, instantiation_1, codeEditorService_1, zoneWidget_1, embeddedCodeEditorWidget_1, contextkey_1, color_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IPeekViewService = instantiation_1.createDecorator('peekViewService');
    var PeekContext;
    (function (PeekContext) {
        PeekContext.inPeekEditor = new contextkey_1.RawContextKey('inReferenceSearchEditor', true);
        PeekContext.notInPeekEditor = PeekContext.inPeekEditor.toNegated();
    })(PeekContext = exports.PeekContext || (exports.PeekContext = {}));
    exports.NOT_INNER_EDITOR_CONTEXT_KEY = new contextkey_1.RawContextKey('inReferenceSearchEditor', true);
    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 = (function (_super) {
        __extends(PeekViewWidget, _super);
        function PeekViewWidget(editor, options) {
            if (options === void 0) { options = {}; }
            var _this = _super.call(this, editor, options) || this;
            _this._onDidClose = new event_1.Emitter();
            _this._isActive = false;
            objects.mixin(_this.options, defaultOptions, false);
            return _this;
        }
        PeekViewWidget.prototype.dispose = function () {
            this._isActive = false;
            _super.prototype.dispose.call(this);
            this._onDidClose.fire(this);
        };
        Object.defineProperty(PeekViewWidget.prototype, "onDidClose", {
            get: function () {
                return this._onDidClose.event;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PeekViewWidget.prototype, "isActive", {
            get: function () {
                return this._isActive;
            },
            enumerable: true,
            configurable: true
        });
        PeekViewWidget.prototype.show = function (where, heightInLines) {
            this._isActive = true;
            _super.prototype.show.call(this, where, heightInLines);
        };
        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) {
                this._headElement.style.backgroundColor = options.headerBackgroundColor.toString();
            }
            if (this._primaryHeading) {
                this._primaryHeading.style.color = options.primaryHeadingColor.toString();
            }
            if (this._secondaryHeading) {
                this._secondaryHeading.style.color = options.secondaryHeadingColor.toString();
            }
            if (this._bodyElement) {
                this._bodyElement.style.borderColor = options.frameColor.toString();
            }
        };
        PeekViewWidget.prototype._fillContainer = function (container) {
            this.setCssClass('peekview-widget');
            this._headElement = builder_1.$('.head').getHTMLElement();
            this._bodyElement = builder_1.$('.body').getHTMLElement();
            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 = builder_1.$('.peekview-title').
                on(dom.EventType.CLICK, function (e) { return _this._onTitleClick(e); }).
                appendTo(this._headElement).
                getHTMLElement();
            this._primaryHeading = builder_1.$('span.filename').appendTo(titleElement).getHTMLElement();
            this._secondaryHeading = builder_1.$('span.dirname').appendTo(titleElement).getHTMLElement();
            this._metaHeading = builder_1.$('span.meta').appendTo(titleElement).getHTMLElement();
            this._actionbarWidget = new actionbar_1.ActionBar(builder_1.$('.peekview-actions').
                appendTo(this._headElement));
            this._actionbarWidget.push(new actions_1.Action('peekview.close', nls.localize(0, null), 'close-peekview-action', true, function () {
                _this.dispose();
                return null;
            }), { label: false, icon: true });
        };
        PeekViewWidget.prototype._onTitleClick = function (event) {
            // implement me
        };
        PeekViewWidget.prototype.setTitle = function (primaryHeading, secondaryHeading) {
            builder_1.$(this._primaryHeading).safeInnerHtml(primaryHeading);
            this._primaryHeading.setAttribute('aria-label', primaryHeading);
            if (secondaryHeading) {
                builder_1.$(this._secondaryHeading).safeInnerHtml(secondaryHeading);
            }
            else {
                dom.clearNode(this._secondaryHeading);
            }
        };
        PeekViewWidget.prototype.setMetaTitle = function (value) {
            if (value) {
                builder_1.$(this._metaHeading).safeInnerHtml(value);
            }
            else {
                dom.clearNode(this._metaHeading);
            }
        };
        PeekViewWidget.prototype._fillBody = function (container) {
            // implement me
        };
        PeekViewWidget.prototype._doLayout = function (heightInPixel, widthInPixel) {
            if (!this._isShowing && heightInPixel < 0) {
                // Looks like the view zone got folded away!
                this.dispose();
                this._onDidClose.fire(this);
                return;
            }
            var headHeight = Math.ceil(this.editor.getConfiguration().lineHeight * 1.2), 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 = strings.format('{0}px', heightInPixel);
            this._headElement.style.lineHeight = this._headElement.style.height;
        };
        PeekViewWidget.prototype._doLayoutBody = function (heightInPixel, widthInPixel) {
            this._bodyElement.style.height = strings.format('{0}px', heightInPixel);
        };
        return PeekViewWidget;
    }(zoneWidget_1.ZoneWidget));
    exports.PeekViewWidget = PeekViewWidget;
});




















define(__m[534/*vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/], __M([1/*require*/,0/*exports*/,6/*vs/nls*/,3/*vs/base/common/lifecycle*/,9/*vs/base/common/strings*/,4/*vs/base/browser/dom*/,102/*vs/base/browser/htmlContentRenderer*/,27/*vs/base/browser/fastDomNode*/,41/*vs/base/browser/ui/widget*/,16/*vs/platform/instantiation/common/instantiation*/,46/*vs/platform/keybinding/common/keybinding*/,19/*vs/platform/contextkey/common/contextkey*/,21/*vs/editor/common/editorContextKeys*/,13/*vs/editor/common/editorCommonExtensions*/,30/*vs/editor/browser/editorBrowserExtensions*/,181/*vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,15/*vs/base/common/platform*/,51/*vs/base/browser/ui/aria/aria*/,71/*vs/platform/opener/common/opener*/,24/*vs/base/common/uri*/,28/*vs/base/browser/browser*/,400/*vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/]), function (require, exports, nls, lifecycle_1, strings, dom, htmlContentRenderer_1, fastDomNode_1, widget_1, instantiation_1, keybinding_1, contextkey_1, editorContextKeys_1, editorCommonExtensions_1, editorBrowserExtensions_1, toggleTabFocusMode_1, themeService_1, colorRegistry_1, platform, aria_1, opener_1, uri_1, browser) {
    /*---------------------------------------------------------------------------------------------
     *  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 CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE = new contextkey_1.RawContextKey('accessibilityHelpWidgetVisible', false);
    var AccessibilityHelpController = (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_1 = AccessibilityHelpController;
        AccessibilityHelpController.get = function (editor) {
            return editor.getContribution(AccessibilityHelpController_1.ID);
        };
        AccessibilityHelpController.prototype.getId = function () {
            return AccessibilityHelpController_1.ID;
        };
        AccessibilityHelpController.prototype.show = function () {
            this._widget.show();
        };
        AccessibilityHelpController.prototype.hide = function () {
            this._widget.hide();
        };
        AccessibilityHelpController.ID = 'editor.contrib.accessibilityHelpController';
        AccessibilityHelpController = AccessibilityHelpController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, instantiation_1.IInstantiationService)
        ], AccessibilityHelpController);
        return AccessibilityHelpController;
        var AccessibilityHelpController_1;
    }(lifecycle_1.Disposable));
    var nlsNoSelection = nls.localize("noSelection", "No selection");
    var nlsSingleSelectionRange = nls.localize("singleSelectionRange", "Line {0}, Column {1} ({2} selected)");
    var nlsSingleSelection = nls.localize("singleSelection", "Line {0}, Column {1}");
    var nlsMultiSelectionRange = nls.localize("multiSelectionRange", "{0} selections ({1} characters selected)");
    var nlsMultiSelection = nls.localize("multiSelection", "{0} selections");
    function getSelectionLabel(selections, charactersSelected) {
        if (!selections || selections.length === 0) {
            return nlsNoSelection;
        }
        if (selections.length === 1) {
            if (charactersSelected) {
                return strings.format(nlsSingleSelectionRange, selections[0].positionLineNumber, selections[0].positionColumn, charactersSelected);
            }
            return strings.format(nlsSingleSelection, selections[0].positionLineNumber, selections[0].positionColumn);
        }
        if (charactersSelected) {
            return strings.format(nlsMultiSelectionRange, selections.length, charactersSelected);
        }
        if (selections.length > 0) {
            return strings.format(nlsMultiSelection, selections.length);
        }
        return null;
    }
    var AccessibilityHelpWidget = (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(nls.localize("emergencyConfOn", "Now changing the setting `accessibilitySupport` to 'on'."));
                    _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(nls.localize("openingDocs", "Now opening the Editor Accessibility documentation page."));
                    var url = _this._editor.getRawConfiguration().accessibilityHelpUrl;
                    if (typeof url === 'undefined') {
                        url = 'https://go.microsoft.com/fwlink/?linkid=852450';
                    }
                    _this._openerService.open(uri_1.default.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 += nls.localize("readonlyDiffEditor", " in a read-only pane of a diff editor.");
                }
                else {
                    text += nls.localize("editableDiffEditor", " in a pane of a diff editor.");
                }
            }
            else {
                if (opts.readOnly) {
                    text += nls.localize("readonlyEditor", " in a read-only code editor");
                }
                else {
                    text += nls.localize("editableEditor", " in a code editor");
                }
            }
            switch (opts.accessibilitySupport) {
                case 0 /* Unknown */:
                    var turnOnMessage = (platform.isMacintosh
                        ? nls.localize("changeConfigToOnMac", "To configure the editor to be optimized for usage with a Screen Reader press Command+E now.")
                        : nls.localize("changeConfigToOnWinLinux", "To configure the editor to be optimized for usage with a Screen Reader press Control+E now."));
                    text += '\n\n - ' + turnOnMessage;
                    break;
                case 2 /* Enabled */:
                    text += '\n\n - ' + nls.localize("auto_on", "The editor is configured to be optimized for usage with a Screen Reader.");
                    break;
                case 1 /* Disabled */:
                    text += '\n\n - ' + nls.localize("auto_off", "The editor is configured to never be optimized for usage with a Screen Reader, which is not the case at this time.");
                    text += ' ' + turnOnMessage;
                    break;
            }
            var NLS_TAB_FOCUS_MODE_ON = nls.localize("tabFocusModeOnMsg", "Pressing Tab in the current editor will move focus to the next focusable element. Toggle this behavior by pressing {0}.");
            var NLS_TAB_FOCUS_MODE_ON_NO_KB = nls.localize("tabFocusModeOnMsgNoKb", "Pressing Tab in the current editor will move focus to the next focusable element. The command {0} is currently not triggerable by a keybinding.");
            var NLS_TAB_FOCUS_MODE_OFF = nls.localize("tabFocusModeOffMsg", "Pressing Tab in the current editor will insert the tab character. Toggle this behavior by pressing {0}.");
            var NLS_TAB_FOCUS_MODE_OFF_NO_KB = nls.localize("tabFocusModeOffMsgNoKb", "Pressing Tab in the current editor will insert the tab character. The command {0} is currently not triggerable by a keybinding.");
            if (opts.tabFocusMode) {
                text += '\n\n - ' + this._descriptionForCommand(toggleTabFocusMode_1.ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_ON, NLS_TAB_FOCUS_MODE_ON_NO_KB);
            }
            else {
                text += '\n\n - ' + this._descriptionForCommand(toggleTabFocusMode_1.ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_OFF, NLS_TAB_FOCUS_MODE_OFF_NO_KB);
            }
            var openDocMessage = (platform.isMacintosh
                ? nls.localize("openDocMac", "Press Command+H now to open a browser window with more information related to editor accessibility.")
                : nls.localize("openDocWinLinux", "Press Control+H now to open a browser window with more information related to editor accessibility."));
            text += '\n\n - ' + openDocMessage;
            text += '\n\n' + nls.localize("outroMsg", "You can dismiss this tooltip and return to the editor by pressing Escape or Shift+Escape.");
            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 = (function (_super) {
        __extends(ShowAccessibilityHelpAction, _super);
        function ShowAccessibilityHelpAction() {
            return _super.call(this, {
                id: 'editor.action.showAccessibilityHelp',
                label: nls.localize("ShowAccessibilityHelpAction", "Show Accessibility Help"),
                alias: 'Show Accessibility Help',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: (browser.isIE ? 2048 /* CtrlCmd */ | 59 /* F1 */ : 512 /* Alt */ | 59 /* F1 */)
                }
            }) || this;
        }
        ShowAccessibilityHelpAction.prototype.run = function (accessor, editor) {
            var controller = AccessibilityHelpController.get(editor);
            if (controller) {
                controller.show();
            }
        };
        ShowAccessibilityHelpAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], ShowAccessibilityHelpAction);
        return ShowAccessibilityHelpAction;
    }(editorCommonExtensions_1.EditorAction));
    var AccessibilityHelpCommand = editorCommonExtensions_1.EditorCommand.bindToContribution(AccessibilityHelpController.get);
    editorCommonExtensions_1.CommonEditorRegistry.registerEditorCommand(new AccessibilityHelpCommand({
        id: 'closeAccessibilityHelp',
        precondition: CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE,
        handler: function (x) { return x.hide(); },
        kbOpts: {
            weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(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 + "; }");
        }
    });
});




















define(__m[535/*vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([1/*require*/,0/*exports*/,376/*vs/nls!vs/editor/standalone/browser/inspectTokens/inspectTokens*/,3/*vs/base/common/lifecycle*/,9/*vs/base/common/strings*/,13/*vs/editor/common/editorCommonExtensions*/,25/*vs/editor/browser/editorBrowser*/,30/*vs/editor/browser/editorBrowserExtensions*/,88/*vs/editor/common/services/modeService*/,116/*vs/editor/common/model/tokensBinaryEncoding*/,17/*vs/editor/common/modes*/,77/*vs/editor/standalone/common/standaloneThemeService*/,68/*vs/editor/common/modes/nullMode*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,403/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/]), function (require, exports, nls, lifecycle_1, strings_1, editorCommonExtensions_1, editorBrowser_1, editorBrowserExtensions_1, modeService_1, tokensBinaryEncoding_1, modes_1, standaloneThemeService_1, nullMode_1, themeService_1, colorRegistry_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var InspectTokensController = (function (_super) {
        __extends(InspectTokensController, _super);
        function InspectTokensController(editor, standaloneColorService, modeService) {
            var _this = _super.call(this) || this;
            _this._editor = editor;
            _this._standaloneThemeService = standaloneColorService;
            _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_1 = InspectTokensController;
        InspectTokensController.get = function (editor) {
            return editor.getContribution(InspectTokensController_1.ID);
        };
        InspectTokensController.prototype.getId = function () {
            return InspectTokensController_1.ID;
        };
        InspectTokensController.prototype.dispose = function () {
            this.stop();
            _super.prototype.dispose.call(this);
        };
        InspectTokensController.prototype.launch = function () {
            if (this._widget) {
                return;
            }
            if (!this._editor.getModel()) {
                return;
            }
            this._widget = new InspectTokensWidget(this._editor, this._standaloneThemeService, this._modeService);
        };
        InspectTokensController.prototype.stop = function () {
            if (this._widget) {
                this._widget.dispose();
                this._widget = null;
            }
        };
        InspectTokensController.ID = 'editor.contrib.inspectTokens';
        InspectTokensController = InspectTokensController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, standaloneThemeService_1.IStandaloneThemeService),
            __param(2, modeService_1.IModeService)
        ], InspectTokensController);
        return InspectTokensController;
        var InspectTokensController_1;
    }(lifecycle_1.Disposable));
    var InspectTokens = (function (_super) {
        __extends(InspectTokens, _super);
        function InspectTokens() {
            return _super.call(this, {
                id: 'editor.action.inspectTokens',
                label: nls.localize(0, null),
                alias: 'Developer: Inspect Tokens',
                precondition: null
            }) || this;
        }
        InspectTokens.prototype.run = function (accessor, editor) {
            var controller = InspectTokensController.get(editor);
            if (controller) {
                controller.launch();
            }
        };
        InspectTokens = __decorate([
            editorCommonExtensions_1.editorAction
        ], InspectTokens);
        return InspectTokens;
    }(editorCommonExtensions_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 += '&rarr;';
                    break;
                case 32 /* Space */:
                    result += '&middot;';
                    break;
                case 60 /* LessThan */:
                    result += '&lt;';
                    break;
                case 62 /* GreaterThan */:
                    result += '&gt;';
                    break;
                case 38 /* Ampersand */:
                    result += '&amp;';
                    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 = (function (_super) {
        __extends(InspectTokensWidget, _super);
        function InspectTokensWidget(editor, standaloneThemeService, modeService) {
            var _this = _super.call(this) || this;
            // Editor.IContentWidget.allowEditorOverflow
            _this.allowEditorOverflow = true;
            _this._editor = editor;
            _this._standaloneThemeService = standaloneThemeService;
            _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 += "<h2 class=\"tm-token\">" + renderTokenText(tokenText) + "<span class=\"tm-token-length\">(" + tokenText.length + " " + (tokenText.length === 1 ? 'char' : 'chars') + ")</span></h2>";
            result += "<hr class=\"tokens-inspect-separator\" style=\"clear:both\"/>";
            var metadata = this._decodeMetadata(data.tokens2[(token2Index << 1) + 1]);
            result += "<table class=\"tm-metadata-table\"><tbody>";
            result += "<tr><td class=\"tm-metadata-key\">language</td><td class=\"tm-metadata-value\">" + strings_1.escape(metadata.languageIdentifier.language) + "</td>";
            result += "<tr><td class=\"tm-metadata-key\">token type</td><td class=\"tm-metadata-value\">" + this._tokenTypeToString(metadata.tokenType) + "</td>";
            result += "<tr><td class=\"tm-metadata-key\">font style</td><td class=\"tm-metadata-value\">" + this._fontStyleToString(metadata.fontStyle) + "</td>";
            result += "<tr><td class=\"tm-metadata-key\">foreground</td><td class=\"tm-metadata-value\">" + metadata.foreground.toRGBHex() + "</td>";
            result += "<tr><td class=\"tm-metadata-key\">background</td><td class=\"tm-metadata-value\">" + metadata.background.toRGBHex() + "</td>";
            result += "</tbody></table>";
            result += "<hr class=\"tokens-inspect-separator\"/>";
            if (token1Index < data.tokens1.length) {
                result += "<span class=\"tm-token-type\">" + strings_1.escape(data.tokens1[token1Index].type) + "</span>";
            }
            this._domNode.innerHTML = result;
            this._editor.layoutContentWidget(this);
        };
        InspectTokensWidget.prototype._decodeMetadata = function (metadata) {
            var colorMap = modes_1.TokenizationRegistry.getColorMap();
            var languageId = tokensBinaryEncoding_1.TokenMetadata.getLanguageId(metadata);
            var tokenType = tokensBinaryEncoding_1.TokenMetadata.getTokenType(metadata);
            var fontStyle = tokensBinaryEncoding_1.TokenMetadata.getFontStyle(metadata);
            var foreground = tokensBinaryEncoding_1.TokenMetadata.getForeground(metadata);
            var background = tokensBinaryEncoding_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: [editorBrowser_1.ContentWidgetPositionPreference.BELOW, editorBrowser_1.ContentWidgetPositionPreference.ABOVE]
            };
        };
        InspectTokensWidget._ID = 'editor.contrib.inspectTokensWidget';
        return InspectTokensWidget;
    }(lifecycle_1.Disposable));
    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 + "; }");
        }
    });
});




















define(__m[143/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/], __M([1/*require*/,0/*exports*/,30/*vs/editor/browser/editorBrowserExtensions*/,483/*vs/editor/standalone/browser/quickOpen/quickOpenEditorWidget*/,13/*vs/editor/common/editorCommonExtensions*/,14/*vs/platform/theme/common/themeService*/,34/*vs/editor/common/model/textModelWithDecorations*/]), function (require, exports, editorBrowserExtensions_1, quickOpenEditorWidget_1, editorCommonExtensions_1, themeService_1, textModelWithDecorations_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var QuickOpenController = (function () {
        function QuickOpenController(editor, themeService) {
            this.themeService = themeService;
            this.editor = editor;
        }
        QuickOpenController_1 = QuickOpenController;
        QuickOpenController.get = function (editor) {
            return editor.getContribution(QuickOpenController_1.ID);
        };
        QuickOpenController.prototype.getId = function () {
            return QuickOpenController_1.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);
                }
                _this.lastKnownEditorSelection = null;
                _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 _this = this;
            editor.changeDecorations(function (changeAccessor) {
                var oldDecorations = [];
                if (_this.rangeHighlightDecorationId) {
                    oldDecorations.push(_this.rangeHighlightDecorationId);
                    _this.rangeHighlightDecorationId = null;
                }
                var newDecorations = [
                    {
                        range: range,
                        options: QuickOpenController_1._RANGE_HIGHLIGHT_DECORATION
                    }
                ];
                var decorations = changeAccessor.deltaDecorations(oldDecorations, newDecorations);
                _this.rangeHighlightDecorationId = decorations[0];
            });
        };
        QuickOpenController.prototype.clearDecorations = function () {
            var _this = this;
            if (this.rangeHighlightDecorationId) {
                this.editor.changeDecorations(function (changeAccessor) {
                    changeAccessor.deltaDecorations([_this.rangeHighlightDecorationId], []);
                    _this.rangeHighlightDecorationId = null;
                });
            }
        };
        QuickOpenController.ID = 'editor.controller.quickOpenController';
        QuickOpenController._RANGE_HIGHLIGHT_DECORATION = textModelWithDecorations_1.ModelDecorationOptions.register({
            className: 'rangeHighlight',
            isWholeLine: true
        });
        QuickOpenController = QuickOpenController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, themeService_1.IThemeService)
        ], QuickOpenController);
        return QuickOpenController;
        var QuickOpenController_1;
    }());
    exports.QuickOpenController = QuickOpenController;
    /**
     * Base class for providing quick open in the editor.
     */
    var BaseEditorQuickOpenAction = (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;
    }(editorCommonExtensions_1.EditorAction));
    exports.BaseEditorQuickOpenAction = BaseEditorQuickOpenAction;
});

/*---------------------------------------------------------------------------------------------
 *  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/standalone/browser/quickOpen/gotoLine*/], __M([1/*require*/,0/*exports*/,377/*vs/nls!vs/editor/standalone/browser/quickOpen/gotoLine*/,120/*vs/base/parts/quickopen/browser/quickOpenModel*/,100/*vs/base/parts/quickopen/common/quickOpen*/,20/*vs/editor/common/editorCommon*/,21/*vs/editor/common/editorContextKeys*/,143/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/,13/*vs/editor/common/editorCommonExtensions*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,404/*vs/css!vs/editor/standalone/browser/quickOpen/gotoLine*/]), function (require, exports, nls, quickOpenModel_1, quickOpen_1, editorCommon, editorContextKeys_1, editorQuickOpen_1, editorCommonExtensions_1, position_1, range_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var GotoLineEntry = (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); }), 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 (editorCommon.isCommonCodeEditor(this.editor)) {
                model = this.editor.getModel();
            }
            else {
                model = this.editor.getModel().modified;
            }
            var isValid = model.validatePosition(position).equals(position), label;
            if (isValid) {
                if (position.column && position.column > 1) {
                    label = nls.localize(0, null, position.lineNumber, position.column);
                }
                else {
                    label = nls.localize(1, null, position.lineNumber, position.column);
                }
            }
            else if (position.lineNumber < 1 || position.lineNumber > model.getLineCount()) {
                label = nls.localize(2, null, model.getLineCount());
            }
            else {
                label = nls.localize(3, null, model.getLineMaxColumn(position.lineNumber));
            }
            return {
                position: position,
                isValid: isValid,
                label: label
            };
        };
        GotoLineEntry.prototype.getLabel = function () {
            return this._parseResult.label;
        };
        GotoLineEntry.prototype.getAriaLabel = function () {
            return nls.localize(4, null, this._parseResult.label);
        };
        GotoLineEntry.prototype.run = function (mode, context) {
            if (mode === quickOpen_1.Mode.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);
            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);
            // 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 = (function (_super) {
        __extends(GotoLineAction, _super);
        function GotoLineAction() {
            return _super.call(this, nls.localize(5, null), {
                id: 'editor.action.gotoLine',
                label: nls.localize(6, null),
                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 */ }
                }
            }) || 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
                    };
                }
            });
        };
        GotoLineAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], GotoLineAction);
        return GotoLineAction;
    }(editorQuickOpen_1.BaseEditorQuickOpenAction));
    exports.GotoLineAction = GotoLineAction;
});

















define(__m[538/*vs/editor/standalone/browser/quickOpen/quickCommand*/], __M([1/*require*/,0/*exports*/,378/*vs/nls!vs/editor/standalone/browser/quickOpen/quickCommand*/,10/*vs/base/common/errors*/,81/*vs/base/common/filters*/,7/*vs/base/common/winjs.base*/,120/*vs/base/parts/quickopen/browser/quickOpenModel*/,100/*vs/base/parts/quickopen/common/quickOpen*/,46/*vs/platform/keybinding/common/keybinding*/,21/*vs/editor/common/editorContextKeys*/,143/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/,13/*vs/editor/common/editorCommonExtensions*/,28/*vs/base/browser/browser*/]), function (require, exports, nls, errors_1, filters_1, winjs_base_1, quickOpenModel_1, quickOpen_1, keybinding_1, editorContextKeys_1, editorQuickOpen_1, editorCommonExtensions_1, browser) {
    /*---------------------------------------------------------------------------------------------
     *  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 EditorActionCommandEntry = (function (_super) {
        __extends(EditorActionCommandEntry, _super);
        function EditorActionCommandEntry(key, highlights, action, editor) {
            var _this = _super.call(this) || this;
            _this.key = key;
            _this.setHighlights(highlights);
            _this.action = action;
            _this.editor = editor;
            return _this;
        }
        EditorActionCommandEntry.prototype.getLabel = function () {
            return this.action.label;
        };
        EditorActionCommandEntry.prototype.getAriaLabel = function () {
            return nls.localize(0, null, this.getLabel());
        };
        EditorActionCommandEntry.prototype.getGroupLabel = function () {
            return this.key;
        };
        EditorActionCommandEntry.prototype.run = function (mode, context) {
            var _this = this;
            if (mode === quickOpen_1.Mode.OPEN) {
                // Use a timeout to give the quick open widget a chance to close itself first
                winjs_base_1.TPromise.timeout(50).done(function () {
                    // Some actions are enabled only when editor has focus
                    _this.editor.focus();
                    try {
                        var promise = _this.action.run() || winjs_base_1.TPromise.as(null);
                        promise.done(null, errors_1.onUnexpectedError);
                    }
                    catch (error) {
                        errors_1.onUnexpectedError(error);
                    }
                }, errors_1.onUnexpectedError);
                return true;
            }
            return false;
        };
        return EditorActionCommandEntry;
    }(quickOpenModel_1.QuickOpenEntryGroup));
    exports.EditorActionCommandEntry = EditorActionCommandEntry;
    var QuickCommandAction = (function (_super) {
        __extends(QuickCommandAction, _super);
        function QuickCommandAction() {
            return _super.call(this, nls.localize(1, null), {
                id: 'editor.action.quickCommand',
                label: nls.localize(2, null),
                alias: 'Command Palette',
                precondition: null,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: (browser.isIE ? 512 /* Alt */ | 59 /* F1 */ : 59 /* F1 */)
                },
                menuOpts: {}
            }) || 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; i < actions.length; i++) {
                var action = actions[i];
                var keybind = keybindingService.lookupKeybinding(action.id);
                if (action.label) {
                    var highlights = filters_1.matchesFuzzy(searchValue, action.label);
                    if (highlights) {
                        entries.push(new EditorActionCommandEntry(keybind ? keybind.getLabel() : '', highlights, action, editor));
                    }
                }
            }
            // Sort by name
            entries = entries.sort(this._sort);
            return entries;
        };
        QuickCommandAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], QuickCommandAction);
        return QuickCommandAction;
    }(editorQuickOpen_1.BaseEditorQuickOpenAction));
    exports.QuickCommandAction = 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[539/*vs/editor/standalone/browser/quickOpen/quickOutline*/], __M([1/*require*/,0/*exports*/,379/*vs/nls!vs/editor/standalone/browser/quickOpen/quickOutline*/,81/*vs/base/common/filters*/,9/*vs/base/common/strings*/,120/*vs/base/parts/quickopen/browser/quickOpenModel*/,100/*vs/base/parts/quickopen/common/quickOpen*/,21/*vs/editor/common/editorContextKeys*/,17/*vs/editor/common/modes*/,143/*vs/editor/standalone/browser/quickOpen/editorQuickOpen*/,470/*vs/editor/contrib/quickOpen/common/quickOpen*/,13/*vs/editor/common/editorCommonExtensions*/,2/*vs/editor/common/core/range*/,405/*vs/css!vs/editor/standalone/browser/quickOpen/quickOutline*/]), function (require, exports, nls, filters_1, strings, quickOpenModel_1, quickOpen_1, editorContextKeys_1, modes_1, editorQuickOpen_1, quickOpen_2, editorCommonExtensions_1, range_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var SCOPE_PREFIX = ':';
    var SymbolEntry = (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 nls.localize(0, null, 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 === quickOpen_1.Mode.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);
            this.editor.focus();
            return true;
        };
        SymbolEntry.prototype.runPreview = function () {
            // Select Outline Position
            var range = this.toSelection();
            this.editor.revealRangeInCenter(range);
            // 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));
    var QuickOutlineAction = (function (_super) {
        __extends(QuickOutlineAction, _super);
        function QuickOutlineAction() {
            return _super.call(this, nls.localize(1, null), {
                id: 'editor.action.quickOutline',
                label: nls.localize(2, null),
                alias: 'Go to Symbol...',
                precondition: editorContextKeys_1.EditorContextKeys.hasDocumentSymbolProvider,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 45 /* KEY_O */
                },
                menuOpts: {
                    group: 'navigation',
                    order: 3
                }
            }) || this;
        }
        QuickOutlineAction.prototype.run = function (accessor, editor) {
            var _this = this;
            var model = editor.getModel();
            if (!modes_1.DocumentSymbolProviderRegistry.has(model)) {
                return null;
            }
            // Resolve outline
            return quickOpen_2.getDocumentSymbols(model).then(function (result) {
                if (result.entries.length === 0) {
                    return;
                }
                _this._run(editor, result.entries);
            });
        };
        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.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; i < flattened.length; i++) {
                var element = flattened[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(new SymbolEntry(label, modes_1.symbolKindToCssClass(element.kind), description, range_1.Range.lift(element.location.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);
                    }
                    else {
                        typeCounter++;
                    }
                }
                // Update previous result with count
                if (currentResult) {
                    currentResult.setGroupLabel(this.typeToLabel(currentType, typeCounter));
                }
            }
            else if (results.length > 0) {
                results[0].setGroupLabel(nls.localize(3, null, results.length));
            }
            return results;
        };
        QuickOutlineAction.prototype.typeToLabel = function (type, count) {
            switch (type) {
                case 'module': return nls.localize(4, null, count);
                case 'class': return nls.localize(5, null, count);
                case 'interface': return nls.localize(6, null, count);
                case 'method': return nls.localize(7, null, count);
                case 'function': return nls.localize(8, null, count);
                case 'property': return nls.localize(9, null, count);
                case 'variable': return nls.localize(10, null, count);
                case 'var': return nls.localize(11, null, count);
                case 'constructor': return nls.localize(12, null, count);
                case 'call': return nls.localize(13, null, 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;
        };
        QuickOutlineAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], QuickOutlineAction);
        return QuickOutlineAction;
    }(editorQuickOpen_1.BaseEditorQuickOpenAction));
    exports.QuickOutlineAction = 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[540/*vs/editor/standalone/browser/standaloneCodeEditor*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,7/*vs/base/common/winjs.base*/,69/*vs/platform/contextview/browser/contextView*/,16/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/commands/common/commands*/,46/*vs/platform/keybinding/common/keybinding*/,19/*vs/platform/contextkey/common/contextkey*/,42/*vs/editor/common/services/codeEditorService*/,61/*vs/editor/common/services/editorWorkerService*/,129/*vs/editor/standalone/browser/simpleServices*/,141/*vs/editor/browser/codeEditor*/,193/*vs/editor/browser/widget/diffEditorWidget*/,77/*vs/editor/standalone/common/standaloneThemeService*/,149/*vs/editor/common/editorAction*/,85/*vs/platform/actions/common/actions*/,14/*vs/platform/theme/common/themeService*/,51/*vs/base/browser/ui/aria/aria*/,50/*vs/platform/message/common/message*/,380/*vs/nls!vs/editor/standalone/browser/standaloneCodeEditor*/,28/*vs/base/browser/browser*/]), function (require, exports, lifecycle_1, winjs_base_1, contextView_1, instantiation_1, commands_1, keybinding_1, contextkey_1, codeEditorService_1, editorWorkerService_1, simpleServices_1, codeEditor_1, diffEditorWidget_1, standaloneThemeService_1, editorAction_1, actions_1, themeService_1, aria, message_1, nls, browser) {
    '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 = (function (_super) {
        __extends(StandaloneCodeEditor, _super);
        function StandaloneCodeEditor(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService) {
            var _this = this;
            options = options || {};
            options.ariaLabel = options.ariaLabel || nls.localize(0, null);
            options.ariaLabel = options.ariaLabel + ';' + (browser.isIE
                ? nls.localize(1, null)
                : nls.localize(2, null));
            _this = _super.call(this, domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, themeService) || 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.empty;
            }
            // 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 () {
                var r = _descriptor.run(_this);
                return r ? r : winjs_base_1.TPromise.as(void 0);
            };
            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(actions_1.MenuId.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({
                dispose: 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)
        ], StandaloneCodeEditor);
        return StandaloneCodeEditor;
    }(codeEditor_1.CodeEditor));
    exports.StandaloneCodeEditor = StandaloneCodeEditor;
    var StandaloneEditor = (function (_super) {
        __extends(StandaloneEditor, _super);
        function StandaloneEditor(domElement, options, toDispose, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, contextViewService, themeService) {
            var _this = this;
            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) || this;
            _this._contextViewService = contextViewService;
            _this._register(toDispose);
            if (typeof model === 'undefined') {
                model = self.monaco.editor.createModel(options.value || '', options.language || 'text/plain');
                _this._ownsModel = true;
            }
            else {
                _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.destroy = function () {
            this.dispose();
        };
        StandaloneEditor.prototype._attachModel = function (model) {
            _super.prototype._attachModel.call(this, model);
            if (this._view) {
                this._contextViewService.setContainer(this._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)
        ], StandaloneEditor);
        return StandaloneEditor;
    }(StandaloneCodeEditor));
    exports.StandaloneEditor = StandaloneEditor;
    var StandaloneDiffEditor = (function (_super) {
        __extends(StandaloneDiffEditor, _super);
        function StandaloneDiffEditor(domElement, options, toDispose, instantiationService, contextKeyService, keybindingService, contextViewService, editorWorkerService, codeEditorService, themeService, messageService) {
            var _this = this;
            options = options || {};
            if (typeof options.theme === 'string') {
                options.theme = themeService.setTheme(options.theme);
            }
            _this = _super.call(this, domElement, options, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, messageService) || this;
            if (keybindingService instanceof simpleServices_1.StandaloneKeybindingService) {
                _this._standaloneKeybindingService = keybindingService;
            }
            _this._contextViewService = contextViewService;
            _this._register(toDispose);
            _this._contextViewService.setContainer(_this._containerDomElement);
            return _this;
        }
        StandaloneDiffEditor.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
        };
        StandaloneDiffEditor.prototype.destroy = function () {
            this.dispose();
        };
        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, message_1.IMessageService)
        ], 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[541/*vs/editor/standalone/common/themes*/], __M([1/*require*/,0/*exports*/,23/*vs/platform/theme/common/colorRegistry*/,37/*vs/editor/common/view/editorColorRegistry*/]), function (require, exports, colorRegistry_1, editorColorRegistry_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /* -------------------------------- Begin vs theme -------------------------------- */
    exports.vs = {
        base: 'vs',
        inherit: false,
        rules: [
            { token: '', foreground: '000000', background: 'fffffe' },
            { token: 'invalid', foreground: 'cd3131' },
            { token: 'emphasis', fontStyle: 'italic' },
            { token: 'strong', fontStyle: 'bold' },
            { token: 'variable', foreground: '001188' },
            { token: 'variable.predefined', foreground: '4864AA' },
            { token: 'constant', foreground: 'dd0000' },
            { token: 'comment', foreground: '008000' },
            { token: 'number', foreground: '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.jade', foreground: '4F76AC' },
            { token: 'tag.class.jade', 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[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.jade', foreground: '4F76AC' },
            { token: 'tag.class.jade', 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[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.jade', foreground: '4F76AC' },
            { token: 'tag.class.jade', 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)
    };
    var _a, _b, _c;
});
/* -------------------------------- End hc-black theme -------------------------------- */

define(__m[542/*vs/editor/standalone/browser/standaloneThemeServiceImpl*/], __M([1/*require*/,0/*exports*/,202/*vs/editor/common/modes/supports/tokenization*/,541/*vs/editor/standalone/common/themes*/,4/*vs/base/browser/dom*/,17/*vs/editor/common/modes*/,32/*vs/base/common/color*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,44/*vs/platform/registry/common/platform*/,11/*vs/base/common/event*/]), function (require, exports, tokenization_1, themes_1, dom, modes_1, color_1, colorRegistry_1, themeService_1, platform_1, event_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var 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 = (function () {
        function StandaloneTheme(base, name, colors, rules) {
            if (name.length > 0) {
                this.id = base + ' ' + name;
                this.themeName = name;
            }
            else {
                this.id = base;
                this.themeName = base;
            }
            this.base = base;
            this.rules = rules;
            this.colors = {};
            for (var id in colors) {
                this.colors[id] = color_1.Color.fromHex(colors[id]);
            }
            this.defaultColors = {};
        }
        StandaloneTheme.prototype.getColor = function (colorId, useDefault) {
            if (this.colors.hasOwnProperty(colorId)) {
                return this.colors[colorId];
            }
            if (useDefault !== false) {
                return this.getDefault(colorId);
            }
            return null;
        };
        StandaloneTheme.prototype.getDefault = function (colorId) {
            if (this.defaultColors.hasOwnProperty(colorId)) {
                return this.defaultColors[colorId];
            }
            var color = colorRegistry.resolveDefaultColor(colorId, this);
            this.defaultColors[colorId] = color;
            return color;
        };
        StandaloneTheme.prototype.defines = function (colorId) {
            return this.colors.hasOwnProperty(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) {
                    this._tokenTheme = tokenization_1.TokenTheme.createFromRawTokenTheme(this.rules);
                }
                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.colors, themeData.rules);
    }
    var StandaloneThemeServiceImpl = (function () {
        function StandaloneThemeServiceImpl() {
            this._onThemeChange = 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) || isBuiltinTheme(themeName)) {
                throw new Error('Illegal theme name!');
            }
            if (!isBuiltinTheme(themeData.base)) {
                throw new Error('Illegal theme base!');
            }
            var rules = [];
            var colors = {};
            if (themeData.inherit) {
                var baseData = getBuiltinRules(themeData.base);
                rules = rules.concat(baseData.rules);
                for (var id in baseData.colors) {
                    colors[id] = baseData.colors[id];
                }
            }
            rules = rules.concat(themeData.rules);
            for (var id in themeData.colors) {
                colors[id] = themeData.colors[id];
            }
            this._knownThemes.set(themeName, new StandaloneTheme(themeData.base, themeName, colors, rules));
        };
        StandaloneThemeServiceImpl.prototype.getTheme = function () {
            return this._theme;
        };
        StandaloneThemeServiceImpl.prototype.setTheme = function (themeName) {
            var theme;
            if (this._knownThemes.has(themeName)) {
                theme = this._knownThemes.get(themeName);
            }
            else {
                theme = this._knownThemes.get(VS_THEME_NAME);
            }
            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); });
            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;
        };
        return StandaloneThemeServiceImpl;
    }());
    exports.StandaloneThemeServiceImpl = StandaloneThemeServiceImpl;
});

define(__m[144/*vs/platform/workspace/common/workspace*/], __M([1/*require*/,0/*exports*/,24/*vs/base/common/uri*/,16/*vs/platform/instantiation/common/instantiation*/,45/*vs/base/common/paths*/,80/*vs/base/common/map*/]), function (require, exports, uri_1, instantiation_1, paths, map_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IWorkspaceContextService = instantiation_1.createDecorator('contextService');
    var LegacyWorkspace = (function () {
        function LegacyWorkspace(_resource, _ctime) {
            this._resource = _resource;
            this._ctime = _ctime;
            this._name = paths.basename(this._resource.fsPath) || this._resource.fsPath;
        }
        Object.defineProperty(LegacyWorkspace.prototype, "resource", {
            get: function () {
                return this._resource;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(LegacyWorkspace.prototype, "name", {
            get: function () {
                return this._name;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(LegacyWorkspace.prototype, "ctime", {
            get: function () {
                return this._ctime;
            },
            enumerable: true,
            configurable: true
        });
        LegacyWorkspace.prototype.toResource = function (workspaceRelativePath, root) {
            if (typeof workspaceRelativePath === 'string') {
                return uri_1.default.file(paths.join(root ? root.fsPath : this._resource.fsPath, workspaceRelativePath));
            }
            return null;
        };
        return LegacyWorkspace;
    }());
    exports.LegacyWorkspace = LegacyWorkspace;
    var Workspace = (function () {
        function Workspace(id, _name, _roots, _configuration) {
            if (_configuration === void 0) { _configuration = null; }
            this.id = id;
            this._name = _name;
            this._roots = _roots;
            this._configuration = _configuration;
            this._rootsMap = new map_1.TrieMap(map_1.TrieMap.PathSplitter);
            this.updateRootsMap();
        }
        Object.defineProperty(Workspace.prototype, "roots", {
            get: function () {
                return this._roots;
            },
            set: function (roots) {
                this._roots = roots;
                this.updateRootsMap();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Workspace.prototype, "name", {
            get: function () {
                return this._name;
            },
            set: function (name) {
                this._name = name;
            },
            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.getRoot = function (resource) {
            if (!resource) {
                return null;
            }
            return this._rootsMap.findSubstr(resource.fsPath);
        };
        Workspace.prototype.updateRootsMap = function () {
            this._rootsMap = new map_1.TrieMap(map_1.TrieMap.PathSplitter);
            for (var _i = 0, _a = this.roots; _i < _a.length; _i++) {
                var root = _a[_i];
                this._rootsMap.insert(root.fsPath, root);
            }
        };
        Workspace.prototype.toJSON = function () {
            return { id: this.id, roots: this.roots, name: this.name };
        };
        return Workspace;
    }());
    exports.Workspace = Workspace;
});




















define(__m[544/*vs/editor/contrib/referenceSearch/browser/referencesWidget*/], __M([1/*require*/,0/*exports*/,367/*vs/nls!vs/editor/contrib/referenceSearch/browser/referencesWidget*/,10/*vs/base/common/errors*/,174/*vs/base/common/labels*/,11/*vs/base/common/event*/,3/*vs/base/common/lifecycle*/,70/*vs/base/common/network*/,9/*vs/base/common/strings*/,7/*vs/base/common/winjs.base*/,32/*vs/base/common/color*/,52/*vs/base/browser/builder*/,4/*vs/base/browser/dom*/,99/*vs/base/browser/ui/sash/sash*/,204/*vs/base/browser/ui/countBadge/countBadge*/,162/*vs/base/browser/ui/iconLabel/iconLabel*/,128/*vs/base/parts/tree/browser/treeDefaults*/,161/*vs/base/parts/tree/browser/treeImpl*/,16/*vs/platform/instantiation/common/instantiation*/,84/*vs/platform/instantiation/common/serviceCollection*/,144/*vs/platform/workspace/common/workspace*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,175/*vs/editor/common/model/model*/,194/*vs/editor/browser/widget/embeddedCodeEditorWidget*/,92/*vs/editor/contrib/zoneWidget/browser/peekViewWidget*/,125/*vs/editor/contrib/referenceSearch/browser/referencesModel*/,87/*vs/editor/common/services/resolverService*/,23/*vs/platform/theme/common/colorRegistry*/,14/*vs/platform/theme/common/themeService*/,137/*vs/platform/theme/common/styler*/,156/*vs/platform/environment/common/environment*/,34/*vs/editor/common/model/textModelWithDecorations*/,24/*vs/base/common/uri*/,392/*vs/css!vs/editor/contrib/referenceSearch/browser/referencesWidget*/]), function (require, exports, nls, errors_1, labels_1, event_1, lifecycle_1, network_1, strings, winjs_base_1, color_1, builder_1, dom, sash_1, countBadge_1, iconLabel_1, treeDefaults_1, treeImpl_1, instantiation_1, serviceCollection_1, workspace_1, range_1, editorCommon, model_1, embeddedCodeEditorWidget_1, peekViewWidget_1, referencesModel_1, resolverService_1, colorRegistry_1, themeService_1, styler_1, environment_1, textModelWithDecorations_1, uri_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var DecorationsManager = (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;
            this._callOnModelChange.push(this._editor.getModel().onDidChangeDecorations(function (event) { return _this._onDecorationChanged(event); }));
            this._editor.changeDecorations(function (accessor) {
                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 = accessor.deltaDecorations([], newDecorations);
                for (var i = 0; i < decorations.length; i++) {
                    _this._decorations.set(decorations[i], reference.children[newDecorationsActualIndex[i]]);
                }
            });
        };
        DecorationsManager.prototype._onDecorationChanged = function (event) {
            var _this = this;
            var changedDecorations = event.changedDecorations, toRemove = [];
            for (var i = 0, len = changedDecorations.length; i < len; i++) {
                var reference = this._decorations.get(changedDecorations[i]);
                if (!reference) {
                    continue;
                }
                var newRange = this._editor.getModel().getDecorationRange(changedDecorations[i]);
                var ignore = false;
                if (range_1.Range.equalsRange(newRange, reference.range)) {
                    continue;
                }
                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(changedDecorations[i]);
                }
                else {
                    reference.range = newRange;
                }
            }
            this._editor.changeDecorations(function (accessor) {
                for (var i = 0, len = toRemove.length; i < len; i++) {
                    _this._decorations.delete(toRemove[i]);
                }
                accessor.deltaDecorations(toRemove, []);
            });
        };
        DecorationsManager.prototype.removeDecorations = function () {
            var _this = this;
            this._editor.changeDecorations(function (accessor) {
                _this._decorations.forEach(function (value, key) {
                    accessor.removeDecoration(key);
                });
                _this._decorations.clear();
            });
        };
        DecorationsManager.DecorationOptions = textModelWithDecorations_1.ModelDecorationOptions.register({
            stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
            className: 'reference-decoration'
        });
        return DecorationsManager;
    }());
    var DataSource = (function () {
        function DataSource(_textModelResolverService) {
            this._textModelResolverService = _textModelResolverService;
            //
        }
        DataSource.prototype.getId = function (tree, element) {
            if (element instanceof referencesModel_1.ReferencesModel) {
                return 'root';
            }
            else if (element instanceof referencesModel_1.FileReferences) {
                return element.id;
            }
            else if (element instanceof referencesModel_1.OneReference) {
                return element.id;
            }
            return undefined;
        };
        DataSource.prototype.hasChildren = function (tree, 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 (tree, element) {
            if (element instanceof referencesModel_1.ReferencesModel) {
                return winjs_base_1.TPromise.as(element.groups);
            }
            else if (element instanceof referencesModel_1.FileReferences) {
                return element.resolve(this._textModelResolverService).then(function (val) {
                    if (element.failure) {
                        // refresh the element on failure so that
                        // we can update its rendering
                        return tree.refresh(element).then(function () { return val.children; });
                    }
                    return val.children;
                });
            }
            else {
                return winjs_base_1.TPromise.as([]);
            }
        };
        DataSource.prototype.getParent = function (tree, element) {
            var result = null;
            if (element instanceof referencesModel_1.FileReferences) {
                result = element.parent;
            }
            else if (element instanceof referencesModel_1.OneReference) {
                result = element.parent;
            }
            return winjs_base_1.TPromise.as(result);
        };
        DataSource = __decorate([
            __param(0, resolverService_1.ITextModelService)
        ], DataSource);
        return DataSource;
    }());
    var Controller = (function (_super) {
        __extends(Controller, _super);
        function Controller() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Controller.prototype.onTap = function (tree, element, event) {
            if (element instanceof referencesModel_1.FileReferences) {
                event.preventDefault();
                event.stopPropagation();
                return this._expandCollapse(tree, element);
            }
            var result = _super.prototype.onTap.call(this, tree, element, event);
            tree.emit(Controller.Events.FOCUSED, element);
            return result;
        };
        Controller.prototype.onMouseDown = function (tree, element, event) {
            if (event.leftButton) {
                if (element instanceof referencesModel_1.FileReferences) {
                    event.preventDefault();
                    event.stopPropagation();
                    return this._expandCollapse(tree, element);
                }
                var result = _super.prototype.onClick.call(this, tree, element, event);
                if (event.ctrlKey || event.metaKey) {
                    tree.emit(Controller.Events.OPEN_TO_SIDE, element);
                }
                else if (event.detail === 2) {
                    tree.emit(Controller.Events.SELECTED, element);
                }
                else {
                    tree.emit(Controller.Events.FOCUSED, element);
                }
                return result;
            }
            return false;
        };
        Controller.prototype.onClick = function (tree, element, event) {
            if (event.leftButton) {
                return false; // Already handled by onMouseDown
            }
            return _super.prototype.onClick.call(this, tree, element, event);
        };
        Controller.prototype._expandCollapse = function (tree, element) {
            if (tree.isExpanded(element)) {
                tree.collapse(element).done(null, errors_1.onUnexpectedError);
            }
            else {
                tree.expand(element).done(null, errors_1.onUnexpectedError);
            }
            return true;
        };
        Controller.prototype.onEscape = function (tree, event) {
            return false;
        };
        Controller.prototype.onEnter = function (tree, event) {
            var element = tree.getFocus();
            if (element instanceof referencesModel_1.FileReferences) {
                return this._expandCollapse(tree, element);
            }
            var result = _super.prototype.onEnter.call(this, tree, event);
            if (event.ctrlKey || event.metaKey) {
                tree.emit(Controller.Events.OPEN_TO_SIDE, element);
            }
            else {
                tree.emit(Controller.Events.SELECTED, element);
            }
            return result;
        };
        Controller.prototype.onUp = function (tree, event) {
            _super.prototype.onUp.call(this, tree, event);
            this._fakeFocus(tree, event);
            return true;
        };
        Controller.prototype.onPageUp = function (tree, event) {
            _super.prototype.onPageUp.call(this, tree, event);
            this._fakeFocus(tree, event);
            return true;
        };
        Controller.prototype.onLeft = function (tree, event) {
            _super.prototype.onLeft.call(this, tree, event);
            this._fakeFocus(tree, event);
            return true;
        };
        Controller.prototype.onDown = function (tree, event) {
            _super.prototype.onDown.call(this, tree, event);
            this._fakeFocus(tree, event);
            return true;
        };
        Controller.prototype.onPageDown = function (tree, event) {
            _super.prototype.onPageDown.call(this, tree, event);
            this._fakeFocus(tree, event);
            return true;
        };
        Controller.prototype.onRight = function (tree, event) {
            _super.prototype.onRight.call(this, tree, event);
            this._fakeFocus(tree, event);
            return true;
        };
        Controller.prototype._fakeFocus = function (tree, event) {
            // focus next item
            var focus = tree.getFocus();
            tree.setSelection([focus]);
            // send out event
            tree.emit(Controller.Events.FOCUSED, focus);
        };
        Controller.Events = {
            FOCUSED: 'events/custom/focused',
            SELECTED: 'events/custom/selected',
            OPEN_TO_SIDE: 'events/custom/opentoside'
        };
        return Controller;
    }(treeDefaults_1.DefaultController));
    var FileReferencesTemplate = (function () {
        function FileReferencesTemplate(container, _contextService, _environmentService, themeService) {
            this._contextService = _contextService;
            this._environmentService = _environmentService;
            var parent = document.createElement('div');
            dom.addClass(parent, 'reference-file');
            container.appendChild(parent);
            this.file = new iconLabel_1.FileLabel(parent, uri_1.default.parse('no:file'), this._contextService, this._environmentService);
            this.badge = new countBadge_1.CountBadge(parent);
            var styler = styler_1.attachBadgeStyler(this.badge, themeService);
            this.dispose = function () { return styler.dispose(); };
        }
        FileReferencesTemplate.prototype.set = function (element) {
            this.file.setFile(element.uri, this._contextService, this._environmentService);
            var len = element.children.length;
            this.badge.setCount(len);
            if (element.failure) {
                this.badge.setTitleFormat(nls.localize(0, null));
            }
            else if (len > 1) {
                this.badge.setTitleFormat(nls.localize(1, null, len));
            }
            else {
                this.badge.setTitleFormat(nls.localize(2, null, len));
            }
        };
        FileReferencesTemplate = __decorate([
            __param(1, workspace_1.IWorkspaceContextService),
            __param(2, instantiation_1.optional(environment_1.IEnvironmentService)),
            __param(3, themeService_1.IThemeService)
        ], FileReferencesTemplate);
        return FileReferencesTemplate;
    }());
    var OneReferenceTemplate = (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 _a = element.parent.preview.preview(element.range), before = _a.before, inside = _a.inside, after = _a.after;
            this.before.innerHTML = strings.escape(before);
            this.inside.innerHTML = strings.escape(inside);
            this.after.innerHTML = strings.escape(after);
        };
        return OneReferenceTemplate;
    }());
    var Renderer = (function () {
        function Renderer(_contextService, _themeService, _environmentService) {
            this._contextService = _contextService;
            this._themeService = _themeService;
            this._environmentService = _environmentService;
            //
        }
        Renderer.prototype.getHeight = function (tree, element) {
            return 22;
        };
        Renderer.prototype.getTemplateId = function (tree, element) {
            if (element instanceof referencesModel_1.FileReferences) {
                return Renderer._ids.FileReferences;
            }
            else if (element instanceof referencesModel_1.OneReference) {
                return Renderer._ids.OneReference;
            }
            throw element;
        };
        Renderer.prototype.renderTemplate = function (tree, templateId, container) {
            if (templateId === Renderer._ids.FileReferences) {
                return new FileReferencesTemplate(container, this._contextService, this._environmentService, this._themeService);
            }
            else if (templateId === Renderer._ids.OneReference) {
                return new OneReferenceTemplate(container);
            }
            throw templateId;
        };
        Renderer.prototype.renderElement = function (tree, element, templateId, templateData) {
            if (element instanceof referencesModel_1.FileReferences) {
                templateData.set(element);
            }
            else if (element instanceof referencesModel_1.OneReference) {
                templateData.set(element);
            }
            else {
                throw templateId;
            }
        };
        Renderer.prototype.disposeTemplate = function (tree, templateId, templateData) {
            if (templateData instanceof FileReferencesTemplate) {
                templateData.dispose();
            }
        };
        Renderer._ids = {
            FileReferences: 'FileReferences',
            OneReference: 'OneReference'
        };
        Renderer = __decorate([
            __param(0, workspace_1.IWorkspaceContextService),
            __param(1, themeService_1.IThemeService),
            __param(2, instantiation_1.optional(environment_1.IEnvironmentService))
        ], Renderer);
        return Renderer;
    }());
    var AriaProvider = (function () {
        function AriaProvider() {
        }
        AriaProvider.prototype.getAriaLabel = function (tree, element) {
            if (element instanceof referencesModel_1.FileReferences) {
                return element.getAriaMessage();
            }
            else if (element instanceof referencesModel_1.OneReference) {
                return element.getAriaMessage();
            }
            else {
                return undefined;
            }
        };
        return AriaProvider;
    }());
    var VSash = (function () {
        function VSash(container, ratio) {
            var _this = this;
            this._disposables = [];
            this._onDidChangePercentages = new event_1.Emitter();
            this._ratio = ratio;
            this._sash = new sash_1.Sash(container, {
                getVerticalSashLeft: function () { return _this._width * _this._ratio; },
                getVerticalSashHeight: function () { return _this._height; }
            });
            // compute the current widget clientX postion since
            // the sash works with clientX when dragging
            var clientX;
            this._disposables.push(this._sash.addListener('start', function (e) {
                clientX = e.startX - (_this._width * _this.ratio);
            }));
            this._disposables.push(this._sash.addListener('change', function (e) {
                // compute the new position of the sash and from that
                // compute the new ratio that we are using
                var newLeft = e.currentX - clientX;
                if (newLeft > 20 && newLeft + 20 < _this._width) {
                    _this._ratio = newLeft / _this._width;
                    _this._sash.layout();
                    _this._onDidChangePercentages.fire(_this);
                }
            }));
        }
        VSash.prototype.dispose = function () {
            this._sash.dispose();
            this._onDidChangePercentages.dispose();
            lifecycle_1.dispose(this._disposables);
        };
        Object.defineProperty(VSash.prototype, "onDidChangePercentages", {
            get: function () {
                return this._onDidChangePercentages.event;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VSash.prototype, "width", {
            set: function (value) {
                this._width = value;
                this._sash.layout();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VSash.prototype, "height", {
            set: function (value) {
                this._height = value;
                this._sash.layout();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VSash.prototype, "percentages", {
            get: function () {
                var left = 100 * this._ratio;
                var right = 100 - left;
                return [left + "%", right + "%"];
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VSash.prototype, "ratio", {
            get: function () {
                return this._ratio;
            },
            enumerable: true,
            configurable: true
        });
        return VSash;
    }());
    /**
     * ZoneWidget that is shown inside the editor
     */
    var ReferenceWidget = (function (_super) {
        __extends(ReferenceWidget, _super);
        function ReferenceWidget(editor, layoutData, _textModelResolverService, _contextService, _themeService, _instantiationService, _environmentService) {
            var _this = _super.call(this, editor, { showFrame: false, showArrow: true, isResizeable: true, isAccessible: true }) || this;
            _this.layoutData = layoutData;
            _this._textModelResolverService = _textModelResolverService;
            _this._contextService = _contextService;
            _this._themeService = _themeService;
            _this._instantiationService = _instantiationService;
            _this._environmentService = _environmentService;
            _this._disposeOnNewModel = [];
            _this._callOnDispose = [];
            _this._onDidSelectReference = new event_1.Emitter();
            _this._applyTheme(_themeService.getTheme());
            _this._callOnDispose.push(_themeService.onThemeChange(_this._applyTheme.bind(_this)));
            _this._instantiationService = _this._instantiationService.createChild(new serviceCollection_1.ServiceCollection([peekViewWidget_1.IPeekViewService, _this]));
            _this.create();
            return _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)
            });
        };
        ReferenceWidget.prototype.dispose = function () {
            this.setModel(null);
            this._callOnDispose = lifecycle_1.dispose(this._callOnDispose);
            lifecycle_1.dispose(this._preview, this._previewNotAvailableMessage, this._tree, this._sash, this._previewModelReference);
            _super.prototype.dispose.call(this);
        };
        Object.defineProperty(ReferenceWidget.prototype, "onDidSelectReference", {
            get: function () {
                return this._onDidSelectReference.event;
            },
            enumerable: true,
            configurable: true
        });
        ReferenceWidget.prototype.show = function (where) {
            this.editor.revealRangeInCenterIfOutsideViewport(where);
            _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 ? 'side' : 'open',
                    source: 'title'
                });
            }
        };
        ReferenceWidget.prototype._fillBody = function (containerElement) {
            var _this = this;
            var container = builder_1.$(containerElement);
            this.setCssClass('reference-zone-widget');
            // message pane
            container.div({ 'class': 'messages' }, function (div) {
                _this._messageContainer = div.hide();
            });
            // editor
            container.div({ 'class': 'preview inline' }, function (div) {
                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, div.getHTMLElement(), options, _this.editor);
                _this._previewContainer = div.hide();
                _this._previewNotAvailableMessage = model_1.Model.createFromString(nls.localize(3, null));
            });
            // sash
            this._sash = new VSash(containerElement, this.layoutData.ratio || .8);
            this._sash.onDidChangePercentages(function () {
                var _a = _this._sash.percentages, left = _a[0], right = _a[1];
                _this._previewContainer.style({ width: left });
                _this._treeContainer.style({ width: right });
                _this._preview.layout();
                _this._tree.layout();
                _this.layoutData.ratio = _this._sash.ratio;
            });
            // tree
            container.div({ 'class': 'ref-tree inline' }, function (div) {
                var config = {
                    dataSource: _this._instantiationService.createInstance(DataSource),
                    renderer: _this._instantiationService.createInstance(Renderer),
                    controller: new Controller(),
                    accessibilityProvider: new AriaProvider()
                };
                var options = {
                    allowHorizontalScroll: false,
                    twistiePixels: 20,
                    ariaLabel: nls.localize(4, null)
                };
                _this._tree = new treeImpl_1.Tree(div.getHTMLElement(), config, options);
                _this._callOnDispose.push(styler_1.attachListStyler(_this._tree, _this._themeService));
                _this._treeContainer = div.hide();
            });
        };
        ReferenceWidget.prototype._doLayoutBody = function (heightInPixel, widthInPixel) {
            _super.prototype._doLayoutBody.call(this, heightInPixel, widthInPixel);
            var height = heightInPixel + 'px';
            this._sash.height = heightInPixel;
            this._sash.width = widthInPixel;
            // set height/width
            var _a = this._sash.percentages, left = _a[0], right = _a[1];
            this._previewContainer.style({ height: height, width: left });
            this._treeContainer.style({ height: height, width: right });
            // forward
            this._tree.layout(heightInPixel);
            this._preview.layout();
            // store layout data
            this.layoutData = {
                heightInLines: this._viewZone.heightInLines,
                ratio: this._sash.ratio
            };
        };
        ReferenceWidget.prototype._onWidth = function (widthInPixel) {
            this._sash.width = widthInPixel;
            this._preview.layout();
        };
        ReferenceWidget.prototype.setSelection = function (selection) {
            return this._revealReference(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 undefined;
        };
        ReferenceWidget.prototype._onNewModel = function () {
            var _this = this;
            if (this._model.empty) {
                this.setTitle('');
                this._messageContainer.innerHtml(nls.localize(5, null)).show();
                return winjs_base_1.TPromise.as(void 0);
            }
            this._messageContainer.hide();
            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.refresh(reference); }));
            // listen on selection and focus
            this._disposeOnNewModel.push(this._tree.addListener(Controller.Events.FOCUSED, function (element) {
                if (element instanceof referencesModel_1.OneReference) {
                    _this._revealReference(element);
                    _this._onDidSelectReference.fire({ element: element, kind: 'show', source: 'tree' });
                }
            }));
            this._disposeOnNewModel.push(this._tree.addListener(Controller.Events.SELECTED, function (element) {
                if (element instanceof referencesModel_1.OneReference) {
                    _this._onDidSelectReference.fire({ element: element, kind: 'goto', source: 'tree' });
                }
            }));
            this._disposeOnNewModel.push(this._tree.addListener(Controller.Events.OPEN_TO_SIDE, function (element) {
                if (element instanceof referencesModel_1.OneReference) {
                    _this._onDidSelectReference.fire({ element: element, kind: 'side', source: 'tree' });
                }
            }));
            // listen on editor
            this._disposeOnNewModel.push(this._preview.onMouseDown(function (e) {
                if (e.event.detail === 2) {
                    _this._onDidSelectReference.fire({
                        element: _this._getFocusedReference(),
                        kind: (e.event.ctrlKey || e.event.metaKey) ? 'side' : 'open',
                        source: 'editor'
                    });
                }
            }));
            // make sure things are rendered
            dom.addClass(this.container, 'results-loaded');
            this._treeContainer.show();
            this._previewContainer.show();
            this._preview.layout();
            this._tree.layout();
            this.focus();
            // pick input and a reference to begin with
            var input = this._model.groups.length === 1 ? this._model.groups[0] : this._model;
            return this._tree.setInput(input);
        };
        ReferenceWidget.prototype._getFocusedReference = function () {
            var element = this._tree.getFocus();
            if (element instanceof referencesModel_1.OneReference) {
                return element;
            }
            else if (element instanceof referencesModel_1.FileReferences) {
                if (element.children.length > 0) {
                    return element.children[0];
                }
            }
            return undefined;
        };
        ReferenceWidget.prototype._revealReference = function (reference) {
            var _this = this;
            // Update widget header
            if (reference.uri.scheme !== network_1.Schemas.inMemory) {
                this.setTitle(reference.name, labels_1.getPathLabel(reference.directory, this._contextService, this._environmentService));
            }
            else {
                this.setTitle(nls.localize(6, null));
            }
            var promise = this._textModelResolverService.createModelReference(reference.uri);
            return winjs_base_1.TPromise.join([promise, this._tree.reveal(reference)]).then(function (values) {
                var ref = values[0];
                if (!_this._model) {
                    ref.dispose();
                    // disposed
                    return;
                }
                lifecycle_1.dispose(_this._previewModelReference);
                // show in editor
                var model = ref.object;
                if (model) {
                    _this._previewModelReference = ref;
                    _this._preview.setModel(model.textEditorModel);
                    var sel = range_1.Range.lift(reference.range).collapseToStart();
                    _this._preview.setSelection(sel);
                    _this._preview.revealRangeInCenter(sel);
                }
                else {
                    _this._preview.setModel(_this._previewNotAvailableMessage);
                    ref.dispose();
                }
                // show in tree
                _this._tree.setSelection([reference]);
                _this._tree.setFocus(reference);
            }, errors_1.onUnexpectedError);
        };
        return ReferenceWidget;
    }(peekViewWidget_1.PeekViewWidget));
    exports.ReferenceWidget = ReferenceWidget;
    // theming
    exports.peekViewTitleBackground = colorRegistry_1.registerColor('peekViewTitle.background', { dark: '#1E1E1E', light: '#FFFFFF', hc: '#0C141F' }, nls.localize(7, null));
    exports.peekViewTitleForeground = colorRegistry_1.registerColor('peekViewTitleLabel.foreground', { dark: '#FFFFFF', light: '#333333', hc: '#FFFFFF' }, nls.localize(8, null));
    exports.peekViewTitleInfoForeground = colorRegistry_1.registerColor('peekViewTitleDescription.foreground', { dark: '#ccccccb3', light: '#6c6c6cb3', hc: '#FFFFFF99' }, nls.localize(9, null));
    exports.peekViewBorder = colorRegistry_1.registerColor('peekView.border', { dark: '#007acc', light: '#007acc', hc: colorRegistry_1.contrastBorder }, nls.localize(10, null));
    exports.peekViewResultsBackground = colorRegistry_1.registerColor('peekViewResult.background', { dark: '#252526', light: '#F3F3F3', hc: color_1.Color.black }, nls.localize(11, null));
    exports.peekViewResultsMatchForeground = colorRegistry_1.registerColor('peekViewResult.lineForeground', { dark: '#bbbbbb', light: '#646465', hc: color_1.Color.white }, nls.localize(12, null));
    exports.peekViewResultsFileForeground = colorRegistry_1.registerColor('peekViewResult.fileForeground', { dark: color_1.Color.white, light: '#1E1E1E', hc: color_1.Color.white }, nls.localize(13, null));
    exports.peekViewResultsSelectionBackground = colorRegistry_1.registerColor('peekViewResult.selectionBackground', { dark: '#3399ff33', light: '#3399ff33', hc: null }, nls.localize(14, null));
    exports.peekViewResultsSelectionForeground = colorRegistry_1.registerColor('peekViewResult.selectionForeground', { dark: color_1.Color.white, light: '#6C6C6C', hc: color_1.Color.white }, nls.localize(15, null));
    exports.peekViewEditorBackground = colorRegistry_1.registerColor('peekViewEditor.background', { dark: '#001F33', light: '#F2F8FC', hc: color_1.Color.black }, nls.localize(16, null));
    exports.peekViewEditorGutterBackground = colorRegistry_1.registerColor('peekViewEditorGutter.background', { dark: exports.peekViewEditorBackground, light: exports.peekViewEditorBackground, hc: exports.peekViewEditorBackground }, nls.localize(17, null));
    exports.peekViewResultsMatchHighlight = colorRegistry_1.registerColor('peekViewResult.matchHighlightBackground', { dark: '#ea5c004d', light: '#ea5c004d', hc: null }, nls.localize(18, null));
    exports.peekViewEditorMatchHighlight = colorRegistry_1.registerColor('peekViewEditor.matchHighlightBackground', { dark: '#ff8f0099', light: '#f5d802de', hc: null }, nls.localize(19, 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 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; }");
            collector.addRule(".monaco-editor .reference-zone-widget .preview .reference-decoration { border: 2px solid " + 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-tree.focused .monaco-tree-rows > .monaco-tree-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-tree.focused .monaco-tree-rows > .monaco-tree-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 + ";") +
                "}");
        }
    });
});










define(__m[198/*vs/editor/contrib/referenceSearch/browser/referencesController*/], __M([1/*require*/,0/*exports*/,364/*vs/nls!vs/editor/contrib/referenceSearch/browser/referencesController*/,10/*vs/base/common/errors*/,3/*vs/base/common/lifecycle*/,36/*vs/base/common/severity*/,64/*vs/platform/editor/common/editor*/,11/*vs/base/common/event*/,16/*vs/platform/instantiation/common/instantiation*/,19/*vs/platform/contextkey/common/contextkey*/,50/*vs/platform/message/common/message*/,58/*vs/platform/telemetry/common/telemetry*/,62/*vs/platform/configuration/common/configuration*/,144/*vs/platform/workspace/common/workspace*/,76/*vs/platform/storage/common/storage*/,30/*vs/editor/browser/editorBrowserExtensions*/,92/*vs/editor/contrib/zoneWidget/browser/peekViewWidget*/,544/*vs/editor/contrib/referenceSearch/browser/referencesWidget*/,87/*vs/editor/common/services/resolverService*/,14/*vs/platform/theme/common/themeService*/,12/*vs/editor/common/core/position*/,156/*vs/platform/environment/common/environment*/]), function (require, exports, nls, errors_1, lifecycle_1, severity_1, editor_1, event_1, instantiation_1, contextkey_1, message_1, telemetry_1, configuration_1, workspace_1, storage_1, editorBrowserExtensions_1, peekViewWidget_1, referencesWidget_1, resolverService_1, themeService_1, position_1, environment_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ctxReferenceSearchVisible = new contextkey_1.RawContextKey('referenceSearchVisible', false);
    var ReferencesController = (function () {
        function ReferencesController(editor, contextKeyService, _editorService, _textModelResolverService, _telemetryService, _messageService, _instantiationService, _contextService, _storageService, _themeService, _configurationService, _peekViewService, _environmentService) {
            this._editorService = _editorService;
            this._textModelResolverService = _textModelResolverService;
            this._telemetryService = _telemetryService;
            this._messageService = _messageService;
            this._instantiationService = _instantiationService;
            this._contextService = _contextService;
            this._storageService = _storageService;
            this._themeService = _themeService;
            this._configurationService = _configurationService;
            this._peekViewService = _peekViewService;
            this._environmentService = _environmentService;
            this._requestIdPool = 0;
            this._disposables = [];
            this._ignoreModelChangeEvent = false;
            this._editor = editor;
            this._referenceSearchVisible = exports.ctxReferenceSearchVisible.bindTo(contextKeyService);
        }
        ReferencesController_1 = ReferencesController;
        ReferencesController.get = function (editor) {
            return editor.getContribution(ReferencesController_1.ID);
        };
        ReferencesController.prototype.getId = function () {
            return ReferencesController_1.ID;
        };
        ReferencesController.prototype.dispose = function () {
            if (this._widget) {
                this._widget.dispose();
                this._widget = null;
            }
            this._editor = 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 null;
            }
            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 = JSON.parse(this._storageService.get(storageKey, undefined, '{}'));
            this._widget = new referencesWidget_1.ReferenceWidget(this._editor, data, this._textModelResolverService, this._contextService, this._themeService, this._instantiationService, this._environmentService);
            this._widget.setTitle(nls.localize(0, null));
            this._widget.show(range);
            this._disposables.push(this._widget.onDidClose(function () {
                modelPromise.cancel();
                _this._storageService.store(storageKey, JSON.stringify(_this._widget.layoutData));
                _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.lookup('editor.stablePeek').value) {
                            // when stable peek is configured we don't close
                            // the peek window on selecting the editor
                            break;
                        }
                    case 'side':
                        _this._openReference(element, kind === 'side');
                        break;
                    case 'goto':
                        if (options.onGoto) {
                            options.onGoto(element);
                        }
                        else {
                            _this._gotoReference(element);
                        }
                        break;
                }
            }));
            var requestId = ++this._requestIdPool;
            var promise = 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;
                // measure time it stays open
                var startTime = Date.now();
                _this._disposables.push({
                    dispose: function () {
                        _this._telemetryService.publicLog('zoneWidgetShown', {
                            mode: 'reference search',
                            elapsedTime: Date.now() - startTime
                        });
                    }
                });
                // show widget
                return _this._widget.setModel(_this._model).then(function () {
                    // 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._messageService.show(severity_1.default.Error, error);
            });
            var onDone = event_1.stopwatch(event_1.fromPromise(promise));
            var mode = this._editor.getModel().getLanguageIdentifier().language;
            onDone(function (duration) { return _this._telemetryService.publicLog('findReferences', {
                duration: duration,
                mode: mode
            }); });
        };
        ReferencesController.prototype.closeWidget = function () {
            if (this._widget) {
                this._widget.dispose();
                this._widget = null;
            }
            this._referenceSearchVisible.reset();
            this._disposables = lifecycle_1.dispose(this._disposables);
            if (this._model) {
                this._model.dispose();
                this._model = null;
            }
            this._editor.focus();
            this._requestIdPool += 1; // Cancel pending requests
        };
        ReferencesController.prototype._gotoReference = function (ref) {
            var _this = this;
            this._widget.hide();
            this._ignoreModelChangeEvent = true;
            var uri = ref.uri, range = ref.range;
            this._editorService.openEditor({
                resource: uri,
                options: { selection: range }
            }).done(function (openedEditor) {
                _this._ignoreModelChangeEvent = false;
                if (!openedEditor || openedEditor.getControl() !== _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;
                }
                _this._widget.show(range);
                _this._widget.focus();
            }, function (err) {
                _this._ignoreModelChangeEvent = false;
                errors_1.onUnexpectedError(err);
            });
        };
        ReferencesController.prototype._openReference = function (ref, sideBySide) {
            var uri = ref.uri, range = ref.range;
            this._editorService.openEditor({
                resource: uri,
                options: { selection: range }
            }, sideBySide);
            // clear stage
            if (!sideBySide) {
                this.closeWidget();
            }
        };
        ReferencesController.ID = 'editor.contrib.referencesController';
        ReferencesController = ReferencesController_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, contextkey_1.IContextKeyService),
            __param(2, editor_1.IEditorService),
            __param(3, resolverService_1.ITextModelService),
            __param(4, telemetry_1.ITelemetryService),
            __param(5, message_1.IMessageService),
            __param(6, instantiation_1.IInstantiationService),
            __param(7, workspace_1.IWorkspaceContextService),
            __param(8, storage_1.IStorageService),
            __param(9, themeService_1.IThemeService),
            __param(10, configuration_1.IConfigurationService),
            __param(11, instantiation_1.optional(peekViewWidget_1.IPeekViewService)),
            __param(12, instantiation_1.optional(environment_1.IEnvironmentService))
        ], ReferencesController);
        return ReferencesController;
        var ReferencesController_1;
    }());
    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[199/*vs/editor/contrib/goToDeclaration/browser/goToDeclarationCommands*/], __M([1/*require*/,0/*exports*/,351/*vs/nls!vs/editor/contrib/goToDeclaration/browser/goToDeclarationCommands*/,51/*vs/base/browser/ui/aria/aria*/,40/*vs/base/common/keyCodes*/,15/*vs/base/common/platform*/,36/*vs/base/common/severity*/,7/*vs/base/common/winjs.base*/,64/*vs/platform/editor/common/editor*/,50/*vs/platform/message/common/message*/,2/*vs/editor/common/core/range*/,13/*vs/editor/common/editorCommonExtensions*/,177/*vs/editor/contrib/goToDeclaration/browser/goToDeclaration*/,198/*vs/editor/contrib/referenceSearch/browser/referencesController*/,125/*vs/editor/contrib/referenceSearch/browser/referencesModel*/,92/*vs/editor/contrib/zoneWidget/browser/peekViewWidget*/,19/*vs/platform/contextkey/common/contextkey*/,521/*vs/editor/contrib/goToDeclaration/browser/messageController*/,21/*vs/editor/common/editorContextKeys*/]), function (require, exports, nls, aria_1, keyCodes_1, platform, severity_1, winjs_base_1, editor_1, message_1, range_1, editorCommonExtensions_1, goToDeclaration_1, referencesController_1, referencesModel_1, peekViewWidget_1, contextkey_1, messageController_1, editorContextKeys_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var DefinitionActionConfig = (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 = (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;
            var messageService = accessor.get(message_1.IMessageService);
            var editorService = accessor.get(editor_1.IEditorService);
            var model = editor.getModel();
            var pos = editor.getPosition();
            return this._getDeclarationsAtPosition(model, pos).then(function (references) {
                if (model.isDisposed() || editor.getModel() !== model) {
                    // new model, no more model
                    return;
                }
                // * remove falsy references
                // * find reference at the current pos
                var idxOfCurrent = -1;
                var result = [];
                for (var i = 0; i < references.length; i++) {
                    var reference = references[i];
                    if (!reference || !reference.range) {
                        continue;
                    }
                    var uri = reference.uri, range = reference.range;
                    var newLen = result.push({
                        uri: uri,
                        range: range
                    });
                    if (_this._configuration.filterCurrent
                        && uri.toString() === model.uri.toString()
                        && range_1.Range.containsPosition(range, pos)
                        && idxOfCurrent === -1) {
                        idxOfCurrent = newLen - 1;
                    }
                }
                if (result.length === 0) {
                    // no result -> show message
                    if (_this._configuration.showMessage) {
                        var info = model.getWordAtPosition(pos);
                        messageController_1.MessageController.get(editor).showMessage(_this._getNoResultFoundMessage(info), pos);
                    }
                }
                else if (result.length === 1 && idxOfCurrent !== -1) {
                    // only the position at which we are -> adjust selection
                    var current = result[0];
                    _this._openReference(editorService, current, false);
                }
                else {
                    // handle multile results
                    _this._onResult(editorService, editor, new referencesModel_1.ReferencesModel(result));
                }
            }, function (err) {
                // report an error
                messageService.show(severity_1.default.Error, err);
                return false;
            });
        };
        DefinitionAction.prototype._getDeclarationsAtPosition = function (model, position) {
            return goToDeclaration_1.getDefinitionsAtPosition(model, position);
        };
        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) {
            var _this = this;
            var msg = model.getAriaMessage();
            aria_1.alert(msg);
            if (this._configuration.openInPeek) {
                this._openInPeek(editorService, editor, model);
            }
            else {
                var next = model.nearestReference(editor.getModel().uri, editor.getPosition());
                this._openReference(editorService, next, this._configuration.openToSide).then(function (editor) {
                    if (editor && model.references.length > 1) {
                        _this._openInPeek(editorService, editor, model);
                    }
                    else {
                        model.dispose();
                    }
                });
            }
        };
        DefinitionAction.prototype._openReference = function (editorService, reference, sideBySide) {
            var uri = reference.uri, range = reference.range;
            return editorService.openEditor({
                resource: uri,
                options: {
                    selection: range_1.Range.collapseToStart(range),
                    revealIfVisible: !sideBySide
                }
            }, sideBySide).then(function (editor) {
                return editor && editor.getControl();
            });
        };
        DefinitionAction.prototype._openInPeek = function (editorService, target, model) {
            var _this = this;
            var controller = referencesController_1.ReferencesController.get(target);
            if (controller) {
                controller.toggleWidget(target.getSelection(), winjs_base_1.TPromise.as(model), {
                    getMetaTitle: function (model) {
                        return _this._getMetaTitle(model);
                    },
                    onGoto: function (reference) {
                        controller.closeWidget();
                        return _this._openReference(editorService, reference, false);
                    }
                });
            }
            else {
                model.dispose();
            }
        };
        return DefinitionAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.DefinitionAction = DefinitionAction;
    var goToDeclarationKb = platform.isWeb
        ? 2048 /* CtrlCmd */ | 70 /* F12 */
        : 70 /* F12 */;
    var GoToDefinitionAction = (function (_super) {
        __extends(GoToDefinitionAction, _super);
        function GoToDefinitionAction() {
            return _super.call(this, new DefinitionActionConfig(), {
                id: GoToDefinitionAction_1.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.textFocus,
                    primary: goToDeclarationKb
                },
                menuOpts: {
                    group: 'navigation',
                    order: 1.1
                }
            }) || this;
        }
        GoToDefinitionAction_1 = GoToDefinitionAction;
        GoToDefinitionAction.ID = 'editor.action.goToDeclaration';
        GoToDefinitionAction = GoToDefinitionAction_1 = __decorate([
            editorCommonExtensions_1.editorAction
        ], GoToDefinitionAction);
        return GoToDefinitionAction;
        var GoToDefinitionAction_1;
    }(DefinitionAction));
    exports.GoToDefinitionAction = GoToDefinitionAction;
    var OpenDefinitionToSideAction = (function (_super) {
        __extends(OpenDefinitionToSideAction, _super);
        function OpenDefinitionToSideAction() {
            return _super.call(this, new DefinitionActionConfig(true), {
                id: OpenDefinitionToSideAction_1.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.textFocus,
                    primary: keyCodes_1.KeyChord(2048 /* CtrlCmd */ | 41 /* KEY_K */, goToDeclarationKb)
                }
            }) || this;
        }
        OpenDefinitionToSideAction_1 = OpenDefinitionToSideAction;
        OpenDefinitionToSideAction.ID = 'editor.action.openDeclarationToTheSide';
        OpenDefinitionToSideAction = OpenDefinitionToSideAction_1 = __decorate([
            editorCommonExtensions_1.editorAction
        ], OpenDefinitionToSideAction);
        return OpenDefinitionToSideAction;
        var OpenDefinitionToSideAction_1;
    }(DefinitionAction));
    exports.OpenDefinitionToSideAction = OpenDefinitionToSideAction;
    var PeekDefinitionAction = (function (_super) {
        __extends(PeekDefinitionAction, _super);
        function PeekDefinitionAction() {
            return _super.call(this, new DefinitionActionConfig(void 0, true, false), {
                id: 'editor.action.previewDeclaration',
                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.textFocus,
                    primary: 512 /* Alt */ | 70 /* F12 */,
                    linux: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 68 /* F10 */ }
                },
                menuOpts: {
                    group: 'navigation',
                    order: 1.2
                }
            }) || this;
        }
        PeekDefinitionAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], PeekDefinitionAction);
        return PeekDefinitionAction;
    }(DefinitionAction));
    exports.PeekDefinitionAction = PeekDefinitionAction;
    var ImplementationAction = (function (_super) {
        __extends(ImplementationAction, _super);
        function ImplementationAction() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ImplementationAction.prototype._getDeclarationsAtPosition = function (model, position) {
            return goToDeclaration_1.getImplementationsAtPosition(model, position);
        };
        ImplementationAction.prototype._getNoResultFoundMessage = function (info) {
            return info && info.word
                ? nls.localize(6, null, info.word)
                : nls.localize(7, null);
        };
        ImplementationAction.prototype._getMetaTitle = function (model) {
            return model.references.length > 1 && nls.localize(8, null, model.references.length);
        };
        return ImplementationAction;
    }(DefinitionAction));
    exports.ImplementationAction = ImplementationAction;
    var GoToImplementationAction = (function (_super) {
        __extends(GoToImplementationAction, _super);
        function GoToImplementationAction() {
            return _super.call(this, new DefinitionActionConfig(), {
                id: GoToImplementationAction_1.ID,
                label: nls.localize(9, null),
                alias: 'Go to Implementation',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasImplementationProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 70 /* F12 */
                }
            }) || this;
        }
        GoToImplementationAction_1 = GoToImplementationAction;
        GoToImplementationAction.ID = 'editor.action.goToImplementation';
        GoToImplementationAction = GoToImplementationAction_1 = __decorate([
            editorCommonExtensions_1.editorAction
        ], GoToImplementationAction);
        return GoToImplementationAction;
        var GoToImplementationAction_1;
    }(ImplementationAction));
    exports.GoToImplementationAction = GoToImplementationAction;
    var PeekImplementationAction = (function (_super) {
        __extends(PeekImplementationAction, _super);
        function PeekImplementationAction() {
            return _super.call(this, new DefinitionActionConfig(false, true, false), {
                id: PeekImplementationAction_1.ID,
                label: nls.localize(10, null),
                alias: 'Peek Implementation',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasImplementationProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 70 /* F12 */
                }
            }) || this;
        }
        PeekImplementationAction_1 = PeekImplementationAction;
        PeekImplementationAction.ID = 'editor.action.peekImplementation';
        PeekImplementationAction = PeekImplementationAction_1 = __decorate([
            editorCommonExtensions_1.editorAction
        ], PeekImplementationAction);
        return PeekImplementationAction;
        var PeekImplementationAction_1;
    }(ImplementationAction));
    exports.PeekImplementationAction = PeekImplementationAction;
    var TypeDefinitionAction = (function (_super) {
        __extends(TypeDefinitionAction, _super);
        function TypeDefinitionAction() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TypeDefinitionAction.prototype._getDeclarationsAtPosition = function (model, position) {
            return goToDeclaration_1.getTypeDefinitionsAtPosition(model, position);
        };
        TypeDefinitionAction.prototype._getNoResultFoundMessage = function (info) {
            return info && info.word
                ? nls.localize(11, null, info.word)
                : nls.localize(12, null);
        };
        TypeDefinitionAction.prototype._getMetaTitle = function (model) {
            return model.references.length > 1 && nls.localize(13, null, model.references.length);
        };
        return TypeDefinitionAction;
    }(DefinitionAction));
    exports.TypeDefinitionAction = TypeDefinitionAction;
    var GoToTypeDefintionAction = (function (_super) {
        __extends(GoToTypeDefintionAction, _super);
        function GoToTypeDefintionAction() {
            return _super.call(this, new DefinitionActionConfig(), {
                id: GoToTypeDefintionAction_1.ID,
                label: nls.localize(14, 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.textFocus,
                    primary: 0
                },
                menuOpts: {
                    group: 'navigation',
                    order: 1.4
                }
            }) || this;
        }
        GoToTypeDefintionAction_1 = GoToTypeDefintionAction;
        GoToTypeDefintionAction.ID = 'editor.action.goToTypeDefinition';
        GoToTypeDefintionAction = GoToTypeDefintionAction_1 = __decorate([
            editorCommonExtensions_1.editorAction
        ], GoToTypeDefintionAction);
        return GoToTypeDefintionAction;
        var GoToTypeDefintionAction_1;
    }(TypeDefinitionAction));
    exports.GoToTypeDefintionAction = GoToTypeDefintionAction;
    var PeekTypeDefinitionAction = (function (_super) {
        __extends(PeekTypeDefinitionAction, _super);
        function PeekTypeDefinitionAction() {
            return _super.call(this, new DefinitionActionConfig(false, true, false), {
                id: PeekTypeDefinitionAction_1.ID,
                label: nls.localize(15, null),
                alias: 'Peek Type Definition',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasTypeDefinitionProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textFocus,
                    primary: 0
                }
            }) || this;
        }
        PeekTypeDefinitionAction_1 = PeekTypeDefinitionAction;
        PeekTypeDefinitionAction.ID = 'editor.action.peekTypeDefinition';
        PeekTypeDefinitionAction = PeekTypeDefinitionAction_1 = __decorate([
            editorCommonExtensions_1.editorAction
        ], PeekTypeDefinitionAction);
        return PeekTypeDefinitionAction;
        var PeekTypeDefinitionAction_1;
    }(TypeDefinitionAction));
    exports.PeekTypeDefinitionAction = PeekTypeDefinitionAction;
});

/*---------------------------------------------------------------------------------------------
 *  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/goToDeclaration/browser/goToDeclarationMouse*/], __M([1/*require*/,0/*exports*/,352/*vs/nls!vs/editor/contrib/goToDeclaration/browser/goToDeclarationMouse*/,18/*vs/base/common/async*/,10/*vs/base/common/errors*/,7/*vs/base/common/winjs.base*/,88/*vs/editor/common/services/modeService*/,2/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,25/*vs/editor/browser/editorBrowser*/,30/*vs/editor/browser/editorBrowserExtensions*/,177/*vs/editor/contrib/goToDeclaration/browser/goToDeclaration*/,3/*vs/base/common/lifecycle*/,87/*vs/editor/common/services/resolverService*/,14/*vs/platform/theme/common/themeService*/,23/*vs/platform/theme/common/colorRegistry*/,131/*vs/editor/common/core/editorState*/,199/*vs/editor/contrib/goToDeclaration/browser/goToDeclarationCommands*/,192/*vs/editor/contrib/goToDeclaration/browser/clickLinkGesture*/,171/*vs/css!vs/editor/contrib/goToDeclaration/browser/goToDeclarationMouse*/]), function (require, exports, nls, async_1, errors_1, winjs_base_1, modeService_1, range_1, modes_1, editorBrowser_1, editorBrowserExtensions_1, goToDeclaration_1, lifecycle_1, resolverService_1, themeService_1, colorRegistry_1, editorState_1, goToDeclarationCommands_1, clickLinkGesture_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var GotoDefinitionWithMouseEditorContribution = (function () {
        function GotoDefinitionWithMouseEditorContribution(editor, textModelResolverService, modeService) {
            var _this = this;
            this.textModelResolverService = textModelResolverService;
            this.modeService = modeService;
            this.toUnhook = [];
            this.decorations = [];
            this.editor = editor;
            this.throttler = new async_1.Throttler();
            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, keyboardEvent);
            }));
            this.toUnhook.push(linkGesture.onExecute(function (mouseEvent) {
                if (_this.isEnabled(mouseEvent)) {
                    _this.gotoDefinition(mouseEvent.target, mouseEvent.hasSideBySideModifier).done(function () {
                        _this.removeDecorations();
                    }, function (error) {
                        _this.removeDecorations();
                        errors_1.onUnexpectedError(error);
                    });
                }
            }));
            this.toUnhook.push(linkGesture.onCancel(function () {
                _this.removeDecorations();
                _this.currentWordUnderMouse = null;
            }));
        }
        GotoDefinitionWithMouseEditorContribution_1 = GotoDefinitionWithMouseEditorContribution;
        GotoDefinitionWithMouseEditorContribution.prototype.startFindDefinition = function (mouseEvent, withKey) {
            var _this = this;
            if (!this.isEnabled(mouseEvent, withKey)) {
                this.currentWordUnderMouse = null;
                this.removeDecorations();
                return;
            }
            // Find word at mouse position
            var position = mouseEvent.target.position;
            var word = position ? this.editor.getModel().getWordAtPosition(position) : null;
            if (!word) {
                this.currentWordUnderMouse = null;
                this.removeDecorations();
                return;
            }
            // 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 */);
            this.throttler.queue(function () {
                return state.validate(_this.editor)
                    ? _this.findDefinition(mouseEvent.target)
                    : winjs_base_1.TPromise.as(null);
            }).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), nls.localize(0, null, results.length));
                }
                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 (textEditorModel.getLineMaxColumn(startLineNumber) === 0) {
                            ref.dispose();
                            return;
                        }
                        var startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
                        var maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionWithMouseEditorContribution_1.MAX_SOURCE_PREVIEW_LINES);
                        var endLineNumber = startLineNumber + 1;
                        var minIndent = startIndent;
                        for (; endLineNumber < maxLineNumber; endLineNumber++) {
                            var endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
                            minIndent = Math.min(minIndent, endIndent);
                            if (startIndent === endIndent) {
                                break;
                            }
                        }
                        var previewRange = new range_1.Range(startLineNumber, 1, endLineNumber + 1, 1);
                        var value = textEditorModel.getValueInRange(previewRange).replace(new RegExp("^\\s{" + (minIndent - 1) + "}", 'gm'), '').trim();
                        _this.addDecoration(new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn), {
                            language: _this.modeService.getModeIdByFilenameOrFirstLine(textEditorModel.uri.fsPath),
                            value: value
                        });
                        ref.dispose();
                    });
                }
            }).done(undefined, errors_1.onUnexpectedError);
        };
        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.getModel() &&
                mouseEvent.isNoneOrSingleMouseDown &&
                mouseEvent.target.type === editorBrowser_1.MouseTargetType.CONTENT_TEXT &&
                (mouseEvent.hasTriggerModifier || (withKey && withKey.keyCodeIsTriggerKey)) &&
                modes_1.DefinitionProviderRegistry.has(this.editor.getModel());
        };
        GotoDefinitionWithMouseEditorContribution.prototype.findDefinition = function (target) {
            var model = this.editor.getModel();
            if (!model) {
                return winjs_base_1.TPromise.as(null);
            }
            return goToDeclaration_1.getDefinitionsAtPosition(this.editor.getModel(), target.position);
        };
        GotoDefinitionWithMouseEditorContribution.prototype.gotoDefinition = function (target, sideBySide) {
            var _this = this;
            this.editor.setPosition(target.position);
            var action = new goToDeclarationCommands_1.DefinitionAction(new goToDeclarationCommands_1.DefinitionActionConfig(sideBySide, false, true, false), { alias: undefined, label: undefined, id: undefined, precondition: undefined });
            return this.editor.invokeWithinContext(function (accessor) { return action.run(accessor, _this.editor); });
        };
        GotoDefinitionWithMouseEditorContribution.prototype.getId = function () {
            return GotoDefinitionWithMouseEditorContribution_1.ID;
        };
        GotoDefinitionWithMouseEditorContribution.prototype.dispose = function () {
            this.toUnhook = lifecycle_1.dispose(this.toUnhook);
        };
        GotoDefinitionWithMouseEditorContribution.ID = 'editor.contrib.gotodefinitionwithmouse';
        GotoDefinitionWithMouseEditorContribution.MAX_SOURCE_PREVIEW_LINES = 8;
        GotoDefinitionWithMouseEditorContribution = GotoDefinitionWithMouseEditorContribution_1 = __decorate([
            editorBrowserExtensions_1.editorContribution,
            __param(1, resolverService_1.ITextModelService),
            __param(2, modeService_1.IModeService)
        ], GotoDefinitionWithMouseEditorContribution);
        return GotoDefinitionWithMouseEditorContribution;
        var GotoDefinitionWithMouseEditorContribution_1;
    }());
    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; }");
        }
    });
});




















define(__m[548/*vs/editor/contrib/referenceSearch/browser/referenceSearch*/], __M([1/*require*/,0/*exports*/,363/*vs/nls!vs/editor/contrib/referenceSearch/browser/referenceSearch*/,24/*vs/base/common/uri*/,7/*vs/base/common/winjs.base*/,64/*vs/platform/editor/common/editor*/,16/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/commands/common/commands*/,19/*vs/platform/contextkey/common/contextkey*/,105/*vs/platform/keybinding/common/keybindingsRegistry*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,20/*vs/editor/common/editorCommon*/,13/*vs/editor/common/editorCommonExtensions*/,17/*vs/editor/common/modes*/,92/*vs/editor/contrib/zoneWidget/browser/peekViewWidget*/,198/*vs/editor/contrib/referenceSearch/browser/referencesController*/,125/*vs/editor/contrib/referenceSearch/browser/referencesModel*/,18/*vs/base/common/async*/,10/*vs/base/common/errors*/,21/*vs/editor/common/editorContextKeys*/]), function (require, exports, nls, uri_1, winjs_base_1, editor_1, instantiation_1, commands_1, contextkey_1, keybindingsRegistry_1, position_1, range_1, editorCommon, editorCommonExtensions_1, modes_1, peekViewWidget_1, referencesController_1, referencesModel_1, async_1, errors_1, editorContextKeys_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var defaultReferenceSearchOptions = {
        getMetaTitle: function (model) {
            return model.references.length > 1 && nls.localize(0, null, model.references.length);
        }
    };
    var ReferenceController = (function () {
        function ReferenceController(editor, contextKeyService, peekViewService) {
            if (peekViewService) {
                peekViewWidget_1.PeekContext.inPeekEditor.bindTo(contextKeyService);
            }
        }
        ReferenceController_1 = ReferenceController;
        ReferenceController.prototype.dispose = function () {
        };
        ReferenceController.prototype.getId = function () {
            return ReferenceController_1.ID;
        };
        ReferenceController.ID = 'editor.contrib.referenceController';
        ReferenceController = ReferenceController_1 = __decorate([
            editorCommonExtensions_1.commonEditorContribution,
            __param(1, contextkey_1.IContextKeyService),
            __param(2, instantiation_1.optional(peekViewWidget_1.IPeekViewService))
        ], ReferenceController);
        return ReferenceController;
        var ReferenceController_1;
    }());
    exports.ReferenceController = ReferenceController;
    var ReferenceAction = (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.textFocus,
                    primary: 1024 /* Shift */ | 70 /* F12 */
                },
                menuOpts: {
                    group: 'navigation',
                    order: 1.5
                }
            }) || this;
        }
        ReferenceAction.prototype.run = function (accessor, editor) {
            var controller = referencesController_1.ReferencesController.get(editor);
            if (!controller) {
                return;
            }
            var range = editor.getSelection();
            var model = editor.getModel();
            var references = provideReferences(model, range.getStartPosition()).then(function (references) { return new referencesModel_1.ReferencesModel(references); });
            controller.toggleWidget(range, references, defaultReferenceSearchOptions);
        };
        ReferenceAction = __decorate([
            editorCommonExtensions_1.editorAction
        ], ReferenceAction);
        return ReferenceAction;
    }(editorCommonExtensions_1.EditorAction));
    exports.ReferenceAction = ReferenceAction;
    var findReferencesCommand = function (accessor, resource, position) {
        if (!(resource instanceof uri_1.default)) {
            throw new Error('illegal argument, uri');
        }
        if (!position) {
            throw new Error('illegal argument, position');
        }
        return accessor.get(editor_1.IEditorService).openEditor({ resource: resource }).then(function (editor) {
            var control = editor.getControl();
            if (!editorCommon.isCommonCodeEditor(control)) {
                return undefined;
            }
            var controller = referencesController_1.ReferencesController.get(control);
            if (!controller) {
                return undefined;
            }
            var references = provideReferences(control.getModel(), position_1.Position.lift(position)).then(function (references) { return new referencesModel_1.ReferencesModel(references); });
            var range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column);
            return winjs_base_1.TPromise.as(controller.toggleWidget(range, references, defaultReferenceSearchOptions));
        });
    };
    var showReferencesCommand = function (accessor, resource, position, references) {
        if (!(resource instanceof uri_1.default)) {
            throw new Error('illegal argument, uri expected');
        }
        return accessor.get(editor_1.IEditorService).openEditor({ resource: resource }).then(function (editor) {
            var control = editor.getControl();
            if (!editorCommon.isCommonCodeEditor(control)) {
                return undefined;
            }
            var controller = referencesController_1.ReferencesController.get(control);
            if (!controller) {
                return undefined;
            }
            return winjs_base_1.TPromise.as(controller.toggleWidget(new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column), winjs_base_1.TPromise.as(new referencesModel_1.ReferencesModel(references)), defaultReferenceSearchOptions)).then(function () { return true; });
        });
    };
    // register commands
    commands_1.CommandsRegistry.registerCommand('editor.action.findReferences', findReferencesCommand);
    commands_1.CommandsRegistry.registerCommand('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.default },
                { 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) {
        var outerEditor = peekViewWidget_1.getOuterEditor(accessor);
        if (!outerEditor) {
            return;
        }
        var controller = referencesController_1.ReferencesController.get(outerEditor);
        if (!controller) {
            return;
        }
        controller.closeWidget();
    }
    keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: 'closeReferenceSearch',
        weight: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(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: editorCommonExtensions_1.CommonEditorRegistry.commandWeight(-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
    });
    function provideReferences(model, position) {
        // collect references from all providers
        var promises = modes_1.ReferenceProviderRegistry.ordered(model).map(function (provider) {
            return async_1.asWinJsPromise(function (token) {
                return 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 winjs_base_1.TPromise.join(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;
    editorCommonExtensions_1.CommonEditorRegistry.registerDefaultLanguageCommand('_executeReferenceProvider', provideReferences);
});

/*---------------------------------------------------------------------------------------------
 *  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/editor.all*/], __M([1/*require*/,0/*exports*/,134/*vs/editor/common/controller/coreCommands*/,191/*vs/editor/browser/widget/codeEditorWidget*/,193/*vs/editor/browser/widget/diffEditorWidget*/,164/*vs/editor/browser/widget/diffNavigator*/,514/*vs/editor/contrib/bracketMatching/common/bracketMatching*/,313/*vs/css!vs/editor/contrib/bracketMatching/browser/bracketMatching*/,450/*vs/editor/contrib/caretOperations/common/caretOperations*/,451/*vs/editor/contrib/caretOperations/common/transpose*/,452/*vs/editor/contrib/clipboard/browser/clipboard*/,516/*vs/editor/contrib/codelens/browser/codelensController*/,454/*vs/editor/contrib/comment/common/comment*/,455/*vs/editor/contrib/contextmenu/browser/contextmenu*/,456/*vs/editor/contrib/cursorUndo/browser/cursorUndo*/,431/*vs/editor/contrib/dnd/browser/dnd*/,520/*vs/editor/contrib/find/browser/find*/,458/*vs/editor/contrib/folding/browser/folding*/,460/*vs/editor/contrib/format/browser/formatActions*/,199/*vs/editor/contrib/goToDeclaration/browser/goToDeclarationCommands*/,547/*vs/editor/contrib/goToDeclaration/browser/goToDeclarationMouse*/,522/*vs/editor/contrib/gotoError/browser/gotoError*/,523/*vs/editor/contrib/hover/browser/hover*/,524/*vs/editor/contrib/inPlaceReplace/common/inPlaceReplace*/,464/*vs/editor/contrib/linesOperations/common/linesOperations*/,525/*vs/editor/contrib/links/browser/links*/,465/*vs/editor/contrib/multicursor/common/multicursor*/,527/*vs/editor/contrib/parameterHints/browser/parameterHints*/,469/*vs/editor/contrib/quickFix/browser/quickFixCommands*/,548/*vs/editor/contrib/referenceSearch/browser/referenceSearch*/,529/*vs/editor/contrib/rename/browser/rename*/,471/*vs/editor/contrib/smartSelect/common/smartSelect*/,180/*vs/editor/contrib/snippet/browser/snippetController2*/,531/*vs/editor/contrib/suggest/browser/suggestController*/,181/*vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode*/,532/*vs/editor/contrib/wordHighlighter/common/wordHighlighter*/,476/*vs/editor/contrib/wordOperations/common/wordOperations*/,517/*vs/editor/contrib/colorPicker/browser/colorPicker*/]), function (require, exports) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
});











define(__m[200/*vs/editor/standalone/browser/standaloneServices*/], __M([1/*require*/,0/*exports*/,3/*vs/base/common/lifecycle*/,62/*vs/platform/configuration/common/configuration*/,387/*vs/platform/contextview/browser/contextMenuService*/,69/*vs/platform/contextview/browser/contextView*/,478/*vs/platform/contextview/browser/contextViewService*/,16/*vs/platform/instantiation/common/instantiation*/,413/*vs/platform/instantiation/common/instantiationService*/,84/*vs/platform/instantiation/common/serviceCollection*/,31/*vs/platform/commands/common/commands*/,46/*vs/platform/keybinding/common/keybinding*/,19/*vs/platform/contextkey/common/contextkey*/,421/*vs/platform/markers/common/markerService*/,103/*vs/platform/markers/common/markers*/,50/*vs/platform/message/common/message*/,163/*vs/platform/progress/common/progress*/,76/*vs/platform/storage/common/storage*/,58/*vs/platform/telemetry/common/telemetry*/,144/*vs/platform/workspace/common/workspace*/,42/*vs/editor/common/services/codeEditorService*/,61/*vs/editor/common/services/editorWorkerService*/,147/*vs/editor/common/services/editorWorkerServiceImpl*/,146/*vs/editor/common/services/resourceConfiguration*/,88/*vs/editor/common/services/modeService*/,437/*vs/editor/common/services/modeServiceImpl*/,56/*vs/editor/common/services/modelService*/,430/*vs/editor/common/services/modelServiceImpl*/,485/*vs/editor/browser/services/codeEditorServiceImpl*/,129/*vs/editor/standalone/browser/simpleServices*/,417/*vs/platform/contextkey/browser/contextKeyService*/,85/*vs/platform/actions/common/actions*/,77/*vs/editor/standalone/common/standaloneThemeService*/,542/*vs/editor/standalone/browser/standaloneThemeServiceImpl*/]), function (require, exports, lifecycle_1, configuration_1, contextMenuService_1, contextView_1, contextViewService_1, instantiation_1, instantiationService_1, serviceCollection_1, commands_1, keybinding_1, contextkey_1, markerService_1, markers_1, message_1, progress_1, storage_1, telemetry_1, workspace_1, codeEditorService_1, editorWorkerService_1, editorWorkerServiceImpl_1, resourceConfiguration_1, modeService_1, modeServiceImpl_1, modelService_1, modelServiceImpl_1, codeEditorServiceImpl_1, simpleServices_1, contextKeyService_1, actions_1, standaloneThemeService_1, standaloneThemeServiceImpl_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    var StaticServices;
    (function (StaticServices) {
        var _serviceCollection = new serviceCollection_1.ServiceCollection();
        var LazyStaticService = (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.contextService = define(workspace_1.IWorkspaceContextService, function () { return new simpleServices_1.SimpleWorkspaceContextService(); });
        StaticServices.telemetryService = define(telemetry_1.ITelemetryService, function () { return new simpleServices_1.StandaloneTelemetryService(); });
        StaticServices.messageService = define(message_1.IMessageService, function () { return new simpleServices_1.SimpleMessageService(); });
        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.markerService.get(o), StaticServices.configurationService.get(o)); });
        StaticServices.editorWorkerService = define(editorWorkerService_1.IEditorWorkerService, function (o) { return new editorWorkerServiceImpl_1.EditorWorkerServiceImpl(StaticServices.modelService.get(o), StaticServices.resourceConfigurationService.get(o), StaticServices.modeService.get(o)); });
        StaticServices.standaloneThemeService = define(standaloneThemeService_1.IStandaloneThemeService, function () { return new standaloneThemeServiceImpl_1.StandaloneThemeServiceImpl(); });
        StaticServices.codeEditorService = define(codeEditorService_1.ICodeEditorService, function (o) { return new codeEditorServiceImpl_1.CodeEditorServiceImpl(StaticServices.standaloneThemeService.get(o)); });
        StaticServices.progressService = define(progress_1.IProgressService, function () { return new simpleServices_1.SimpleProgressService(); });
        StaticServices.storageService = define(storage_1.IStorageService, function () { return storage_1.NullStorageService; });
    })(StaticServices = exports.StaticServices || (exports.StaticServices = {}));
    var DynamicStandaloneServices = (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 messageService = _this.get(message_1.IMessageService);
            var telemetryService = _this.get(telemetry_1.ITelemetryService);
            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)); });
            var commandService = ensure(commands_1.ICommandService, function () { return new simpleServices_1.StandaloneCommandService(_this._instantiationService); });
            ensure(keybinding_1.IKeybindingService, function () { return _this._register(new simpleServices_1.StandaloneKeybindingService(contextKeyService, commandService, messageService, domElement)); });
            var contextViewService = ensure(contextView_1.IContextViewService, function () { return _this._register(new contextViewService_1.ContextViewService(domElement, telemetryService, messageService)); });
            ensure(contextView_1.IContextMenuService, function () { return _this._register(new contextMenuService_1.ContextMenuService(domElement, telemetryService, messageService, contextViewService)); });
            ensure(actions_1.IMenuService, function () { return new simpleServices_1.SimpleMenuService(commandService); });
            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;
});

define(__m[422/*vs/editor/standalone/browser/standaloneEditor*/], __M([1/*require*/,0/*exports*/,20/*vs/editor/common/editorCommon*/,25/*vs/editor/browser/editorBrowser*/,540/*vs/editor/standalone/browser/standaloneCodeEditor*/,48/*vs/base/common/scrollable*/,200/*vs/editor/standalone/browser/standaloneServices*/,480/*vs/platform/opener/browser/openerService*/,71/*vs/platform/opener/common/opener*/,273/*vs/editor/standalone/browser/colorizer*/,129/*vs/editor/standalone/browser/simpleServices*/,17/*vs/editor/common/modes*/,397/*vs/editor/common/services/webWorker*/,164/*vs/editor/browser/widget/diffNavigator*/,64/*vs/platform/editor/common/editor*/,31/*vs/platform/commands/common/commands*/,69/*vs/platform/contextview/browser/contextView*/,16/*vs/platform/instantiation/common/instantiation*/,46/*vs/platform/keybinding/common/keybinding*/,19/*vs/platform/contextkey/common/contextkey*/,42/*vs/editor/common/services/codeEditorService*/,61/*vs/editor/common/services/editorWorkerService*/,87/*vs/editor/common/services/resolverService*/,68/*vs/editor/common/modes/nullMode*/,77/*vs/editor/standalone/common/standaloneThemeService*/,132/*vs/editor/common/config/fontInfo*/,49/*vs/editor/common/config/editorOptions*/,54/*vs/editor/common/controller/cursorEvents*/,50/*vs/platform/message/common/message*/,408/*vs/css!vs/editor/standalone/browser/standalone-tokens*/]), function (require, exports, editorCommon, editorBrowser_1, standaloneCodeEditor_1, scrollable_1, standaloneServices_1, openerService_1, opener_1, colorizer_1, simpleServices_1, modes, webWorker_1, diffNavigator_1, editor_1, commands_1, contextView_1, instantiation_1, keybinding_1, contextkey_1, codeEditorService_1, editorWorkerService_1, resolverService_1, nullMode_1, standaloneThemeService_1, fontInfo_1, editorOptions, cursorEvents_1, message_1) {
    /*---------------------------------------------------------------------------------------------
     *  Copyright (c) Microsoft Corporation. All rights reserved.
     *  Licensed under the MIT License. See License.txt in the project root for license information.
     *--------------------------------------------------------------------------------------------*/
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * @internal
     */
    function setupServices(overrides) {
        return standaloneServices_1.StaticServices.init(overrides);
    }
    exports.setupServices = setupServices;
    function withAllStandaloneServices(domElement, override, callback) {
        var services = new standaloneServices_1.DynamicStandaloneServices(domElement, override);
        // The editorService is a lovely beast. It needs to point back to the code editor instance...
        var simpleEditorService = null;
        if (!services.has(editor_1.IEditorService)) {
            simpleEditorService = new simpleServices_1.SimpleEditorService();
            services.set(editor_1.IEditorService, simpleEditorService);
        }
        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(editor_1.IEditorService), services.get(commands_1.ICommandService)));
        }
        var result = callback(services);
        if (simpleEditorService) {
            simpleEditorService.setEditor(result);
        }
        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));
        });
    }
    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(message_1.IMessageService));
        });
    }
    exports.createDiffEditor = createDiffEditor;
    function createDiffNavigator(diffEditor, opts) {
        return new diffNavigator_1.DiffNavigator(diffEditor, opts);
    }
    exports.createDiffNavigator = createDiffNavigator;
    function doCreateModel(value, mode, uri) {
        return standaloneServices_1.StaticServices.modelService.get().createModel(value, mode, 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().getOrCreateModeByFilenameOrFirstLine(path, firstLine), uri);
        }
        return doCreateModel(value, standaloneServices_1.StaticServices.modeService.get().getOrCreateMode(language), uri);
    }
    exports.createModel = createModel;
    /**
     * Change the language for a model.
     */
    function setModelLanguage(model, language) {
        standaloneServices_1.StaticServices.modelService.get().setMode(model, standaloneServices_1.StaticServices.modeService.get().getOrCreateMode(language));
    }
    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 ant/or resource
     * @returns {IMarkerData[]} list of markers
     * @param filter
     */
    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(languageId) {
        var tokenizationSupport = modes.TokenizationRegistry.get(languageId);
        if (tokenizationSupport) {
            return tokenizationSupport;
        }
        return {
            getInitialState: function () { return nullMode_1.NULL_STATE; },
            tokenize: function (line, state, deltaOffset) { return nullMode_1.nullTokenize(languageId, line, state, deltaOffset); },
            tokenize2: undefined,
        };
    }
    /**
     * 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.getOrCreateMode(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.
     */
    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;
    /**
     * @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,
            // enums
            ScrollbarVisibility: scrollable_1.ScrollbarVisibility,
            WrappingIndent: editorOptions.WrappingIndent,
            OverviewRulerLane: editorCommon.OverviewRulerLane,
            EndOfLinePreference: editorCommon.EndOfLinePreference,
            DefaultEndOfLine: editorCommon.DefaultEndOfLine,
            EndOfLineSequence: editorCommon.EndOfLineSequence,
            TrackedRangeStickiness: editorCommon.TrackedRangeStickiness,
            CursorChangeReason: cursorEvents_1.CursorChangeReason,
            MouseTargetType: editorBrowser_1.MouseTargetType,
            TextEditorCursorStyle: editorOptions.TextEditorCursorStyle,
            TextEditorCursorBlinkingStyle: editorOptions.TextEditorCursorBlinkingStyle,
            ContentWidgetPositionPreference: editorBrowser_1.ContentWidgetPositionPreference,
            OverlayWidgetPositionPreference: editorBrowser_1.OverlayWidgetPositionPreference,
            RenderMinimap: editorOptions.RenderMinimap,
            // classes
            InternalEditorOptions: editorOptions.InternalEditorOptions,
            BareFontInfo: fontInfo_1.BareFontInfo,
            FontInfo: fontInfo_1.FontInfo,
            TextModelResolvedOptions: editorCommon.TextModelResolvedOptions,
            FindMatch: editorCommon.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[227/*vs/editor/standalone/browser/standaloneLanguages*/], __M([1/*require*/,0/*exports*/,7/*vs/base/common/winjs.base*/,126/*vs/editor/common/modes/modesRegistry*/,200/*vs/editor/standalone/browser/standaloneServices*/,17/*vs/editor/common/modes*/,60/*vs/editor/common/modes/languageConfiguration*/,12/*vs/editor/common/core/position*/,2/*vs/editor/common/core/range*/,18/*vs/base/common/async*/,275/*vs/editor/standalone/common/monarch/monarchCompile*/,276/*vs/editor/standalone/common/monarch/monarchLexer*/,43/*vs/editor/common/modes/languageConfigurationRegistry*/,97/*vs/editor/common/core/token*/]), function (require, exports, winjs_base_1, modesRegistry_1, standaloneServices_1, modes, languageConfiguration_1, position_1, range_1, async_1, monarchCompile_1, monarchLexer_1, languageConfigurationRegistry_1, token_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;
    /**
     * 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 TokenizationSupport2Adapter = (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;
    /**
     * 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 adapter = new TokenizationSupport2Adapter(standaloneServices_1.StaticServices.standaloneThemeService.get(), languageIdentifier, provider);
        return modes.TokenizationRegistry.register(languageId, adapter);
    }
    exports.setTokensProvider = setTokensProvider;
    /**
     * Set the tokens provider for a language (monarch implementation).
     */
    function setMonarchTokensProvider(languageId, languageDef) {
        var lexer = monarchCompile_1.compile(languageId, languageDef);
        var adapter = monarchLexer_1.createTokenizationSupport(standaloneServices_1.StaticServices.modeService.get(), standaloneServices_1.StaticServices.standaloneThemeService.get(), languageId, lexer);
        return modes.TokenizationRegistry.register(languageId, adapter);
    }
    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. paremeter 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 async_1.toThenable(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, 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 }, 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) {
        var adapter = new SuggestAdapter(provider);
        return modes.SuggestRegistry.register(languageId, {
            triggerCharacters: provider.triggerCharacters,
            provideCompletionItems: function (model, position, token) {
                return adapter.provideCompletionItems(model, position, token);
            },
            resolveCompletionItem: function (model, position, suggestion, token) {
                return adapter.resolveCompletionItem(model, position, suggestion, token);
            }
        });
    }
    exports.registerCompletionItemProvider = registerCompletionItemProvider;
    /**
     * Completion item kinds.
     */
    var CompletionItemKind;
    (function (CompletionItemKind) {
        CompletionItemKind[CompletionItemKind["Text"] = 0] = "Text";
        CompletionItemKind[CompletionItemKind["Method"] = 1] = "Method";
        CompletionItemKind[CompletionItemKind["Function"] = 2] = "Function";
        CompletionItemKind[CompletionItemKind["Constructor"] = 3] = "Constructor";
        CompletionItemKind[CompletionItemKind["Field"] = 4] = "Field";
        CompletionItemKind[CompletionItemKind["Variable"] = 5] = "Variable";
        CompletionItemKind[CompletionItemKind["Class"] = 6] = "Class";
        CompletionItemKind[CompletionItemKind["Interface"] = 7] = "Interface";
        CompletionItemKind[CompletionItemKind["Module"] = 8] = "Module";
        CompletionItemKind[CompletionItemKind["Property"] = 9] = "Property";
        CompletionItemKind[CompletionItemKind["Unit"] = 10] = "Unit";
        CompletionItemKind[CompletionItemKind["Value"] = 11] = "Value";
        CompletionItemKind[CompletionItemKind["Enum"] = 12] = "Enum";
        CompletionItemKind[CompletionItemKind["Keyword"] = 13] = "Keyword";
        CompletionItemKind[CompletionItemKind["Snippet"] = 14] = "Snippet";
        CompletionItemKind[CompletionItemKind["Color"] = 15] = "Color";
        CompletionItemKind[CompletionItemKind["File"] = 16] = "File";
        CompletionItemKind[CompletionItemKind["Reference"] = 17] = "Reference";
        CompletionItemKind[CompletionItemKind["Folder"] = 18] = "Folder";
    })(CompletionItemKind = exports.CompletionItemKind || (exports.CompletionItemKind = {}));
    function convertKind(kind) {
        switch (kind) {
            case CompletionItemKind.Method: return 'method';
            case CompletionItemKind.Function: return 'function';
            case CompletionItemKind.Constructor: return 'constructor';
            case CompletionItemKind.Field: return 'field';
            case CompletionItemKind.Variable: return 'variable';
            case CompletionItemKind.Class: return 'class';
            case CompletionItemKind.Interface: return 'interface';
            case CompletionItemKind.Module: return 'module';
            case CompletionItemKind.Property: return 'property';
            case CompletionItemKind.Unit: return 'unit';
            case CompletionItemKind.Value: return 'value';
            case CompletionItemKind.Enum: return 'enum';
            case CompletionItemKind.Keyword: return 'keyword';
            case CompletionItemKind.Snippet: return 'snippet';
            case CompletionItemKind.Text: return 'text';
            case CompletionItemKind.Color: return 'color';
            case CompletionItemKind.File: return 'file';
            case CompletionItemKind.Reference: return 'reference';
            case CompletionItemKind.Folder: return 'folder';
        }
        return 'property';
    }
    var SuggestAdapter = (function () {
        function SuggestAdapter(provider) {
            this._provider = provider;
        }
        SuggestAdapter.from = function (item, position, wordStartPos) {
            var suggestion = {
                _actual: item,
                label: item.label,
                insertText: item.label,
                type: convertKind(item.kind),
                detail: item.detail,
                documentation: item.documentation,
                sortText: item.sortText,
                filterText: item.filterText,
                snippetType: 'internal'
            };
            var editRange = item.textEdit ? item.textEdit.range : item.range;
            if (editRange) {
                var isSingleLine = (editRange.startLineNumber === editRange.endLineNumber);
                // invalid text edit
                if (!isSingleLine || editRange.startLineNumber !== position.lineNumber) {
                    console.warn('INVALID range, must be single line and on the same line');
                    return null;
                }
                // insert the text of the edit and create a dedicated
                // suggestion-container with overwrite[Before|After]
                suggestion.overwriteBefore = position.column - editRange.startColumn;
                suggestion.overwriteAfter = editRange.endColumn - position.column;
            }
            else {
                suggestion.overwriteBefore = position.column - wordStartPos.column;
                suggestion.overwriteAfter = 0;
            }
            if (item.textEdit) {
                suggestion.insertText = item.textEdit.text;
            }
            else if (typeof item.insertText === 'object' && typeof item.insertText.value === 'string') {
                suggestion.insertText = item.insertText.value;
                suggestion.snippetType = 'textmate';
            }
            else if (typeof item.insertText === 'string') {
                suggestion.insertText = item.insertText;
            }
            return suggestion;
        };
        SuggestAdapter.prototype.provideCompletionItems = function (model, position, token) {
            return async_1.toThenable(this._provider.provideCompletionItems(model, position, token)).then(function (value) {
                var result = {
                    suggestions: []
                };
                // default text edit start
                var wordStartPos = position;
                var word = model.getWordUntilPosition(position);
                if (word) {
                    wordStartPos = new position_1.Position(wordStartPos.lineNumber, word.startColumn);
                }
                var list;
                if (Array.isArray(value)) {
                    list = {
                        items: value,
                        isIncomplete: false
                    };
                }
                else if (typeof value === 'object' && Array.isArray(value.items)) {
                    list = value;
                    result.incomplete = list.isIncomplete;
                }
                else if (!value) {
                    // undefined and null are valid results
                    return undefined;
                }
                else {
                    // warn about everything else
                    console.warn('INVALID result from completion provider. expected CompletionItem-array or CompletionList but got:', value);
                }
                for (var i = 0; i < list.items.length; i++) {
                    var item = list.items[i];
                    var suggestion = SuggestAdapter.from(item, position, wordStartPos);
                    if (suggestion) {
                        result.suggestions.push(suggestion);
                    }
                }
                return result;
            });
        };
        SuggestAdapter.prototype.resolveCompletionItem = function (model, position, suggestion, token) {
            if (typeof this._provider.resolveCompletionItem !== 'function') {
                return winjs_base_1.TPromise.as(suggestion);
            }
            var item = suggestion._actual;
            if (!item) {
                return winjs_base_1.TPromise.as(suggestion);
            }
            return async_1.toThenable(this._provider.resolveCompletionItem(item, token)).then(function (resolvedItem) {
                var wordStartPos = position;
                var word = model.getWordUntilPosition(position);
                if (word) {
                    wordStartPos = new position_1.Position(wordStartPos.lineNumber, word.startColumn);
                }
                return SuggestAdapter.from(resolvedItem, position, wordStartPos);
            });
        };
        return SuggestAdapter;
    }());
    /**
     * @internal
     */
    function createMonacoLanguagesAPI() {
        return {
            register: register,
            getLanguages: getLanguages,
            onLanguage: onLanguage,
            // 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,
            // enums
            DocumentHighlightKind: modes.DocumentHighlightKind,
            CompletionItemKind: CompletionItemKind,
            SymbolKind: modes.SymbolKind,
            IndentAction: languageConfiguration_1.IndentAction,
        };
    }
    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[553/*vs/editor/editor.main*/], __M([1/*require*/,0/*exports*/,152/*vs/editor/common/standalone/standaloneBase*/,422/*vs/editor/standalone/browser/standaloneEditor*/,227/*vs/editor/standalone/browser/standaloneLanguages*/,49/*vs/editor/common/config/editorOptions*/,549/*vs/editor/editor.all*/,534/*vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/,535/*vs/editor/standalone/browser/inspectTokens/inspectTokens*/,432/*vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/,539/*vs/editor/standalone/browser/quickOpen/quickOutline*/,537/*vs/editor/standalone/browser/quickOpen/gotoLine*/,538/*vs/editor/standalone/browser/quickOpen/quickCommand*/,477/*vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast*/]), function (require, exports, standaloneBase_1, standaloneEditor_1, standaloneLanguages_1, editorOptions_1) {
    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    // Set defaults for standalone editor
    editorOptions_1.EDITOR_DEFAULTS.wrappingIndent = editorOptions_1.WrappingIndent.None;
    editorOptions_1.EDITOR_DEFAULTS.contribInfo.folding = false;
    editorOptions_1.EDITOR_DEFAULTS.viewInfo.glyphMargin = false;
    editorOptions_1.EDITOR_DEFAULTS.autoIndent = false;
    var base = standaloneBase_1.createMonacoBaseAPI();
    for (var prop in base) {
        if (base.hasOwnProperty(prop)) {
            exports[prop] = base[prop];
        }
    }
    exports.editor = standaloneEditor_1.createMonacoEditorAPI();
    exports.languages = standaloneLanguages_1.createMonacoLanguagesAPI();
    var global = self;
    global.monaco = exports;
    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'
            ]
        });
    }
});

}).call(this);

/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * monaco-typescript version: 2.3.0(fd172013f77fa599e03a1c17b79aab62637569fa)
 * Released under the MIT license
 * https://github.com/Microsoft/monaco-typescript/blob/master/LICENSE.md
 *-----------------------------------------------------------------------------*/
define("vs/language/typescript/src/monaco.contribution",["require","exports","vs/editor/edcore.main"],function(e,t){"use strict";function n(){return new monaco.Promise(function(e,t){r(function(n){n.getTypeScriptWorker().then(e,t)})})}function i(){return new monaco.Promise(function(e,t){r(function(n){n.getJavaScriptWorker().then(e,t)})})}function o(){return{ModuleKind:c,JsxEmit:p,NewLineKind:u,ScriptTarget:g,ModuleResolutionKind:d,typescriptDefaults:S,javascriptDefaults:m,getTypeScriptWorker:n,getJavaScriptWorker:i}}function r(t){e(["vs/language/typescript/src/mode"],t)}Object.defineProperty(t,"__esModule",{value:!0});var a=monaco.Emitter,s=function(){function e(e,t){this._onDidChange=new a,this._extraLibs=Object.create(null),this._workerMaxIdleTime=12e4,this.setCompilerOptions(e),this.setDiagnosticsOptions(t)}return Object.defineProperty(e.prototype,"onDidChange",{get:function(){return this._onDidChange.event},enumerable:!0,configurable:!0}),e.prototype.getExtraLibs=function(){var e=Object.create(null);for(var t in this._extraLibs)e[t]=this._extraLibs[t];return Object.freeze(e)},e.prototype.addExtraLib=function(e,t){var n=this;if("undefined"==typeof t&&(t="ts:extralib-"+Date.now()),this._extraLibs[t])throw new Error(t+" already a extra lib");return this._extraLibs[t]=e,this._onDidChange.fire(this),{dispose:function(){delete n._extraLibs[t]&&n._onDidChange.fire(n)}}},e.prototype.getCompilerOptions=function(){return this._compilerOptions},e.prototype.setCompilerOptions=function(e){this._compilerOptions=e||Object.create(null),this._onDidChange.fire(this)},e.prototype.getDiagnosticsOptions=function(){return this._diagnosticsOptions},e.prototype.setDiagnosticsOptions=function(e){this._diagnosticsOptions=e||Object.create(null),this._onDidChange.fire(this)},e.prototype.setMaximunWorkerIdleTime=function(e){this._workerMaxIdleTime=e},e.prototype.getWorkerMaxIdleTime=function(){return this._workerMaxIdleTime},e.prototype.setEagerModelSync=function(e){this._eagerModelSync=e},e.prototype.getEagerModelSync=function(){return this._eagerModelSync},e}();t.LanguageServiceDefaultsImpl=s;var c;!function(e){e[e.None=0]="None",e[e.CommonJS=1]="CommonJS",e[e.AMD=2]="AMD",e[e.UMD=3]="UMD",e[e.System=4]="System",e[e.ES2015=5]="ES2015"}(c||(c={}));var p;!function(e){e[e.None=0]="None",e[e.Preserve=1]="Preserve",e[e.React=2]="React"}(p||(p={}));var u;!function(e){e[e.CarriageReturnLineFeed=0]="CarriageReturnLineFeed",e[e.LineFeed=1]="LineFeed"}(u||(u={}));var l;!function(e){e[e.Unknown=0]="Unknown",e[e.JS=1]="JS",e[e.JSX=2]="JSX",e[e.TS=3]="TS",e[e.TSX=4]="TSX"}(l||(l={}));var g;!function(e){e[e.ES3=0]="ES3",e[e.ES5=1]="ES5",e[e.ES2015=2]="ES2015",e[e.ES2016=3]="ES2016",e[e.ES2017=4]="ES2017",e[e.ESNext=5]="ESNext",e[e.Latest=5]="Latest"}(g||(g={}));var f;!function(e){e[e.Standard=0]="Standard",e[e.JSX=1]="JSX"}(f||(f={}));var d;!function(e){e[e.Classic=1]="Classic",e[e.NodeJs=2]="NodeJs"}(d||(d={}));var S=new s({allowNonTsExtensions:!0,target:g.Latest},{noSemanticValidation:!1,noSyntaxValidation:!1}),m=new s({allowNonTsExtensions:!0,allowJs:!0,target:g.Latest},{noSemanticValidation:!0,noSyntaxValidation:!1});monaco.languages.typescript=o(),monaco.languages.register({id:"typescript",extensions:[".ts",".tsx"],aliases:["TypeScript","ts","typescript"],mimetypes:["text/typescript"]}),monaco.languages.onLanguage("typescript",function(){r(function(e){return e.setupTypeScript(S)})}),monaco.languages.register({id:"javascript",extensions:[".js",".es6",".jsx"],firstLine:"^#!.*\\bnode",filenames:["jakefile"],aliases:["JavaScript","javascript","js"],mimetypes:["text/javascript"]}),monaco.languages.onLanguage("javascript",function(){r(function(e){return e.setupJavaScript(m)})})});
/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * monaco-css version: 1.3.3(69ad62c9851c1708c61446b6ac2218b99fcdd428)
 * Released under the MIT license
 * https://github.com/Microsoft/monaco-css/blob/master/LICENSE.md
 *-----------------------------------------------------------------------------*/
!function(e){if("object"==typeof module&&"object"==typeof module.exports){var n=e(require,exports);void 0!==n&&(module.exports=n)}else"function"==typeof define&&define.amd&&define("vs/language/css/monaco.contribution",["require","exports","vs/editor/edcore.main"],e)}(function(e,n){function o(){return{cssDefaults:a,lessDefaults:c,scssDefaults:u}}function t(n){e(["vs/language/css/cssMode"],n)}Object.defineProperty(n,"__esModule",{value:!0});var i=monaco.Emitter,r=function(){function e(e,n){this._onDidChange=new i,this._languageId=e,this.setDiagnosticsOptions(n)}return Object.defineProperty(e.prototype,"onDidChange",{get:function(){return this._onDidChange.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"languageId",{get:function(){return this._languageId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"diagnosticsOptions",{get:function(){return this._diagnosticsOptions},enumerable:!0,configurable:!0}),e.prototype.setDiagnosticsOptions=function(e){this._diagnosticsOptions=e||Object.create(null),this._onDidChange.fire(this)},e}();n.LanguageServiceDefaultsImpl=r;var s={validate:!0,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"}},a=new r("css",s),u=new r("scss",s),c=new r("less",s);monaco.languages.css=o(),monaco.languages.onLanguage("less",function(){t(function(e){return e.setupMode(c)})}),monaco.languages.onLanguage("scss",function(){t(function(e){return e.setupMode(u)})}),monaco.languages.onLanguage("css",function(){t(function(e){return e.setupMode(a)})})});
/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * monaco-json version: 1.3.2(63d6dadc9cc5928c83a232dd95cdc31403f08974)
 * Released under the MIT license
 * https://github.com/Microsoft/monaco-json/blob/master/LICENSE.md
 *-----------------------------------------------------------------------------*/
!function(e){if("object"==typeof module&&"object"==typeof module.exports){var n=e(require,exports);void 0!==n&&(module.exports=n)}else"function"==typeof define&&define.amd&&define("vs/language/json/monaco.contribution",["require","exports","vs/editor/edcore.main"],e)}(function(e,n){function o(){return{jsonDefaults:r}}function t(n){e(["vs/language/json/jsonMode"],n)}Object.defineProperty(n,"__esModule",{value:!0});var i=monaco.Emitter,s=function(){function e(e,n){this._onDidChange=new i,this._languageId=e,this.setDiagnosticsOptions(n)}return Object.defineProperty(e.prototype,"onDidChange",{get:function(){return this._onDidChange.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"languageId",{get:function(){return this._languageId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"diagnosticsOptions",{get:function(){return this._diagnosticsOptions},enumerable:!0,configurable:!0}),e.prototype.setDiagnosticsOptions=function(e){this._diagnosticsOptions=e||Object.create(null),this._onDidChange.fire(this)},e}();n.LanguageServiceDefaultsImpl=s;var a={validate:!0,allowComments:!0,schemas:[]},r=new s("json",a);monaco.languages.json=o(),monaco.languages.register({id:"json",extensions:[".json",".bowerrc",".jshintrc",".jscsrc",".eslintrc",".babelrc"],aliases:["JSON","json"],mimetypes:["application/json"]}),monaco.languages.onLanguage("json",function(){t(function(e){return e.setupMode(r)})})});
/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * monaco-html version: 1.3.2(5ec45016d73d25ccf42bc1626de18d4329aabe34)
 * Released under the MIT license
 * https://github.com/Microsoft/monaco-html/blob/master/LICENSE.md
 *-----------------------------------------------------------------------------*/
!function(e){if("object"==typeof module&&"object"==typeof module.exports){var t=e(require,exports);void 0!==t&&(module.exports=t)}else"function"==typeof define&&define.amd&&define("vs/language/html/monaco.contribution",["require","exports","vs/editor/edcore.main"],e)}(function(e,t){function n(){return{htmlDefaults:d,razorDefaults:p,handlebarDefaults:m}}function o(t){e(["vs/language/html/htmlMode"],t)}Object.defineProperty(t,"__esModule",{value:!0});var a=monaco.Emitter,r=function(){function e(e,t){this._onDidChange=new a,this._languageId=e,this.setOptions(t)}return Object.defineProperty(e.prototype,"onDidChange",{get:function(){return this._onDidChange.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"languageId",{get:function(){return this._languageId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!0,configurable:!0}),e.prototype.setOptions=function(e){this._options=e||Object.create(null),this._onDidChange.fire(this)},e}();t.LanguageServiceDefaultsImpl=r;var u={tabSize:4,insertSpaces:!1,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:!1,preserveNewLines:!0,maxPreserveNewLines:null,indentHandlebars:!1,endWithNewline:!1,extraLiners:"head, body, /html",wrapAttributes:"auto"},i={format:u,suggest:{html5:!0,angular1:!0,ionic:!0}},s={format:u,suggest:{html5:!0}},l={format:u,suggest:{html5:!0,razor:!0}},g="html",c="handlebars",f="razor",d=new r(g,i),m=new r(c,s),p=new r(f,l);monaco.languages.html=n(),monaco.languages.onLanguage(g,function(){o(function(e){return e.setupMode(d)})}),monaco.languages.onLanguage(c,function(){o(function(e){return e.setupMode(m)})}),monaco.languages.onLanguage(f,function(){o(function(e){return e.setupMode(p)})})});
/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * monaco-languages version: 0.9.0(e162b4ba29044167bc7181c42b3270fa8a467424)
 * Released under the MIT license
 * https://github.com/Microsoft/monaco-languages/blob/master/LICENSE.md
 *-----------------------------------------------------------------------------*/
define("vs/basic-languages/src/monaco.contribution",["require","exports","vs/editor/edcore.main"],function(s,e){"use strict";function i(e){var i=o[e].module;return new l.Promise(function(a,t,o){s([i],function(s){l.languages.setMonarchTokensProvider(e,s.language),l.languages.setLanguageConfiguration(e,s.conf),a(void 0)},t)})}function a(s){return n[s]||(n[s]=i(s)),n[s]}function t(s){var e=s.id;o[e]=s,l.languages.register(s),l.languages.onLanguage(e,function(){a(e)})}Object.defineProperty(e,"__esModule",{value:!0});var l="undefined"==typeof monaco?self.monaco:monaco,o={},n={};e.loadLanguage=a,t({id:"bat",extensions:[".bat",".cmd"],aliases:["Batch","bat"],module:"./bat"}),t({id:"coffeescript",extensions:[".coffee"],aliases:["CoffeeScript","coffeescript","coffee"],mimetypes:["text/x-coffeescript","text/coffeescript"],module:"./coffee"}),t({id:"c",extensions:[".c",".h"],aliases:["C","c"],module:"./cpp"}),t({id:"cpp",extensions:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],aliases:["C++","Cpp","cpp"],module:"./cpp"}),t({id:"csharp",extensions:[".cs",".csx"],aliases:["C#","csharp"],module:"./csharp"}),t({id:"dockerfile",extensions:[".dockerfile"],filenames:["Dockerfile"],aliases:["Dockerfile"],module:"./dockerfile"}),t({id:"fsharp",extensions:[".fs",".fsi",".ml",".mli",".fsx",".fsscript"],aliases:["F#","FSharp","fsharp"],module:"./fsharp"}),t({id:"go",extensions:[".go"],aliases:["Go"],module:"./go"}),t({id:"handlebars",extensions:[".handlebars",".hbs"],aliases:["Handlebars","handlebars"],mimetypes:["text/x-handlebars-template"],module:"./handlebars"}),t({id:"html",extensions:[".html",".htm",".shtml",".xhtml",".mdoc",".jsp",".asp",".aspx",".jshtm"],aliases:["HTML","htm","html","xhtml"],mimetypes:["text/html","text/x-jshtm","text/template","text/ng-template"],module:"./html"}),t({id:"ini",extensions:[".ini",".properties",".gitconfig"],filenames:["config",".gitattributes",".gitconfig",".editorconfig"],aliases:["Ini","ini"],module:"./ini"}),t({id:"pug",extensions:[".jade",".pug"],aliases:["Pug","Jade","jade"],module:"./pug"}),t({id:"java",extensions:[".java",".jav"],aliases:["Java","java"],mimetypes:["text/x-java-source","text/x-java"],module:"./java"}),t({id:"lua",extensions:[".lua"],aliases:["Lua","lua"],module:"./lua"}),t({id:"markdown",extensions:[".md",".markdown",".mdown",".mkdn",".mkd",".mdwn",".mdtxt",".mdtext"],aliases:["Markdown","markdown"],module:"./markdown"}),t({id:"msdax",extensions:[".dax",".msdax"],aliases:["DAX","MSDAX"],module:"./msdax"}),t({id:"objective-c",extensions:[".m"],aliases:["Objective-C"],module:"./objective-c"}),t({id:"postiats",extensions:[".dats",".sats",".hats"],aliases:["ATS","ATS/Postiats"],module:"./postiats"}),t({id:"php",extensions:[".php",".php4",".php5",".phtml",".ctp"],aliases:["PHP","php"],mimetypes:["application/x-php"],module:"./php"}),t({id:"powershell",extensions:[".ps1",".psm1",".psd1"],aliases:["PowerShell","powershell","ps","ps1"],module:"./powershell"}),t({id:"python",extensions:[".py",".rpy",".pyw",".cpy",".gyp",".gypi"],aliases:["Python","py"],firstLine:"^#!/.*\\bpython[0-9.-]*\\b",module:"./python"}),t({id:"r",extensions:[".r",".rhistory",".rprofile",".rt"],aliases:["R","r"],module:"./r"}),t({id:"razor",extensions:[".cshtml"],aliases:["Razor","razor"],mimetypes:["text/x-cshtml"],module:"./razor"}),t({id:"ruby",extensions:[".rb",".rbx",".rjs",".gemspec",".pp"],filenames:["rakefile"],aliases:["Ruby","rb"],module:"./ruby"}),t({id:"swift",aliases:["Swift","swift"],extensions:[".swift"],mimetypes:["text/swift"],module:"./swift"}),t({id:"sql",extensions:[".sql"],aliases:["SQL"],module:"./sql"}),t({id:"vb",extensions:[".vb"],aliases:["Visual Basic","vb"],module:"./vb"}),t({id:"xml",extensions:[".xml",".dtd",".ascx",".csproj",".config",".wxi",".wxl",".wxs",".xaml",".svg",".svgz"],firstLine:"(\\<\\?xml.*)|(\\<svg)|(\\<\\!doctype\\s+svg)",aliases:["XML","xml"],mimetypes:["text/xml","application/xml","application/xaml+xml","application/xml-dtd"],module:"./xml"}),t({id:"less",extensions:[".less"],aliases:["Less","less"],mimetypes:["text/x-less","text/less"],module:"./less"}),t({id:"scss",extensions:[".scss"],aliases:["Sass","sass","scss"],mimetypes:["text/x-scss","text/scss"],module:"./scss"}),t({id:"css",extensions:[".css"],aliases:["CSS","css"],mimetypes:["text/css"],module:"./css"}),t({id:"yaml",extensions:[".yaml",".yml"],aliases:["YAML","yaml","YML","yml"],mimetypes:["application/x-yaml"],module:"./yaml"}),t({id:"sol",extensions:[".sol"],aliases:["sol","solidity","Solidity"],module:"./solidity"}),t({id:"sb",extensions:[".sb"],aliases:["Small Basic","sb"],module:"./sb"})});
define("vs/editor/editor.main", ["vs/editor/edcore.main","vs/language/typescript/src/monaco.contribution","vs/language/css/monaco.contribution","vs/language/json/monaco.contribution","vs/language/html/monaco.contribution","vs/basic-languages/src/monaco.contribution"], function() {});
//# sourceMappingURL=editor.main.js.map
