hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 3, "code_window": [ "\n", "viteLegacyPlugin.cspHashes = [\n", " createHash('sha256').update(safari10NoModuleFix).digest('base64'),\n", " createHash('sha256').update(systemJSInlineCode).digest('base64'),\n", " createHash('sha256').update(dynamicFallbackInlineCode).digest('base64')\n", "]" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " createHash('sha256').update(detectDynamicImportVarInitCode).digest('base64'),\n", " createHash('sha256').update(detectDynamicImportCode).digest('base64'),\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "add", "edit_start_line_idx": 697 }
Object.assign(exports, { hello() { return 'Hello World!' } })
packages/playground/ssr-deps/only-object-assigned-exports/index.js
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.0001744814362609759, 0.0001744814362609759, 0.0001744814362609759, 0.0001744814362609759, 0 ]
{ "id": 3, "code_window": [ "\n", "viteLegacyPlugin.cspHashes = [\n", " createHash('sha256').update(safari10NoModuleFix).digest('base64'),\n", " createHash('sha256').update(systemJSInlineCode).digest('base64'),\n", " createHash('sha256').update(dynamicFallbackInlineCode).digest('base64')\n", "]" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " createHash('sha256').update(detectDynamicImportVarInitCode).digest('base64'),\n", " createHash('sha256').update(detectDynamicImportCode).digest('base64'),\n" ], "file_path": "packages/plugin-legacy/index.js", "type": "add", "edit_start_line_idx": 697 }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" href="/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite App</title> </head> <body> <div id="app"></div> <script type="module" src="/src/main.js"></script> </body> </html>
packages/create-vite/template-vue/index.html
0
https://github.com/vitejs/vite/commit/a118a1d98c63028ddc8b2b3389b8cfa58d771e76
[ 0.00017144595040008426, 0.00016969037824310362, 0.000167934806086123, 0.00016969037824310362, 0.0000017555721569806337 ]
{ "id": 0, "code_window": [ "\t * @internal\n", "\t */\n", "\tonDidType(listener: (text: string) => void): IDisposable;\n", "\t/**\n", "\t * An event emitted when users paste text in the editor.\n", "\t * @event\n", "\t * @internal\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t/**\n", "\t * An event emitted when editing failed because the editor is read-only.\n", "\t * @event\n", "\t * @internal\n", "\t */\n", "\tonDidAttemptReadOnlyEdit(listener: () => void): IDisposable;\n" ], "file_path": "src/vs/editor/browser/editorBrowser.ts", "type": "add", "edit_start_line_idx": 393 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./messageController'; import { setDisposableTimeout } from 'vs/base/common/async'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { ICodeEditor, IContentWidget, IContentWidgetPosition, ContentWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IPosition } from 'vs/editor/common/core/position'; import { registerThemingParticipant, HIGH_CONTRAST } from 'vs/platform/theme/common/themeService'; import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry'; import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; export class MessageController implements editorCommon.IEditorContribution { private static readonly _id = 'editor.contrib.messageController'; static MESSAGE_VISIBLE = new RawContextKey<boolean>('messageVisible', false); static get(editor: ICodeEditor): MessageController { return editor.getContribution<MessageController>(MessageController._id); } getId(): string { return MessageController._id; } private _editor: ICodeEditor; private _visible: IContextKey<boolean>; private _messageWidget: MessageWidget; private _messageListeners: IDisposable[] = []; constructor( editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService ) { this._editor = editor; this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService); } dispose(): void { this._visible.reset(); } isVisible() { return this._visible.get(); } showMessage(message: string, position: IPosition): void { alert(message); this._visible.set(true); dispose(this._messageWidget); this._messageListeners = dispose(this._messageListeners); this._messageWidget = new MessageWidget(this._editor, position, message); // close on blur, cursor, model change, dispose this._messageListeners.push(this._editor.onDidBlurEditorText(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeCursorPosition(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidDispose(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeModel(() => this.closeMessage())); // close after 3s this._messageListeners.push(setDisposableTimeout(() => this.closeMessage(), 3000)); // close on mouse move let bounds: Range; this._messageListeners.push(this._editor.onMouseMove(e => { // outside the text area if (!e.target.position) { return; } if (!bounds) { // define bounding box around position and first mouse occurance bounds = new Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1); } else if (!bounds.containsPosition(e.target.position)) { // check if position is still in bounds this.closeMessage(); } })); } closeMessage(): void { this._visible.reset(); this._messageListeners = dispose(this._messageListeners); this._messageListeners.push(MessageWidget.fadeOut(this._messageWidget)); } } const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get); registerEditorCommand(new MessageCommand({ id: 'leaveEditorMessage', precondition: MessageController.MESSAGE_VISIBLE, handler: c => c.closeMessage(), kbOpts: { weight: KeybindingsRegistry.WEIGHT.editorContrib(30), primary: KeyCode.Escape } })); class MessageWidget implements IContentWidget { // Editor.IContentWidget.allowEditorOverflow readonly allowEditorOverflow = true; readonly suppressMouseDown = false; private _editor: ICodeEditor; private _position: IPosition; private _domNode: HTMLDivElement; static fadeOut(messageWidget: MessageWidget): IDisposable { let handle: number; const dispose = () => { messageWidget.dispose(); clearTimeout(handle); messageWidget.getDomNode().removeEventListener('animationend', dispose); }; handle = setTimeout(dispose, 110); messageWidget.getDomNode().addEventListener('animationend', dispose); messageWidget.getDomNode().classList.add('fadeOut'); return { dispose }; } constructor(editor: ICodeEditor, { lineNumber, column }: IPosition, text: string) { this._editor = editor; this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, editorCommon.ScrollType.Smooth); this._position = { lineNumber, column: column - 1 }; this._domNode = document.createElement('div'); this._domNode.classList.add('monaco-editor-overlaymessage'); const message = document.createElement('div'); message.classList.add('message'); message.textContent = text; this._domNode.appendChild(message); const anchor = document.createElement('div'); anchor.classList.add('anchor'); this._domNode.appendChild(anchor); this._editor.addContentWidget(this); this._domNode.classList.add('fadeIn'); } dispose() { this._editor.removeContentWidget(this); } getId(): string { return 'messageoverlay'; } getDomNode(): HTMLElement { return this._domNode; } getPosition(): IContentWidgetPosition { return { position: this._position, preference: [ContentWidgetPositionPreference.ABOVE] }; } } registerEditorContribution(MessageController); registerThemingParticipant((theme, collector) => { let border = theme.getColor(inputValidationInfoBorder); if (border) { let borderWidth = theme.type === 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}; }`); } let background = theme.getColor(inputValidationInfoBackground); if (background) { collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { background-color: ${background}; }`); } });
src/vs/editor/contrib/message/messageController.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0008472886984236538, 0.0002081074781017378, 0.0001652331557124853, 0.00016752361261751503, 0.0001518068602308631 ]
{ "id": 0, "code_window": [ "\t * @internal\n", "\t */\n", "\tonDidType(listener: (text: string) => void): IDisposable;\n", "\t/**\n", "\t * An event emitted when users paste text in the editor.\n", "\t * @event\n", "\t * @internal\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t/**\n", "\t * An event emitted when editing failed because the editor is read-only.\n", "\t * @event\n", "\t * @internal\n", "\t */\n", "\tonDidAttemptReadOnlyEdit(listener: () => void): IDisposable;\n" ], "file_path": "src/vs/editor/browser/editorBrowser.ts", "type": "add", "edit_start_line_idx": 393 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "reflectCSSValue": "Emmet: ะพั‚ั€ะฐะถะตะฝะธะต ะทะฝะฐั‡ะตะฝะธั CSS" }
i18n/rus/src/vs/workbench/parts/emmet/electron-browser/actions/reflectCssValue.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017047309665940702, 0.00017047309665940702, 0.00017047309665940702, 0.00017047309665940702, 0 ]
{ "id": 0, "code_window": [ "\t * @internal\n", "\t */\n", "\tonDidType(listener: (text: string) => void): IDisposable;\n", "\t/**\n", "\t * An event emitted when users paste text in the editor.\n", "\t * @event\n", "\t * @internal\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t/**\n", "\t * An event emitted when editing failed because the editor is read-only.\n", "\t * @event\n", "\t * @internal\n", "\t */\n", "\tonDidAttemptReadOnlyEdit(listener: () => void): IDisposable;\n" ], "file_path": "src/vs/editor/browser/editorBrowser.ts", "type": "add", "edit_start_line_idx": 393 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "displayName": "Ruby Dil Temelleri", "description": "Ruby dosyalarฤฑ iรงin sรถz dizimi vurgulama ve ayraรง eลŸleลŸtirme saฤŸlar." }
i18n/trk/extensions/ruby/package.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017434025357943028, 0.00017354529700241983, 0.0001727503549773246, 0.00017354529700241983, 7.949493010528386e-7 ]
{ "id": 0, "code_window": [ "\t * @internal\n", "\t */\n", "\tonDidType(listener: (text: string) => void): IDisposable;\n", "\t/**\n", "\t * An event emitted when users paste text in the editor.\n", "\t * @event\n", "\t * @internal\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t/**\n", "\t * An event emitted when editing failed because the editor is read-only.\n", "\t * @event\n", "\t * @internal\n", "\t */\n", "\tonDidAttemptReadOnlyEdit(listener: () => void): IDisposable;\n" ], "file_path": "src/vs/editor/browser/editorBrowser.ts", "type": "add", "edit_start_line_idx": 393 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "ariaCompositeToolbarLabel": "{0} ๋™์ž‘", "titleTooltip": "{0}({1})" }
i18n/kor/src/vs/workbench/browser/parts/compositePart.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017434025357943028, 0.00017399308853782713, 0.00017364593804813921, 0.00017399308853782713, 3.471577656455338e-7 ]
{ "id": 1, "code_window": [ "\tpublic readonly onDidChangeCursorPosition: Event<ICursorPositionChangedEvent> = this._onDidChangeCursorPosition.event;\n", "\n", "\tprivate readonly _onDidChangeCursorSelection: Emitter<ICursorSelectionChangedEvent> = this._register(new Emitter<ICursorSelectionChangedEvent>());\n", "\tpublic readonly onDidChangeCursorSelection: Event<ICursorSelectionChangedEvent> = this._onDidChangeCursorSelection.event;\n", "\n", "\tprivate readonly _onDidLayoutChange: Emitter<editorOptions.EditorLayoutInfo> = this._register(new Emitter<editorOptions.EditorLayoutInfo>());\n", "\tpublic readonly onDidLayoutChange: Event<editorOptions.EditorLayoutInfo> = this._onDidLayoutChange.event;\n", "\n", "\tprotected _editorTextFocus: BooleanEventEmitter = this._register(new BooleanEventEmitter());\n", "\tpublic readonly onDidFocusEditorText: Event<void> = this._editorTextFocus.onDidChangeToTrue;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _onDidAttemptReadOnlyEdit: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidAttemptReadOnlyEdit: Event<void> = this._onDidAttemptReadOnlyEdit.event;\n", "\n" ], "file_path": "src/vs/editor/common/commonCodeEditor.ts", "type": "add", "edit_start_line_idx": 69 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./messageController'; import { setDisposableTimeout } from 'vs/base/common/async'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { ICodeEditor, IContentWidget, IContentWidgetPosition, ContentWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IPosition } from 'vs/editor/common/core/position'; import { registerThemingParticipant, HIGH_CONTRAST } from 'vs/platform/theme/common/themeService'; import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry'; import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; export class MessageController implements editorCommon.IEditorContribution { private static readonly _id = 'editor.contrib.messageController'; static MESSAGE_VISIBLE = new RawContextKey<boolean>('messageVisible', false); static get(editor: ICodeEditor): MessageController { return editor.getContribution<MessageController>(MessageController._id); } getId(): string { return MessageController._id; } private _editor: ICodeEditor; private _visible: IContextKey<boolean>; private _messageWidget: MessageWidget; private _messageListeners: IDisposable[] = []; constructor( editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService ) { this._editor = editor; this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService); } dispose(): void { this._visible.reset(); } isVisible() { return this._visible.get(); } showMessage(message: string, position: IPosition): void { alert(message); this._visible.set(true); dispose(this._messageWidget); this._messageListeners = dispose(this._messageListeners); this._messageWidget = new MessageWidget(this._editor, position, message); // close on blur, cursor, model change, dispose this._messageListeners.push(this._editor.onDidBlurEditorText(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeCursorPosition(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidDispose(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeModel(() => this.closeMessage())); // close after 3s this._messageListeners.push(setDisposableTimeout(() => this.closeMessage(), 3000)); // close on mouse move let bounds: Range; this._messageListeners.push(this._editor.onMouseMove(e => { // outside the text area if (!e.target.position) { return; } if (!bounds) { // define bounding box around position and first mouse occurance bounds = new Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1); } else if (!bounds.containsPosition(e.target.position)) { // check if position is still in bounds this.closeMessage(); } })); } closeMessage(): void { this._visible.reset(); this._messageListeners = dispose(this._messageListeners); this._messageListeners.push(MessageWidget.fadeOut(this._messageWidget)); } } const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get); registerEditorCommand(new MessageCommand({ id: 'leaveEditorMessage', precondition: MessageController.MESSAGE_VISIBLE, handler: c => c.closeMessage(), kbOpts: { weight: KeybindingsRegistry.WEIGHT.editorContrib(30), primary: KeyCode.Escape } })); class MessageWidget implements IContentWidget { // Editor.IContentWidget.allowEditorOverflow readonly allowEditorOverflow = true; readonly suppressMouseDown = false; private _editor: ICodeEditor; private _position: IPosition; private _domNode: HTMLDivElement; static fadeOut(messageWidget: MessageWidget): IDisposable { let handle: number; const dispose = () => { messageWidget.dispose(); clearTimeout(handle); messageWidget.getDomNode().removeEventListener('animationend', dispose); }; handle = setTimeout(dispose, 110); messageWidget.getDomNode().addEventListener('animationend', dispose); messageWidget.getDomNode().classList.add('fadeOut'); return { dispose }; } constructor(editor: ICodeEditor, { lineNumber, column }: IPosition, text: string) { this._editor = editor; this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, editorCommon.ScrollType.Smooth); this._position = { lineNumber, column: column - 1 }; this._domNode = document.createElement('div'); this._domNode.classList.add('monaco-editor-overlaymessage'); const message = document.createElement('div'); message.classList.add('message'); message.textContent = text; this._domNode.appendChild(message); const anchor = document.createElement('div'); anchor.classList.add('anchor'); this._domNode.appendChild(anchor); this._editor.addContentWidget(this); this._domNode.classList.add('fadeIn'); } dispose() { this._editor.removeContentWidget(this); } getId(): string { return 'messageoverlay'; } getDomNode(): HTMLElement { return this._domNode; } getPosition(): IContentWidgetPosition { return { position: this._position, preference: [ContentWidgetPositionPreference.ABOVE] }; } } registerEditorContribution(MessageController); registerThemingParticipant((theme, collector) => { let border = theme.getColor(inputValidationInfoBorder); if (border) { let borderWidth = theme.type === 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}; }`); } let background = theme.getColor(inputValidationInfoBackground); if (background) { collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { background-color: ${background}; }`); } });
src/vs/editor/contrib/message/messageController.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.9978118538856506, 0.05268539860844612, 0.00016602501273155212, 0.00017093877249863, 0.22276844084262848 ]
{ "id": 1, "code_window": [ "\tpublic readonly onDidChangeCursorPosition: Event<ICursorPositionChangedEvent> = this._onDidChangeCursorPosition.event;\n", "\n", "\tprivate readonly _onDidChangeCursorSelection: Emitter<ICursorSelectionChangedEvent> = this._register(new Emitter<ICursorSelectionChangedEvent>());\n", "\tpublic readonly onDidChangeCursorSelection: Event<ICursorSelectionChangedEvent> = this._onDidChangeCursorSelection.event;\n", "\n", "\tprivate readonly _onDidLayoutChange: Emitter<editorOptions.EditorLayoutInfo> = this._register(new Emitter<editorOptions.EditorLayoutInfo>());\n", "\tpublic readonly onDidLayoutChange: Event<editorOptions.EditorLayoutInfo> = this._onDidLayoutChange.event;\n", "\n", "\tprotected _editorTextFocus: BooleanEventEmitter = this._register(new BooleanEventEmitter());\n", "\tpublic readonly onDidFocusEditorText: Event<void> = this._editorTextFocus.onDidChangeToTrue;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _onDidAttemptReadOnlyEdit: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidAttemptReadOnlyEdit: Event<void> = this._onDidAttemptReadOnlyEdit.event;\n", "\n" ], "file_path": "src/vs/editor/common/commonCodeEditor.ts", "type": "add", "edit_start_line_idx": 69 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "retry": "๋‹ค์‹œ ์‹œ๋„", "rename": "์ด๋ฆ„ ๋ฐ”๊พธ๊ธฐ", "newFile": "์ƒˆ ํŒŒ์ผ", "newFolder": "์ƒˆ ํด๋”", "openFolderFirst": "์•ˆ์— ํŒŒ์ผ์ด๋‚˜ ํด๋”๋ฅผ ๋งŒ๋“ค๋ ค๋ฉด ๋จผ์ € ํด๋”๋ฅผ ์—ฝ๋‹ˆ๋‹ค.", "newUntitledFile": "์ œ๋ชฉ์ด ์—†๋Š” ์ƒˆ ํŒŒ์ผ", "createNewFile": "์ƒˆ ํŒŒ์ผ", "createNewFolder": "์ƒˆ ํด๋”", "deleteButtonLabelRecycleBin": "ํœด์ง€ํ†ต์œผ๋กœ ์ด๋™(&&M)", "deleteButtonLabelTrash": "ํœด์ง€ํ†ต์œผ๋กœ ์ด๋™(&&M)", "deleteButtonLabel": "์‚ญ์ œ(&&D)", "dirtyMessageFolderOneDelete": "1๊ฐœ ํŒŒ์ผ์— ์ €์žฅ๋˜์ง€ ์•Š์€ ๋ณ€๊ฒฝ ๋‚ด์šฉ์ด ์žˆ๋Š” ํด๋”๋ฅผ ์‚ญ์ œํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๊ณ„์†ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?", "dirtyMessageFolderDelete": "{0}๊ฐœ ํŒŒ์ผ์— ์ €์žฅ๋˜์ง€ ์•Š์€ ๋ณ€๊ฒฝ ๋‚ด์šฉ์ด ์žˆ๋Š” ํด๋”๋ฅผ ์‚ญ์ œํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๊ณ„์†ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?", "dirtyMessageFileDelete": "์ €์žฅ๋˜์ง€ ์•Š์€ ๋ณ€๊ฒฝ ๋‚ด์šฉ์ด ์žˆ๋Š” ํŒŒ์ผ์„ ์‚ญ์ œํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๊ณ„์†ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?", "dirtyWarning": "๋ณ€๊ฒฝ ๋‚ด์šฉ์„ ์ €์žฅํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ ๋ณ€๊ฒฝ ๋‚ด์šฉ์ด ์†์‹ค๋ฉ๋‹ˆ๋‹ค.", "confirmMoveTrashMessageFolder": "'{0}'๊ณผ(์™€) ํ•ด๋‹น ๋‚ด์šฉ์„ ์‚ญ์ œํ• ๊นŒ์š”?", "confirmMoveTrashMessageFile": "'{0}'์„(๋ฅผ) ์‚ญ์ œํ• ๊นŒ์š”?", "undoBin": "ํœด์ง€ํ†ต์—์„œ ๋ณต์›ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.", "undoTrash": "ํœด์ง€ํ†ต์—์„œ ๋ณต์›ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.", "doNotAskAgain": "์ด ๋ฉ”์‹œ์ง€๋ฅผ ๋‹ค์‹œ ํ‘œ์‹œ ์•ˆ ํ•จ", "confirmDeleteMessageFolder": "'{0}'๊ณผ(์™€) ํ•ด๋‹น ๋‚ด์šฉ์„ ์˜๊ตฌํžˆ ์‚ญ์ œํ• ๊นŒ์š”?", "confirmDeleteMessageFile": "'{0}'์„(๋ฅผ) ์˜๊ตฌํžˆ ์‚ญ์ œํ• ๊นŒ์š”?", "irreversible": "์ด ์ž‘์—…์€ ์ทจ์†Œํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.", "permDelete": "์˜๊ตฌํžˆ ์‚ญ์ œ", "delete": "์‚ญ์ œ", "importFiles": "ํŒŒ์ผ ๊ฐ€์ ธ์˜ค๊ธฐ", "confirmOverwrite": "์ด๋ฆ„์ด ๊ฐ™์€ ํŒŒ์ผ ๋˜๋Š” ํด๋”๊ฐ€ ๋Œ€์ƒ ํด๋”์— ์ด๋ฏธ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฎ์–ด์“ธ๊นŒ์š”?", "replaceButtonLabel": "๋ฐ”๊พธ๊ธฐ(&&R)", "copyFile": "๋ณต์‚ฌ", "pasteFile": "๋ถ™์—ฌ๋„ฃ๊ธฐ", "duplicateFile": "์ค‘๋ณต", "openToSide": "์ธก๋ฉด์—์„œ ์—ด๊ธฐ", "compareSource": "๋น„๊ต๋ฅผ ์œ„ํ•ด ์„ ํƒ", "globalCompareFile": "ํ™œ์„ฑ ํŒŒ์ผ์„ ๋‹ค์Œ๊ณผ ๋น„๊ต...", "openFileToCompare": "์ฒซ ๋ฒˆ์งธ ํŒŒ์ผ์„ ์—ด์–ด์„œ ๋‹ค๋ฅธ ํŒŒ์ผ๊ณผ ๋น„๊ตํ•ฉ๋‹ˆ๋‹ค.", "compareWith": "'{0}'๊ณผ(์™€) '{1}' ๋น„๊ต", "compareFiles": "ํŒŒ์ผ ๋น„๊ต", "refresh": "์ƒˆ๋กœ ๊ณ ์นจ", "save": "์ €์žฅ", "saveAs": "๋‹ค๋ฅธ ์ด๋ฆ„์œผ๋กœ ์ €์žฅ...", "saveAll": "๋ชจ๋‘ ์ €์žฅ", "saveAllInGroup": "๊ทธ๋ฃน์˜ ๋ชจ๋“  ํ•ญ๋ชฉ ์ €์žฅ", "saveFiles": "ํŒŒ์ผ ๋ชจ๋‘ ์ €์žฅ", "revert": "ํŒŒ์ผ ๋˜๋Œ๋ฆฌ๊ธฐ", "focusOpenEditors": "์—ด๋ ค ์žˆ๋Š” ํŽธ์ง‘๊ธฐ ๋ทฐ์— ํฌ์ปค์Šค", "focusFilesExplorer": "ํŒŒ์ผ ํƒ์ƒ‰๊ธฐ์— ํฌ์ปค์Šค", "showInExplorer": "์„ธ๋กœ ๋ง‰๋Œ€์—์„œ ํ™œ์„ฑ ํŒŒ์ผ ํ‘œ์‹œ", "openFileToShow": "ํƒ์ƒ‰๊ธฐ์— ํ‘œ์‹œํ•˜๋ ค๋ฉด ๋จผ์ € ํŒŒ์ผ์„ ์—ฝ๋‹ˆ๋‹ค.", "collapseExplorerFolders": "ํƒ์ƒ‰๊ธฐ์—์„œ ํด๋” ์ถ•์†Œ", "refreshExplorer": "ํƒ์ƒ‰๊ธฐ ์ƒˆ๋กœ ๊ณ ์นจ", "openFileInNewWindow": "์ƒˆ ์ฐฝ์—์„œ ํ™œ์„ฑ ํŒŒ์ผ ์—ด๊ธฐ", "openFileToShowInNewWindow": "๋จผ์ € ํŒŒ์ผ ํ•œ ๊ฐœ๋ฅผ ์ƒˆ ์ฐฝ์—์„œ ์—ฝ๋‹ˆ๋‹ค.", "revealInWindows": "ํƒ์ƒ‰๊ธฐ์— ํ‘œ์‹œ", "revealInMac": "Finder์— ํ‘œ์‹œ", "openContainer": "์ƒ์œ„ ํด๋” ์—ด๊ธฐ", "revealActiveFileInWindows": "Windows ํƒ์ƒ‰๊ธฐ์— ํ™œ์„ฑ ํŒŒ์ผ ํ‘œ์‹œ", "revealActiveFileInMac": "Finder์— ํ™œ์„ฑ ํŒŒ์ผ ํ‘œ์‹œ", "openActiveFileContainer": "ํ™œ์„ฑ ํŒŒ์ผ์˜ ์ƒ์œ„ ํด๋” ์—ด๊ธฐ", "copyPath": "๊ฒฝ๋กœ ๋ณต์‚ฌ", "copyPathOfActive": "ํ™œ์„ฑ ํŒŒ์ผ์˜ ๊ฒฝ๋กœ ๋ณต์‚ฌ", "emptyFileNameError": "ํŒŒ์ผ ๋˜๋Š” ํด๋” ์ด๋ฆ„์„ ์ž…๋ ฅํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.", "fileNameExistsError": "ํŒŒ์ผ ๋˜๋Š” ํด๋” **{0}**์ด(๊ฐ€) ์ด ์œ„์น˜์— ์ด๋ฏธ ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์„ ํƒํ•˜์„ธ์š”.", "invalidFileNameError": "**{0}**(์ด)๋ผ๋Š” ์ด๋ฆ„์€ ํŒŒ์ผ ๋˜๋Š” ํด๋” ์ด๋ฆ„์œผ๋กœ ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์„ ํƒํ•˜์„ธ์š”.", "filePathTooLongError": "**{0}**(์ด)๋ผ๋Š” ์ด๋ฆ„์„ ์‚ฌ์šฉํ•˜๋ฉด ๊ฒฝ๋กœ๊ฐ€ ๋„ˆ๋ฌด ๊ธธ์–ด์ง‘๋‹ˆ๋‹ค. ์งง์€ ์ด๋ฆ„์„ ์„ ํƒํ•˜์„ธ์š”.", "compareWithSaved": "ํ™œ์„ฑ ํŒŒ์ผ์„ ์ €์žฅ๋œ ํŒŒ์ผ๊ณผ ๋น„๊ต", "modifiedLabel": "{0}(๋””์Šคํฌ) โ†” {1}" }
i18n/kor/src/vs/workbench/parts/files/browser/fileActions.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017452618340030313, 0.00016940497152972966, 0.0001657322427490726, 0.0001689023629296571, 0.0000026433824587002164 ]
{ "id": 1, "code_window": [ "\tpublic readonly onDidChangeCursorPosition: Event<ICursorPositionChangedEvent> = this._onDidChangeCursorPosition.event;\n", "\n", "\tprivate readonly _onDidChangeCursorSelection: Emitter<ICursorSelectionChangedEvent> = this._register(new Emitter<ICursorSelectionChangedEvent>());\n", "\tpublic readonly onDidChangeCursorSelection: Event<ICursorSelectionChangedEvent> = this._onDidChangeCursorSelection.event;\n", "\n", "\tprivate readonly _onDidLayoutChange: Emitter<editorOptions.EditorLayoutInfo> = this._register(new Emitter<editorOptions.EditorLayoutInfo>());\n", "\tpublic readonly onDidLayoutChange: Event<editorOptions.EditorLayoutInfo> = this._onDidLayoutChange.event;\n", "\n", "\tprotected _editorTextFocus: BooleanEventEmitter = this._register(new BooleanEventEmitter());\n", "\tpublic readonly onDidFocusEditorText: Event<void> = this._editorTextFocus.onDidChangeToTrue;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _onDidAttemptReadOnlyEdit: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidAttemptReadOnlyEdit: Event<void> = this._onDidAttemptReadOnlyEdit.event;\n", "\n" ], "file_path": "src/vs/editor/common/commonCodeEditor.ts", "type": "add", "edit_start_line_idx": 69 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import { QuickOpenModel, QuickOpenEntry, QuickOpenEntryGroup } from 'vs/base/parts/quickopen/browser/quickOpenModel'; import { DataSource } from 'vs/base/parts/quickopen/browser/quickOpenViewer'; suite('QuickOpen', () => { test('QuickOpenModel', () => { const model = new QuickOpenModel(); const entry1 = new QuickOpenEntry(); const entry2 = new QuickOpenEntry(); const entry3 = new QuickOpenEntryGroup(); assert.notEqual(entry1.getId(), entry2.getId()); assert.notEqual(entry2.getId(), entry3.getId()); model.addEntries([entry1, entry2, entry3]); assert.equal(3, model.getEntries().length); model.setEntries([entry1, entry2]); assert.equal(2, model.getEntries().length); entry1.setHidden(true); assert.equal(1, model.getEntries(true).length); assert.equal(entry2, model.getEntries(true)[0]); }); test('QuickOpenDataSource', () => { const model = new QuickOpenModel(); const entry1 = new QuickOpenEntry(); const entry2 = new QuickOpenEntry(); const entry3 = new QuickOpenEntryGroup(); model.addEntries([entry1, entry2, entry3]); const ds = new DataSource(model); assert.equal(entry1.getId(), ds.getId(null, entry1)); assert.equal(true, ds.hasChildren(null, model)); assert.equal(false, ds.hasChildren(null, entry1)); ds.getChildren(null, model).then((children: any[]) => { assert.equal(3, children.length); }); }); });
src/vs/base/parts/quickopen/test/browser/quickopen.test.ts
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017426328849978745, 0.00017271727847401053, 0.0001676685642451048, 0.0001737284183036536, 0.000002282020204802393 ]
{ "id": 1, "code_window": [ "\tpublic readonly onDidChangeCursorPosition: Event<ICursorPositionChangedEvent> = this._onDidChangeCursorPosition.event;\n", "\n", "\tprivate readonly _onDidChangeCursorSelection: Emitter<ICursorSelectionChangedEvent> = this._register(new Emitter<ICursorSelectionChangedEvent>());\n", "\tpublic readonly onDidChangeCursorSelection: Event<ICursorSelectionChangedEvent> = this._onDidChangeCursorSelection.event;\n", "\n", "\tprivate readonly _onDidLayoutChange: Emitter<editorOptions.EditorLayoutInfo> = this._register(new Emitter<editorOptions.EditorLayoutInfo>());\n", "\tpublic readonly onDidLayoutChange: Event<editorOptions.EditorLayoutInfo> = this._onDidLayoutChange.event;\n", "\n", "\tprotected _editorTextFocus: BooleanEventEmitter = this._register(new BooleanEventEmitter());\n", "\tpublic readonly onDidFocusEditorText: Event<void> = this._editorTextFocus.onDidChangeToTrue;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _onDidAttemptReadOnlyEdit: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidAttemptReadOnlyEdit: Event<void> = this._onDidAttemptReadOnlyEdit.event;\n", "\n" ], "file_path": "src/vs/editor/common/commonCodeEditor.ts", "type": "add", "edit_start_line_idx": 69 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "nonempty": "ๅฟ…้ ˆๆ˜ฏ้ž็ฉบ็™ฝๅ€ผใ€‚", "requirestring": "ๅฑฌๆ€ง '{0}' ็‚บๅผทๅˆถ้ …็›ฎไธ”ๅฟ…้ ˆๅฑฌๆ–ผ `string` ้กžๅž‹", "optstring": "ๅฑฌๆ€ง `{0}` ๅฏไปฅ็œ็•ฅๆˆ–ๅฟ…้ ˆๅฑฌๆ–ผ `string` ้กžๅž‹", "vscode.extension.contributes.keybindings.command": "่งธ็™ผๆŒ‰้ต็นซ็ต้—œไฟ‚ๆ™‚ๆ‰€่ฆๅŸท่กŒๅ‘ฝไปค็š„่ญ˜ๅˆฅ็ขผใ€‚", "vscode.extension.contributes.keybindings.key": "ๆŒ‰้ตๆˆ–ๆŒ‰้ต้ †ๅบ (ไปฅๅŠ ่™Ÿๅˆ†้š”ๆŒ‰้ตไธฆไปฅ็ฉบๆ ผๅˆ†้š”้ †ๅบ๏ผŒไพ‹ๅฆ‚ Ctrl+O ๅŠ Ctrl+L L ้€ฒ่กŒๅŒๆญฅ้ธๅ–)ใ€‚", "vscode.extension.contributes.keybindings.mac": "Mac ็‰นๅฎšๆŒ‰้ตๆˆ–ๆŒ‰้ต้ †ๅบใ€‚", "vscode.extension.contributes.keybindings.linux": "Linux ็‰นๅฎšๆŒ‰้ตๆˆ–ๆŒ‰้ต้ †ๅบใ€‚", "vscode.extension.contributes.keybindings.win": "Windows ็‰นๅฎšๆŒ‰้ตๆˆ–ๆŒ‰้ต้ †ๅบใ€‚", "vscode.extension.contributes.keybindings.when": "ๆŒ‰้ต็‚บไฝฟ็”จไธญๆ™‚็š„ๆขไปถใ€‚", "vscode.extension.contributes.keybindings": "ๆไพ›ๆŒ‰้ต็นซ็ต้—œไฟ‚ใ€‚", "invalid.keybindings": "`contributes.{0}` ็„กๆ•ˆ: {1}", "unboundCommands": "ๅ…ถไป–ๅฏ็”จๅ‘ฝไปคๅฆ‚ไธ‹: ", "keybindings.json.title": "ๆŒ‰้ต็นซ็ต้—œไฟ‚็ต„ๆ…‹", "keybindings.json.key": "ๆŒ‰้ตๆˆ–ๆŒ‰้ต้ †ๅบ (ไปฅ็ฉบๆ ผๅˆ†้š”)", "keybindings.json.command": "ๆ‰€่ฆๅŸท่กŒๅ‘ฝไปค็š„ๅ็จฑ", "keybindings.json.when": "ๆŒ‰้ต็‚บไฝฟ็”จไธญๆ™‚็š„ๆขไปถใ€‚", "keybindings.json.args": "่ฆๅ‚ณ้ž่‡ณๅ‘ฝไปคๅŠ ไปฅๅŸท่กŒ็š„ๅผ•ๆ•ธใ€‚", "keyboardConfigurationTitle": "้ต็›ค", "dispatch": "ๆŽงๅˆถๆŒ‰ไธ‹ๆŒ‰้ตๆ™‚็š„ๅˆ†ๆดพ้‚่ผฏ (ไฝฟ็”จ 'code' (ๅปบ่ญฐไฝฟ็”จ) ๆˆ– 'keyCode')ใ€‚", "touchbar.enabled": "ๅ•Ÿ็”จ้ต็›คไธŠ็š„ macOS ่งธๆ‘ธๆฟๆŒ‰้ˆ• (ๅฆ‚ๆžœๅฏ็”จ)ใ€‚" }
i18n/cht/src/vs/workbench/services/keybinding/electron-browser/keybindingService.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0001760164013830945, 0.0001729030627757311, 0.00017106971063185483, 0.00017162307631224394, 0.0000022130238903628197 ]
{ "id": 2, "code_window": [ "\n", "\t\t\tthis.listenersToRemove.push(this.cursor.onDidReachMaxCursorCount(() => {\n", "\t\t\t\tthis._notificationService.warn(nls.localize('cursors.maximum', \"The number of cursors has been limited to {0}.\", Cursor.MAX_CURSOR_COUNT));\n", "\t\t\t}));\n", "\n", "\t\t\tthis.listenersToRemove.push(this.cursor.onDidChange((e: CursorStateChangedEvent) => {\n", "\n", "\t\t\t\tlet positions: Position[] = [];\n", "\t\t\t\tfor (let i = 0, len = e.selections.length; i < len; i++) {\n", "\t\t\t\t\tpositions[i] = e.selections[i].getPosition();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.listenersToRemove.push(this.cursor.onDidAttemptReadOnlyEdit(() => {\n", "\t\t\t\tthis._onDidAttemptReadOnlyEdit.fire(void 0);\n", "\t\t\t}));\n", "\n" ], "file_path": "src/vs/editor/common/commonCodeEditor.ts", "type": "add", "edit_start_line_idx": 970 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./messageController'; import { setDisposableTimeout } from 'vs/base/common/async'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { ICodeEditor, IContentWidget, IContentWidgetPosition, ContentWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IPosition } from 'vs/editor/common/core/position'; import { registerThemingParticipant, HIGH_CONTRAST } from 'vs/platform/theme/common/themeService'; import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry'; import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; export class MessageController implements editorCommon.IEditorContribution { private static readonly _id = 'editor.contrib.messageController'; static MESSAGE_VISIBLE = new RawContextKey<boolean>('messageVisible', false); static get(editor: ICodeEditor): MessageController { return editor.getContribution<MessageController>(MessageController._id); } getId(): string { return MessageController._id; } private _editor: ICodeEditor; private _visible: IContextKey<boolean>; private _messageWidget: MessageWidget; private _messageListeners: IDisposable[] = []; constructor( editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService ) { this._editor = editor; this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService); } dispose(): void { this._visible.reset(); } isVisible() { return this._visible.get(); } showMessage(message: string, position: IPosition): void { alert(message); this._visible.set(true); dispose(this._messageWidget); this._messageListeners = dispose(this._messageListeners); this._messageWidget = new MessageWidget(this._editor, position, message); // close on blur, cursor, model change, dispose this._messageListeners.push(this._editor.onDidBlurEditorText(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeCursorPosition(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidDispose(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeModel(() => this.closeMessage())); // close after 3s this._messageListeners.push(setDisposableTimeout(() => this.closeMessage(), 3000)); // close on mouse move let bounds: Range; this._messageListeners.push(this._editor.onMouseMove(e => { // outside the text area if (!e.target.position) { return; } if (!bounds) { // define bounding box around position and first mouse occurance bounds = new Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1); } else if (!bounds.containsPosition(e.target.position)) { // check if position is still in bounds this.closeMessage(); } })); } closeMessage(): void { this._visible.reset(); this._messageListeners = dispose(this._messageListeners); this._messageListeners.push(MessageWidget.fadeOut(this._messageWidget)); } } const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get); registerEditorCommand(new MessageCommand({ id: 'leaveEditorMessage', precondition: MessageController.MESSAGE_VISIBLE, handler: c => c.closeMessage(), kbOpts: { weight: KeybindingsRegistry.WEIGHT.editorContrib(30), primary: KeyCode.Escape } })); class MessageWidget implements IContentWidget { // Editor.IContentWidget.allowEditorOverflow readonly allowEditorOverflow = true; readonly suppressMouseDown = false; private _editor: ICodeEditor; private _position: IPosition; private _domNode: HTMLDivElement; static fadeOut(messageWidget: MessageWidget): IDisposable { let handle: number; const dispose = () => { messageWidget.dispose(); clearTimeout(handle); messageWidget.getDomNode().removeEventListener('animationend', dispose); }; handle = setTimeout(dispose, 110); messageWidget.getDomNode().addEventListener('animationend', dispose); messageWidget.getDomNode().classList.add('fadeOut'); return { dispose }; } constructor(editor: ICodeEditor, { lineNumber, column }: IPosition, text: string) { this._editor = editor; this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, editorCommon.ScrollType.Smooth); this._position = { lineNumber, column: column - 1 }; this._domNode = document.createElement('div'); this._domNode.classList.add('monaco-editor-overlaymessage'); const message = document.createElement('div'); message.classList.add('message'); message.textContent = text; this._domNode.appendChild(message); const anchor = document.createElement('div'); anchor.classList.add('anchor'); this._domNode.appendChild(anchor); this._editor.addContentWidget(this); this._domNode.classList.add('fadeIn'); } dispose() { this._editor.removeContentWidget(this); } getId(): string { return 'messageoverlay'; } getDomNode(): HTMLElement { return this._domNode; } getPosition(): IContentWidgetPosition { return { position: this._position, preference: [ContentWidgetPositionPreference.ABOVE] }; } } registerEditorContribution(MessageController); registerThemingParticipant((theme, collector) => { let border = theme.getColor(inputValidationInfoBorder); if (border) { let borderWidth = theme.type === 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}; }`); } let background = theme.getColor(inputValidationInfoBackground); if (background) { collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { background-color: ${background}; }`); } });
src/vs/editor/contrib/message/messageController.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0005395441548898816, 0.00020680708985310048, 0.00016654396313242614, 0.00017174471577163786, 0.00010442984785186127 ]
{ "id": 2, "code_window": [ "\n", "\t\t\tthis.listenersToRemove.push(this.cursor.onDidReachMaxCursorCount(() => {\n", "\t\t\t\tthis._notificationService.warn(nls.localize('cursors.maximum', \"The number of cursors has been limited to {0}.\", Cursor.MAX_CURSOR_COUNT));\n", "\t\t\t}));\n", "\n", "\t\t\tthis.listenersToRemove.push(this.cursor.onDidChange((e: CursorStateChangedEvent) => {\n", "\n", "\t\t\t\tlet positions: Position[] = [];\n", "\t\t\t\tfor (let i = 0, len = e.selections.length; i < len; i++) {\n", "\t\t\t\t\tpositions[i] = e.selections[i].getPosition();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.listenersToRemove.push(this.cursor.onDidAttemptReadOnlyEdit(() => {\n", "\t\t\t\tthis._onDidAttemptReadOnlyEdit.fire(void 0);\n", "\t\t\t}));\n", "\n" ], "file_path": "src/vs/editor/common/commonCodeEditor.ts", "type": "add", "edit_start_line_idx": 970 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "label": "Explorer", "canNotResolve": "Arbeitsbereichsordner kann nicht aufgelรถst werden." }
i18n/deu/src/vs/workbench/parts/files/browser/views/explorerDecorationsProvider.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0001739778817864135, 0.0001739778817864135, 0.0001739778817864135, 0.0001739778817864135, 0 ]
{ "id": 2, "code_window": [ "\n", "\t\t\tthis.listenersToRemove.push(this.cursor.onDidReachMaxCursorCount(() => {\n", "\t\t\t\tthis._notificationService.warn(nls.localize('cursors.maximum', \"The number of cursors has been limited to {0}.\", Cursor.MAX_CURSOR_COUNT));\n", "\t\t\t}));\n", "\n", "\t\t\tthis.listenersToRemove.push(this.cursor.onDidChange((e: CursorStateChangedEvent) => {\n", "\n", "\t\t\t\tlet positions: Position[] = [];\n", "\t\t\t\tfor (let i = 0, len = e.selections.length; i < len; i++) {\n", "\t\t\t\t\tpositions[i] = e.selections[i].getPosition();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.listenersToRemove.push(this.cursor.onDidAttemptReadOnlyEdit(() => {\n", "\t\t\t\tthis._onDidAttemptReadOnlyEdit.fire(void 0);\n", "\t\t\t}));\n", "\n" ], "file_path": "src/vs/editor/common/commonCodeEditor.ts", "type": "add", "edit_start_line_idx": 970 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "userGuide": "Verwenden Sie die Aktionen in der Editor-Symbolleiste, um Ihre ร„nderungen rรผckgรคngig zu machen oder den Inhalt auf dem Datentrรคger mit Ihren ร„nderungen zu รผberschreiben.", "staleSaveError": "Fehler beim Speichern von \"{0}\": Der Inhalt auf dem Datentrรคger ist neuer. Vergleichen Sie Ihre Version mit der Version auf dem Datentrรคger.", "retry": "Wiederholen", "discard": "Verwerfen", "readonlySaveErrorAdmin": "Fehler beim Speichern von '{0}': Datei ist schreibgeschรผtzt. 'Als Admin รผberschreiben' auswรคhlen, um den Vorgang als Administrator zu wiederholen. ", "readonlySaveError": "Fehler beim Speichern von '{0}': Datei ist schreibgeschรผtzt. Wรคhlen Sie 'รœberschreiben' aus, um den Schutz aufzuheben.", "permissionDeniedSaveError": "Fehler beim Speichern von '{0}': Unzureichende Zugriffsrechte. Wรคhlen Sie 'Als Admin wiederholen' aus, um den Vorgang als Admin zu wiederholen.", "genericSaveError": "Fehler beim Speichern von \"{0}\": {1}.", "learnMore": "Weitere Informationen", "dontShowAgain": "Nicht mehr anzeigen", "compareChanges": "Vergleichen", "saveConflictDiffLabel": "{0} (auf Datentrรคger) โ†” {1} (in {2}): Speicherkonflikt lรถsen", "overwriteElevated": "Als Admin รผberschreiben...", "saveElevated": "Als Admin wiederholen...", "overwrite": "รœberschreiben" }
i18n/deu/src/vs/workbench/parts/files/electron-browser/saveErrorHandler.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017591321375221014, 0.0001750296214595437, 0.00017352659779135138, 0.00017564908193890005, 0.0000010682613265089458 ]
{ "id": 2, "code_window": [ "\n", "\t\t\tthis.listenersToRemove.push(this.cursor.onDidReachMaxCursorCount(() => {\n", "\t\t\t\tthis._notificationService.warn(nls.localize('cursors.maximum', \"The number of cursors has been limited to {0}.\", Cursor.MAX_CURSOR_COUNT));\n", "\t\t\t}));\n", "\n", "\t\t\tthis.listenersToRemove.push(this.cursor.onDidChange((e: CursorStateChangedEvent) => {\n", "\n", "\t\t\t\tlet positions: Position[] = [];\n", "\t\t\t\tfor (let i = 0, len = e.selections.length; i < len; i++) {\n", "\t\t\t\t\tpositions[i] = e.selections[i].getPosition();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.listenersToRemove.push(this.cursor.onDidAttemptReadOnlyEdit(() => {\n", "\t\t\t\tthis._onDidAttemptReadOnlyEdit.fire(void 0);\n", "\t\t\t}));\n", "\n" ], "file_path": "src/vs/editor/common/commonCodeEditor.ts", "type": "add", "edit_start_line_idx": 970 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "displayName": "Nozioni di base del linguaggio Docker", "description": "Offre la sottolineatura delle sintassi e il match delle parentesi nei file Docker." }
i18n/ita/extensions/docker/package.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.000176395449670963, 0.0001736190461087972, 0.00017084262799471617, 0.0001736190461087972, 0.000002776410838123411 ]
{ "id": 3, "code_window": [ "\n", "\tprivate readonly _onDidReachMaxCursorCount: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidReachMaxCursorCount: Event<void> = this._onDidReachMaxCursorCount.event;\n", "\n", "\tprivate readonly _onDidChange: Emitter<CursorStateChangedEvent> = this._register(new Emitter<CursorStateChangedEvent>());\n", "\tpublic readonly onDidChange: Event<CursorStateChangedEvent> = this._onDidChange.event;\n", "\n", "\tprivate readonly _configuration: editorCommon.IConfiguration;\n", "\tprivate readonly _model: ITextModel;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _onDidAttemptReadOnlyEdit: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidAttemptReadOnlyEdit: Event<void> = this._onDidAttemptReadOnlyEdit.event;\n", "\n" ], "file_path": "src/vs/editor/common/controller/cursor.ts", "type": "add", "edit_start_line_idx": 94 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./messageController'; import { setDisposableTimeout } from 'vs/base/common/async'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { ICodeEditor, IContentWidget, IContentWidgetPosition, ContentWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IPosition } from 'vs/editor/common/core/position'; import { registerThemingParticipant, HIGH_CONTRAST } from 'vs/platform/theme/common/themeService'; import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry'; import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; export class MessageController implements editorCommon.IEditorContribution { private static readonly _id = 'editor.contrib.messageController'; static MESSAGE_VISIBLE = new RawContextKey<boolean>('messageVisible', false); static get(editor: ICodeEditor): MessageController { return editor.getContribution<MessageController>(MessageController._id); } getId(): string { return MessageController._id; } private _editor: ICodeEditor; private _visible: IContextKey<boolean>; private _messageWidget: MessageWidget; private _messageListeners: IDisposable[] = []; constructor( editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService ) { this._editor = editor; this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService); } dispose(): void { this._visible.reset(); } isVisible() { return this._visible.get(); } showMessage(message: string, position: IPosition): void { alert(message); this._visible.set(true); dispose(this._messageWidget); this._messageListeners = dispose(this._messageListeners); this._messageWidget = new MessageWidget(this._editor, position, message); // close on blur, cursor, model change, dispose this._messageListeners.push(this._editor.onDidBlurEditorText(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeCursorPosition(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidDispose(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeModel(() => this.closeMessage())); // close after 3s this._messageListeners.push(setDisposableTimeout(() => this.closeMessage(), 3000)); // close on mouse move let bounds: Range; this._messageListeners.push(this._editor.onMouseMove(e => { // outside the text area if (!e.target.position) { return; } if (!bounds) { // define bounding box around position and first mouse occurance bounds = new Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1); } else if (!bounds.containsPosition(e.target.position)) { // check if position is still in bounds this.closeMessage(); } })); } closeMessage(): void { this._visible.reset(); this._messageListeners = dispose(this._messageListeners); this._messageListeners.push(MessageWidget.fadeOut(this._messageWidget)); } } const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get); registerEditorCommand(new MessageCommand({ id: 'leaveEditorMessage', precondition: MessageController.MESSAGE_VISIBLE, handler: c => c.closeMessage(), kbOpts: { weight: KeybindingsRegistry.WEIGHT.editorContrib(30), primary: KeyCode.Escape } })); class MessageWidget implements IContentWidget { // Editor.IContentWidget.allowEditorOverflow readonly allowEditorOverflow = true; readonly suppressMouseDown = false; private _editor: ICodeEditor; private _position: IPosition; private _domNode: HTMLDivElement; static fadeOut(messageWidget: MessageWidget): IDisposable { let handle: number; const dispose = () => { messageWidget.dispose(); clearTimeout(handle); messageWidget.getDomNode().removeEventListener('animationend', dispose); }; handle = setTimeout(dispose, 110); messageWidget.getDomNode().addEventListener('animationend', dispose); messageWidget.getDomNode().classList.add('fadeOut'); return { dispose }; } constructor(editor: ICodeEditor, { lineNumber, column }: IPosition, text: string) { this._editor = editor; this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, editorCommon.ScrollType.Smooth); this._position = { lineNumber, column: column - 1 }; this._domNode = document.createElement('div'); this._domNode.classList.add('monaco-editor-overlaymessage'); const message = document.createElement('div'); message.classList.add('message'); message.textContent = text; this._domNode.appendChild(message); const anchor = document.createElement('div'); anchor.classList.add('anchor'); this._domNode.appendChild(anchor); this._editor.addContentWidget(this); this._domNode.classList.add('fadeIn'); } dispose() { this._editor.removeContentWidget(this); } getId(): string { return 'messageoverlay'; } getDomNode(): HTMLElement { return this._domNode; } getPosition(): IContentWidgetPosition { return { position: this._position, preference: [ContentWidgetPositionPreference.ABOVE] }; } } registerEditorContribution(MessageController); registerThemingParticipant((theme, collector) => { let border = theme.getColor(inputValidationInfoBorder); if (border) { let borderWidth = theme.type === 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}; }`); } let background = theme.getColor(inputValidationInfoBackground); if (background) { collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { background-color: ${background}; }`); } });
src/vs/editor/contrib/message/messageController.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.9185797572135925, 0.04854312166571617, 0.0001609174651093781, 0.0001723326276987791, 0.2050696611404419 ]
{ "id": 3, "code_window": [ "\n", "\tprivate readonly _onDidReachMaxCursorCount: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidReachMaxCursorCount: Event<void> = this._onDidReachMaxCursorCount.event;\n", "\n", "\tprivate readonly _onDidChange: Emitter<CursorStateChangedEvent> = this._register(new Emitter<CursorStateChangedEvent>());\n", "\tpublic readonly onDidChange: Event<CursorStateChangedEvent> = this._onDidChange.event;\n", "\n", "\tprivate readonly _configuration: editorCommon.IConfiguration;\n", "\tprivate readonly _model: ITextModel;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _onDidAttemptReadOnlyEdit: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidAttemptReadOnlyEdit: Event<void> = this._onDidAttemptReadOnlyEdit.event;\n", "\n" ], "file_path": "src/vs/editor/common/controller/cursor.ts", "type": "add", "edit_start_line_idx": 94 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "displayName": "JavaScript ์–ธ์–ด ๊ธฐ๋ณธ", "description": "JavaScript ํŒŒ์ผ์—์„œ ์ฝ”๋“œ ์กฐ๊ฐ, ๊ตฌ๋ฌธ ๊ฐ•์กฐ ํ‘œ์‹œ, ๊ด„ํ˜ธ ์ผ์น˜ ๋ฐ ์ ‘๊ธฐ๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค." }
i18n/kor/extensions/javascript/package.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017679014126770198, 0.0001750967639964074, 0.00017340337217319757, 0.0001750967639964074, 0.000001693384547252208 ]
{ "id": 3, "code_window": [ "\n", "\tprivate readonly _onDidReachMaxCursorCount: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidReachMaxCursorCount: Event<void> = this._onDidReachMaxCursorCount.event;\n", "\n", "\tprivate readonly _onDidChange: Emitter<CursorStateChangedEvent> = this._register(new Emitter<CursorStateChangedEvent>());\n", "\tpublic readonly onDidChange: Event<CursorStateChangedEvent> = this._onDidChange.event;\n", "\n", "\tprivate readonly _configuration: editorCommon.IConfiguration;\n", "\tprivate readonly _model: ITextModel;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _onDidAttemptReadOnlyEdit: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidAttemptReadOnlyEdit: Event<void> = this._onDidAttemptReadOnlyEdit.event;\n", "\n" ], "file_path": "src/vs/editor/common/controller/cursor.ts", "type": "add", "edit_start_line_idx": 94 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "vscode.extension.contributes.configuration.title": "่จญๅฎš็š„ๆ‘˜่ฆใ€‚ๆญคๆจ™็ฑคๅฐ‡ๆœƒๅœจ่จญๅฎšๆช”ไธญไฝœ็‚บๅˆ†้š”่จป่งฃไฝฟ็”จใ€‚", "vscode.extension.contributes.configuration.properties": "็ต„ๆ…‹ๅฑฌๆ€ง็š„ๆ่ฟฐใ€‚", "scope.window.description": "่ฆ–็ช—็‰นๅฎš็ต„ๆ…‹๏ผŒๅฏๅœจไฝฟ็”จ่€…ๆˆ–ๅทฅไฝœๅ€่จญๅฎšไธญไบˆไปฅ่จญๅฎšใ€‚", "scope.resource.description": "่ณ‡ๆบ็‰นๅฎš่จญๅฎš๏ผŒๅฏๅœจไฝฟ็”จ่€…ใ€ๅทฅไฝœๅ€ๆˆ–่ณ‡ๆ–™ๅคพ่จญๅฎšไธญไบˆไปฅ่จญๅฎšใ€‚", "scope.description": "็ต„ๆ…‹้ฉ็”จ็š„็ฏ„ๅœใ€‚ๅฏ็”จ็š„็ฏ„ๅœ็‚บใ€Œ่ฆ–็ช—ใ€ๅ’Œใ€Œ่ณ‡ๆบใ€ใ€‚", "vscode.extension.contributes.defaultConfiguration": "ไพ่ชž่จ€่ฒข็ป้ ่จญ็ทจ่ผฏๅ™จ็ต„ๆ…‹่จญๅฎšใ€‚", "vscode.extension.contributes.configuration": "ๆไพ›็ต„ๆ…‹่จญๅฎšใ€‚", "invalid.title": "'configuration.title' ๅฟ…้ ˆๆ˜ฏๅญ—ไธฒ", "invalid.properties": "'configuration.properties' ๅฟ…้ ˆๆ˜ฏ็‰ฉไปถ", "invalid.allOf": "'configuration.allOf' ๅทฒๅ–ไปฃ่€Œไธๆ‡‰ๅ†ไฝฟ็”จใ€‚่ซ‹ๆ”น็‚บๅฐ‡ๅคšๅ€‹็ต„ๆ…‹ๅ€ๆฎตไฝœ็‚บ้™ฃๅˆ—๏ผŒๅ‚ณ้ž่‡ณใ€Œ็ต„ๆ…‹ใ€่ฒข็ป้ปžใ€‚", "workspaceConfig.folders.description": "่ฆ่ผ‰ๅ…ฅๅทฅไฝœๅ€ไน‹่ณ‡ๆ–™ๅคพ็š„ๆธ…ๅ–ฎใ€‚", "workspaceConfig.path.description": "ๆช”ๆกˆ่ทฏๅพ‘๏ผŒไพ‹ๅฆ‚ `/root/folderA` ๆˆ– `./folderA` ๅณ็‚บๆœƒๅฐๅทฅไฝœๅ€ๆช”ๆกˆไฝ็ฝฎ่งฃๆž็š„็›ธ้—œ่ทฏๅพ‘ใ€‚", "workspaceConfig.name.description": "่ณ‡ๆ–™ๅคพ็š„้ธ็”จๅ็จฑใ€‚", "workspaceConfig.uri.description": "่ณ‡ๆ–™ๅคพ็š„ URI", "workspaceConfig.settings.description": "ๅทฅไฝœๅ€่จญๅฎš", "workspaceConfig.launch.description": "ๅทฅไฝœๅ€ๅ•Ÿๅ‹•้…็ฝฎ", "workspaceConfig.extensions.description": "ๅทฅไฝœๅ€ๅปถไผธๆจก็ต„", "unknownWorkspaceProperty": "ๆœช็Ÿฅ็š„ๅทฅไฝœๅ€็ต„ๆ…‹ๅฑฌๆ€ง" }
i18n/cht/src/vs/workbench/services/configuration/common/configurationExtensionPoint.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017579988343641162, 0.0001693663652986288, 0.0001651956554269418, 0.00016710357158444822, 0.000004615380476025166 ]
{ "id": 3, "code_window": [ "\n", "\tprivate readonly _onDidReachMaxCursorCount: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidReachMaxCursorCount: Event<void> = this._onDidReachMaxCursorCount.event;\n", "\n", "\tprivate readonly _onDidChange: Emitter<CursorStateChangedEvent> = this._register(new Emitter<CursorStateChangedEvent>());\n", "\tpublic readonly onDidChange: Event<CursorStateChangedEvent> = this._onDidChange.event;\n", "\n", "\tprivate readonly _configuration: editorCommon.IConfiguration;\n", "\tprivate readonly _model: ITextModel;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _onDidAttemptReadOnlyEdit: Emitter<void> = this._register(new Emitter<void>());\n", "\tpublic readonly onDidAttemptReadOnlyEdit: Event<void> = this._onDidAttemptReadOnlyEdit.event;\n", "\n" ], "file_path": "src/vs/editor/common/controller/cursor.ts", "type": "add", "edit_start_line_idx": 94 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "too many submodules": "El repositorio ' {0} ' tiene {1} submรณdulos que no se abrirรกn automรกticamente. Usted todavรญa puede abrir cada archivo individualmente.", "no repositories": "No hay repositorios disponibles", "pick repo": "Elija un repositorio" }
i18n/esn/extensions/git/out/model.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017668027430772781, 0.00017471876344643533, 0.00017275725258514285, 0.00017471876344643533, 0.0000019615108612924814 ]
{ "id": 4, "code_window": [ "\t\t}\n", "\n", "\t\tif (this._configuration.editor.readOnly) {\n", "\t\t\t// All the remaining handlers will try to edit the model,\n", "\t\t\t// but we cannot edit when read only...\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst oldState = new CursorModelState(this._model, this);\n", "\t\tlet cursorChangeReason = CursorChangeReason.NotSet;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._onDidAttemptReadOnlyEdit.fire(void 0);\n" ], "file_path": "src/vs/editor/common/controller/cursor.ts", "type": "add", "edit_start_line_idx": 468 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./messageController'; import { setDisposableTimeout } from 'vs/base/common/async'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { ICodeEditor, IContentWidget, IContentWidgetPosition, ContentWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IPosition } from 'vs/editor/common/core/position'; import { registerThemingParticipant, HIGH_CONTRAST } from 'vs/platform/theme/common/themeService'; import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry'; import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; export class MessageController implements editorCommon.IEditorContribution { private static readonly _id = 'editor.contrib.messageController'; static MESSAGE_VISIBLE = new RawContextKey<boolean>('messageVisible', false); static get(editor: ICodeEditor): MessageController { return editor.getContribution<MessageController>(MessageController._id); } getId(): string { return MessageController._id; } private _editor: ICodeEditor; private _visible: IContextKey<boolean>; private _messageWidget: MessageWidget; private _messageListeners: IDisposable[] = []; constructor( editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService ) { this._editor = editor; this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService); } dispose(): void { this._visible.reset(); } isVisible() { return this._visible.get(); } showMessage(message: string, position: IPosition): void { alert(message); this._visible.set(true); dispose(this._messageWidget); this._messageListeners = dispose(this._messageListeners); this._messageWidget = new MessageWidget(this._editor, position, message); // close on blur, cursor, model change, dispose this._messageListeners.push(this._editor.onDidBlurEditorText(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeCursorPosition(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidDispose(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeModel(() => this.closeMessage())); // close after 3s this._messageListeners.push(setDisposableTimeout(() => this.closeMessage(), 3000)); // close on mouse move let bounds: Range; this._messageListeners.push(this._editor.onMouseMove(e => { // outside the text area if (!e.target.position) { return; } if (!bounds) { // define bounding box around position and first mouse occurance bounds = new Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1); } else if (!bounds.containsPosition(e.target.position)) { // check if position is still in bounds this.closeMessage(); } })); } closeMessage(): void { this._visible.reset(); this._messageListeners = dispose(this._messageListeners); this._messageListeners.push(MessageWidget.fadeOut(this._messageWidget)); } } const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get); registerEditorCommand(new MessageCommand({ id: 'leaveEditorMessage', precondition: MessageController.MESSAGE_VISIBLE, handler: c => c.closeMessage(), kbOpts: { weight: KeybindingsRegistry.WEIGHT.editorContrib(30), primary: KeyCode.Escape } })); class MessageWidget implements IContentWidget { // Editor.IContentWidget.allowEditorOverflow readonly allowEditorOverflow = true; readonly suppressMouseDown = false; private _editor: ICodeEditor; private _position: IPosition; private _domNode: HTMLDivElement; static fadeOut(messageWidget: MessageWidget): IDisposable { let handle: number; const dispose = () => { messageWidget.dispose(); clearTimeout(handle); messageWidget.getDomNode().removeEventListener('animationend', dispose); }; handle = setTimeout(dispose, 110); messageWidget.getDomNode().addEventListener('animationend', dispose); messageWidget.getDomNode().classList.add('fadeOut'); return { dispose }; } constructor(editor: ICodeEditor, { lineNumber, column }: IPosition, text: string) { this._editor = editor; this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, editorCommon.ScrollType.Smooth); this._position = { lineNumber, column: column - 1 }; this._domNode = document.createElement('div'); this._domNode.classList.add('monaco-editor-overlaymessage'); const message = document.createElement('div'); message.classList.add('message'); message.textContent = text; this._domNode.appendChild(message); const anchor = document.createElement('div'); anchor.classList.add('anchor'); this._domNode.appendChild(anchor); this._editor.addContentWidget(this); this._domNode.classList.add('fadeIn'); } dispose() { this._editor.removeContentWidget(this); } getId(): string { return 'messageoverlay'; } getDomNode(): HTMLElement { return this._domNode; } getPosition(): IContentWidgetPosition { return { position: this._position, preference: [ContentWidgetPositionPreference.ABOVE] }; } } registerEditorContribution(MessageController); registerThemingParticipant((theme, collector) => { let border = theme.getColor(inputValidationInfoBorder); if (border) { let borderWidth = theme.type === 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}; }`); } let background = theme.getColor(inputValidationInfoBackground); if (background) { collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { background-color: ${background}; }`); } });
src/vs/editor/contrib/message/messageController.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0001776644930941984, 0.00017196452245116234, 0.00016413661069236696, 0.00017110577027779073, 0.000002895344096032204 ]
{ "id": 4, "code_window": [ "\t\t}\n", "\n", "\t\tif (this._configuration.editor.readOnly) {\n", "\t\t\t// All the remaining handlers will try to edit the model,\n", "\t\t\t// but we cannot edit when read only...\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst oldState = new CursorModelState(this._model, this);\n", "\t\tlet cursorChangeReason = CursorChangeReason.NotSet;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._onDidAttemptReadOnlyEdit.fire(void 0);\n" ], "file_path": "src/vs/editor/common/controller/cursor.ts", "type": "add", "edit_start_line_idx": 468 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "htmlserver.name": "ะฏะทั‹ะบะพะฒะพะน ัะตั€ะฒะตั€ HTML", "folding.start": "ะะฐั‡ะฐะปะพ ัะฒะพั€ะฐั‡ะธะฒะฐะตะผะพะณะพ ั€ะตะณะธะพะฝะฐ", "folding.end": "ะžะบะพะฝั‡ะฐะฝะธะต ัะฒะพั€ะฐั‡ะธะฒะฐะตะผะพะณะพ ั€ะตะณะธะพะฝะฐ" }
i18n/rus/extensions/html/client/out/htmlMain.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017380826466251165, 0.00017266118084080517, 0.00017151411157101393, 0.00017266118084080517, 0.0000011470765457488596 ]
{ "id": 4, "code_window": [ "\t\t}\n", "\n", "\t\tif (this._configuration.editor.readOnly) {\n", "\t\t\t// All the remaining handlers will try to edit the model,\n", "\t\t\t// but we cannot edit when read only...\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst oldState = new CursorModelState(this._model, this);\n", "\t\tlet cursorChangeReason = CursorChangeReason.NotSet;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._onDidAttemptReadOnlyEdit.fire(void 0);\n" ], "file_path": "src/vs/editor/common/controller/cursor.ts", "type": "add", "edit_start_line_idx": 468 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "modesContentHover.loading": "Yรผkleniyor..." }
i18n/trk/src/vs/editor/contrib/hover/browser/modesContentHover.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017693011614028364, 0.00017693011614028364, 0.00017693011614028364, 0.00017693011614028364, 0 ]
{ "id": 4, "code_window": [ "\t\t}\n", "\n", "\t\tif (this._configuration.editor.readOnly) {\n", "\t\t\t// All the remaining handlers will try to edit the model,\n", "\t\t\t// but we cannot edit when read only...\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst oldState = new CursorModelState(this._model, this);\n", "\t\tlet cursorChangeReason = CursorChangeReason.NotSet;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._onDidAttemptReadOnlyEdit.fire(void 0);\n" ], "file_path": "src/vs/editor/common/controller/cursor.ts", "type": "add", "edit_start_line_idx": 468 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "open": "Abrir", "index modified": "รndice Modificado", "modified": "Modificado", "index added": "รndice Adicionado", "index deleted": "รndice Excluรญdo", "deleted": "Excluรญdo", "index renamed": "รndice Renomeado", "index copied": "รndice Copiado", "untracked": "Nรฃo acompanhado", "ignored": "Ignorado", "both deleted": "Ambos Excluรญdos", "added by us": "Adicionado Por Nรณs", "deleted by them": "Excluรญdo Por Eles", "added by them": "Adicionado Por Eles", "deleted by us": "Excluรญdo Por Nรณs", "both added": "Ambos adicionados", "both modified": "Ambos Modificados", "commitMessage": "Mensagem (tecle {0} para confirmar)", "commit": "Confirmar", "merge changes": "Mesclar Alteraรงรตes", "staged changes": "Alteraรงรตes em Etapas", "changes": "Alteraรงรตes", "commitMessageCountdown": "{0} caracteres restantes na linha atual", "commitMessageWarning": "{0} caracteres sobre {1} na linha atual", "neveragain": "Nรฃo mostrar novamente", "huge": "O repositรณrio git em '{0}' tem muitas atualizaรงรตes ativas, somente um subconjunto de funcionalidades do Git serรก habilitado." }
i18n/ptb/extensions/git/out/repository.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.000177509878994897, 0.0001755330158630386, 0.00017404841491952538, 0.00017528687021695077, 0.0000014859131169941975 ]
{ "id": 5, "code_window": [ "\n", "'use strict';\n", "\n", "import 'vs/css!./messageController';\n", "import { setDisposableTimeout } from 'vs/base/common/async';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "import * as nls from 'vs/nls';\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 8 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./messageController'; import { setDisposableTimeout } from 'vs/base/common/async'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { ICodeEditor, IContentWidget, IContentWidgetPosition, ContentWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IPosition } from 'vs/editor/common/core/position'; import { registerThemingParticipant, HIGH_CONTRAST } from 'vs/platform/theme/common/themeService'; import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry'; import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; export class MessageController implements editorCommon.IEditorContribution { private static readonly _id = 'editor.contrib.messageController'; static MESSAGE_VISIBLE = new RawContextKey<boolean>('messageVisible', false); static get(editor: ICodeEditor): MessageController { return editor.getContribution<MessageController>(MessageController._id); } getId(): string { return MessageController._id; } private _editor: ICodeEditor; private _visible: IContextKey<boolean>; private _messageWidget: MessageWidget; private _messageListeners: IDisposable[] = []; constructor( editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService ) { this._editor = editor; this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService); } dispose(): void { this._visible.reset(); } isVisible() { return this._visible.get(); } showMessage(message: string, position: IPosition): void { alert(message); this._visible.set(true); dispose(this._messageWidget); this._messageListeners = dispose(this._messageListeners); this._messageWidget = new MessageWidget(this._editor, position, message); // close on blur, cursor, model change, dispose this._messageListeners.push(this._editor.onDidBlurEditorText(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeCursorPosition(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidDispose(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeModel(() => this.closeMessage())); // close after 3s this._messageListeners.push(setDisposableTimeout(() => this.closeMessage(), 3000)); // close on mouse move let bounds: Range; this._messageListeners.push(this._editor.onMouseMove(e => { // outside the text area if (!e.target.position) { return; } if (!bounds) { // define bounding box around position and first mouse occurance bounds = new Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1); } else if (!bounds.containsPosition(e.target.position)) { // check if position is still in bounds this.closeMessage(); } })); } closeMessage(): void { this._visible.reset(); this._messageListeners = dispose(this._messageListeners); this._messageListeners.push(MessageWidget.fadeOut(this._messageWidget)); } } const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get); registerEditorCommand(new MessageCommand({ id: 'leaveEditorMessage', precondition: MessageController.MESSAGE_VISIBLE, handler: c => c.closeMessage(), kbOpts: { weight: KeybindingsRegistry.WEIGHT.editorContrib(30), primary: KeyCode.Escape } })); class MessageWidget implements IContentWidget { // Editor.IContentWidget.allowEditorOverflow readonly allowEditorOverflow = true; readonly suppressMouseDown = false; private _editor: ICodeEditor; private _position: IPosition; private _domNode: HTMLDivElement; static fadeOut(messageWidget: MessageWidget): IDisposable { let handle: number; const dispose = () => { messageWidget.dispose(); clearTimeout(handle); messageWidget.getDomNode().removeEventListener('animationend', dispose); }; handle = setTimeout(dispose, 110); messageWidget.getDomNode().addEventListener('animationend', dispose); messageWidget.getDomNode().classList.add('fadeOut'); return { dispose }; } constructor(editor: ICodeEditor, { lineNumber, column }: IPosition, text: string) { this._editor = editor; this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, editorCommon.ScrollType.Smooth); this._position = { lineNumber, column: column - 1 }; this._domNode = document.createElement('div'); this._domNode.classList.add('monaco-editor-overlaymessage'); const message = document.createElement('div'); message.classList.add('message'); message.textContent = text; this._domNode.appendChild(message); const anchor = document.createElement('div'); anchor.classList.add('anchor'); this._domNode.appendChild(anchor); this._editor.addContentWidget(this); this._domNode.classList.add('fadeIn'); } dispose() { this._editor.removeContentWidget(this); } getId(): string { return 'messageoverlay'; } getDomNode(): HTMLElement { return this._domNode; } getPosition(): IContentWidgetPosition { return { position: this._position, preference: [ContentWidgetPositionPreference.ABOVE] }; } } registerEditorContribution(MessageController); registerThemingParticipant((theme, collector) => { let border = theme.getColor(inputValidationInfoBorder); if (border) { let borderWidth = theme.type === 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}; }`); } let background = theme.getColor(inputValidationInfoBackground); if (background) { collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { background-color: ${background}; }`); } });
src/vs/editor/contrib/message/messageController.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.6340039968490601, 0.033820949494838715, 0.00016422834596596658, 0.00018680820357985795, 0.14146719872951508 ]
{ "id": 5, "code_window": [ "\n", "'use strict';\n", "\n", "import 'vs/css!./messageController';\n", "import { setDisposableTimeout } from 'vs/base/common/async';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "import * as nls from 'vs/nls';\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 8 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "displayName": "Monokai Dimmed ใƒ†ใƒผใƒž", "description": "Visual Studio Code ใฎ Monokai dimmed ใƒ†ใƒผใƒž" }
i18n/jpn/extensions/theme-monokai-dimmed/package.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.000175014793057926, 0.0001747979549691081, 0.00017458113143220544, 0.0001747979549691081, 2.1683081286028028e-7 ]
{ "id": 5, "code_window": [ "\n", "'use strict';\n", "\n", "import 'vs/css!./messageController';\n", "import { setDisposableTimeout } from 'vs/base/common/async';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "import * as nls from 'vs/nls';\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 8 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "openRawDefaultSettings": "Abrir Configuraciรณn Predeterminada Raw", "openGlobalSettings": "Abrir configuraciรณn de usuario", "openGlobalKeybindings": "Abrir mรฉtodos abreviados de teclado", "openGlobalKeybindingsFile": "Abrir el archivo de mรฉtodos abreviados de teclado", "openWorkspaceSettings": "Abrir configuraciรณn del รกrea de trabajo", "openFolderSettings": "Abrir Configuraciรณn de carpeta", "configureLanguageBasedSettings": "Configurar opciones especรญficas del lenguaje...", "languageDescriptionConfigured": "({0})", "pickLanguage": "Seleccionar lenguaje" }
i18n/esn/src/vs/workbench/parts/preferences/browser/preferencesActions.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017316313460469246, 0.0001705362374195829, 0.00016790934023447335, 0.0001705362374195829, 0.0000026268971851095557 ]
{ "id": 5, "code_window": [ "\n", "'use strict';\n", "\n", "import 'vs/css!./messageController';\n", "import { setDisposableTimeout } from 'vs/base/common/async';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "import * as nls from 'vs/nls';\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 8 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "action.showContextMenu.label": "ใ‚จใƒ‡ใ‚ฃใ‚ฟใƒผใฎใ‚ณใƒณใƒ†ใ‚ญใ‚นใƒˆ ใƒกใƒ‹ใƒฅใƒผใฎ่กจ็คบ" }
i18n/jpn/src/vs/editor/contrib/contextmenu/browser/contextmenu.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017191395454574376, 0.00017191395454574376, 0.00017191395454574376, 0.00017191395454574376, 0 ]
{ "id": 6, "code_window": [ "import { setDisposableTimeout } from 'vs/base/common/async';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n", "import { IDisposable, dispose } from 'vs/base/common/lifecycle';\n", "import { alert } from 'vs/base/browser/ui/aria/aria';\n", "import { Range } from 'vs/editor/common/core/range';\n", "import * as editorCommon from 'vs/editor/common/editorCommon';\n", "import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions';\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "replace", "edit_start_line_idx": 10 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Event, Emitter } from 'vs/base/common/event'; import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle'; import { TPromise } from 'vs/base/common/winjs.base'; import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IContextKey, IContextKeyServiceTarget, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { CommonEditorConfiguration } from 'vs/editor/common/config/commonEditorConfig'; import { Cursor, CursorStateChangedEvent } from 'vs/editor/common/controller/cursor'; import { CursorColumns, ICursors, CursorConfiguration } from 'vs/editor/common/controller/cursorCommon'; import { Position, IPosition } from 'vs/editor/common/core/position'; import { Range, IRange } from 'vs/editor/common/core/range'; import { Selection, ISelection } from 'vs/editor/common/core/selection'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { ViewModel } from 'vs/editor/common/viewModel/viewModelImpl'; import { hash } from 'vs/base/common/hash'; import { IModelContentChangedEvent, IModelDecorationsChangedEvent, IModelLanguageChangedEvent, IModelOptionsChangedEvent, IModelLanguageConfigurationChangedEvent } from 'vs/editor/common/model/textModelEvents'; import * as editorOptions from 'vs/editor/common/config/editorOptions'; import { ICursorPositionChangedEvent, ICursorSelectionChangedEvent } from 'vs/editor/common/controller/cursorEvents'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { VerticalRevealType } from 'vs/editor/common/view/viewEvents'; import { ModelDecorationOptions } from 'vs/editor/common/model/textModel'; import { IEditorWhitespace } from 'vs/editor/common/viewLayout/whitespaceComputer'; import * as modes from 'vs/editor/common/modes'; import { Schemas } from 'vs/base/common/network'; import { ITextModel, EndOfLinePreference, IIdentifiedSingleEditOperation, IModelDecorationsChangeAccessor, IModelDecoration, IModelDeltaDecoration, IModelDecorationOptions } from 'vs/editor/common/model'; import { INotificationService } from 'vs/platform/notification/common/notification'; let EDITOR_ID = 0; export abstract class CommonCodeEditor extends Disposable { private readonly _onDidDispose: Emitter<void> = this._register(new Emitter<void>()); public readonly onDidDispose: Event<void> = this._onDidDispose.event; private readonly _onDidChangeModelContent: Emitter<IModelContentChangedEvent> = this._register(new Emitter<IModelContentChangedEvent>()); public readonly onDidChangeModelContent: Event<IModelContentChangedEvent> = this._onDidChangeModelContent.event; private readonly _onDidChangeModelLanguage: Emitter<IModelLanguageChangedEvent> = this._register(new Emitter<IModelLanguageChangedEvent>()); public readonly onDidChangeModelLanguage: Event<IModelLanguageChangedEvent> = this._onDidChangeModelLanguage.event; private readonly _onDidChangeModelLanguageConfiguration: Emitter<IModelLanguageConfigurationChangedEvent> = this._register(new Emitter<IModelLanguageConfigurationChangedEvent>()); public readonly onDidChangeModelLanguageConfiguration: Event<IModelLanguageConfigurationChangedEvent> = this._onDidChangeModelLanguageConfiguration.event; private readonly _onDidChangeModelOptions: Emitter<IModelOptionsChangedEvent> = this._register(new Emitter<IModelOptionsChangedEvent>()); public readonly onDidChangeModelOptions: Event<IModelOptionsChangedEvent> = this._onDidChangeModelOptions.event; private readonly _onDidChangeModelDecorations: Emitter<IModelDecorationsChangedEvent> = this._register(new Emitter<IModelDecorationsChangedEvent>()); public readonly onDidChangeModelDecorations: Event<IModelDecorationsChangedEvent> = this._onDidChangeModelDecorations.event; private readonly _onDidChangeConfiguration: Emitter<editorOptions.IConfigurationChangedEvent> = this._register(new Emitter<editorOptions.IConfigurationChangedEvent>()); public readonly onDidChangeConfiguration: Event<editorOptions.IConfigurationChangedEvent> = this._onDidChangeConfiguration.event; protected readonly _onDidChangeModel: Emitter<editorCommon.IModelChangedEvent> = this._register(new Emitter<editorCommon.IModelChangedEvent>()); public readonly onDidChangeModel: Event<editorCommon.IModelChangedEvent> = this._onDidChangeModel.event; private readonly _onDidChangeCursorPosition: Emitter<ICursorPositionChangedEvent> = this._register(new Emitter<ICursorPositionChangedEvent>()); public readonly onDidChangeCursorPosition: Event<ICursorPositionChangedEvent> = this._onDidChangeCursorPosition.event; private readonly _onDidChangeCursorSelection: Emitter<ICursorSelectionChangedEvent> = this._register(new Emitter<ICursorSelectionChangedEvent>()); public readonly onDidChangeCursorSelection: Event<ICursorSelectionChangedEvent> = this._onDidChangeCursorSelection.event; private readonly _onDidLayoutChange: Emitter<editorOptions.EditorLayoutInfo> = this._register(new Emitter<editorOptions.EditorLayoutInfo>()); public readonly onDidLayoutChange: Event<editorOptions.EditorLayoutInfo> = this._onDidLayoutChange.event; protected _editorTextFocus: BooleanEventEmitter = this._register(new BooleanEventEmitter()); public readonly onDidFocusEditorText: Event<void> = this._editorTextFocus.onDidChangeToTrue; public readonly onDidBlurEditorText: Event<void> = this._editorTextFocus.onDidChangeToFalse; protected _editorFocus: BooleanEventEmitter = this._register(new BooleanEventEmitter()); public readonly onDidFocusEditor: Event<void> = this._editorFocus.onDidChangeToTrue; public readonly onDidBlurEditor: Event<void> = this._editorFocus.onDidChangeToFalse; private readonly _onWillType: Emitter<string> = this._register(new Emitter<string>()); public readonly onWillType = this._onWillType.event; private readonly _onDidType: Emitter<string> = this._register(new Emitter<string>()); public readonly onDidType = this._onDidType.event; private readonly _onDidPaste: Emitter<Range> = this._register(new Emitter<Range>()); public readonly onDidPaste = this._onDidPaste.event; public readonly isSimpleWidget: boolean; protected readonly domElement: IContextKeyServiceTarget; protected readonly id: number; protected readonly _configuration: CommonEditorConfiguration; protected _contributions: { [key: string]: editorCommon.IEditorContribution; }; protected _actions: { [key: string]: editorCommon.IEditorAction; }; // --- Members logically associated to a model protected model: ITextModel; protected listenersToRemove: IDisposable[]; protected hasView: boolean; protected viewModel: ViewModel; protected cursor: Cursor; protected readonly _instantiationService: IInstantiationService; protected readonly _contextKeyService: IContextKeyService; protected readonly _notificationService: INotificationService; /** * map from "parent" decoration type to live decoration ids. */ private _decorationTypeKeysToIds: { [decorationTypeKey: string]: string[] }; private _decorationTypeSubtypes: { [decorationTypeKey: string]: { [subtype: string]: boolean } }; constructor( domElement: IContextKeyServiceTarget, options: editorOptions.IEditorOptions, isSimpleWidget: boolean, instantiationService: IInstantiationService, contextKeyService: IContextKeyService, notificationService: INotificationService, ) { super(); this.domElement = domElement; this.id = (++EDITOR_ID); this._decorationTypeKeysToIds = {}; this._decorationTypeSubtypes = {}; this.isSimpleWidget = isSimpleWidget; options = options || {}; this._configuration = this._register(this._createConfiguration(options)); this._register(this._configuration.onDidChange((e) => { this._onDidChangeConfiguration.fire(e); if (e.layoutInfo) { this._onDidLayoutChange.fire(this._configuration.editor.layoutInfo); } })); this._contextKeyService = this._register(contextKeyService.createScoped(this.domElement)); this._notificationService = notificationService; this._register(new EditorContextKeysManager(this, this._contextKeyService)); this._register(new EditorModeContext(this, this._contextKeyService)); this._instantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService])); this._attachModel(null); this._contributions = {}; this._actions = {}; } protected abstract _createConfiguration(options: editorOptions.IEditorOptions): CommonEditorConfiguration; public getId(): string { return this.getEditorType() + ':' + this.id; } public getEditorType(): string { return editorCommon.EditorType.ICodeEditor; } public dispose(): void { let keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { let contributionId = keys[i]; this._contributions[contributionId].dispose(); } this._contributions = {}; // editor actions don't need to be disposed this._actions = {}; this._removeDecorationTypes(); this._postDetachModelCleanup(this._detachModel()); this._onDidDispose.fire(); super.dispose(); } public invokeWithinContext<T>(fn: (accessor: ServicesAccessor) => T): T { return this._instantiationService.invokeFunction(fn); } public updateOptions(newOptions: editorOptions.IEditorOptions): void { this._configuration.updateOptions(newOptions); } public getConfiguration(): editorOptions.InternalEditorOptions { return this._configuration.editor; } public getRawConfiguration(): editorOptions.IEditorOptions { return this._configuration.getRawOptions(); } public getValue(options: { preserveBOM: boolean; lineEnding: string; } = null): string { if (this.model) { let preserveBOM: boolean = (options && options.preserveBOM) ? true : false; let eolPreference = EndOfLinePreference.TextDefined; if (options && options.lineEnding && options.lineEnding === '\n') { eolPreference = EndOfLinePreference.LF; } else if (options && options.lineEnding && options.lineEnding === '\r\n') { eolPreference = EndOfLinePreference.CRLF; } return this.model.getValue(eolPreference, preserveBOM); } return ''; } public setValue(newValue: string): void { if (this.model) { this.model.setValue(newValue); } } public getModel(): ITextModel { return this.model; } public setModel(model: ITextModel = null): void { if (this.model === model) { // Current model is the new model return; } let detachedModel = this._detachModel(); this._attachModel(model); let e: editorCommon.IModelChangedEvent = { oldModelUrl: detachedModel ? detachedModel.uri : null, newModelUrl: model ? model.uri : null }; this._removeDecorationTypes(); this._onDidChangeModel.fire(e); this._postDetachModelCleanup(detachedModel); } private _removeDecorationTypes(): void { this._decorationTypeKeysToIds = {}; if (this._decorationTypeSubtypes) { for (let decorationType in this._decorationTypeSubtypes) { let subTypes = this._decorationTypeSubtypes[decorationType]; for (let subType in subTypes) { this._removeDecorationType(decorationType + '-' + subType); } } this._decorationTypeSubtypes = {}; } } public getVisibleRanges(): Range[] { if (!this.hasView) { return []; } return this.viewModel.getVisibleRanges(); } public getWhitespaces(): IEditorWhitespace[] { if (!this.hasView) { return []; } return this.viewModel.viewLayout.getWhitespaces(); } protected _getVerticalOffsetForPosition(modelLineNumber: number, modelColumn: number): number { let modelPosition = this.model.validatePosition({ lineNumber: modelLineNumber, column: modelColumn }); let viewPosition = this.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition); return this.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber); } public getTopForLineNumber(lineNumber: number): number { if (!this.hasView) { return -1; } return this._getVerticalOffsetForPosition(lineNumber, 1); } public getTopForPosition(lineNumber: number, column: number): number { if (!this.hasView) { return -1; } return this._getVerticalOffsetForPosition(lineNumber, column); } public setHiddenAreas(ranges: IRange[]): void { if (this.viewModel) { this.viewModel.setHiddenAreas(ranges.map(r => Range.lift(r))); } } public getVisibleColumnFromPosition(rawPosition: IPosition): number { if (!this.model) { return rawPosition.column; } let position = this.model.validatePosition(rawPosition); let tabSize = this.model.getOptions().tabSize; return CursorColumns.visibleColumnFromColumn(this.model.getLineContent(position.lineNumber), position.column, tabSize) + 1; } public getPosition(): Position { if (!this.cursor) { return null; } return this.cursor.getPosition().clone(); } public setPosition(position: IPosition): void { if (!this.cursor) { return; } if (!Position.isIPosition(position)) { throw new Error('Invalid arguments'); } this.cursor.setSelections('api', [{ selectionStartLineNumber: position.lineNumber, selectionStartColumn: position.column, positionLineNumber: position.lineNumber, positionColumn: position.column }]); } private _sendRevealRange(modelRange: Range, verticalType: VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType): void { if (!this.model || !this.cursor) { return; } if (!Range.isIRange(modelRange)) { throw new Error('Invalid arguments'); } const validatedModelRange = this.model.validateRange(modelRange); const viewRange = this.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange); this.cursor.emitCursorRevealRange(viewRange, verticalType, revealHorizontal, scrollType); } public revealLine(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLine(lineNumber, VerticalRevealType.Simple, scrollType); } public revealLineInCenter(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLine(lineNumber, VerticalRevealType.Center, scrollType); } public revealLineInCenterIfOutsideViewport(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLine(lineNumber, VerticalRevealType.CenterIfOutsideViewport, scrollType); } private _revealLine(lineNumber: number, revealType: VerticalRevealType, scrollType: editorCommon.ScrollType): void { if (typeof lineNumber !== 'number') { throw new Error('Invalid arguments'); } this._sendRevealRange( new Range(lineNumber, 1, lineNumber, 1), revealType, false, scrollType ); } public revealPosition(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealPosition( position, VerticalRevealType.Simple, true, scrollType ); } public revealPositionInCenter(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealPosition( position, VerticalRevealType.Center, true, scrollType ); } public revealPositionInCenterIfOutsideViewport(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealPosition( position, VerticalRevealType.CenterIfOutsideViewport, true, scrollType ); } private _revealPosition(position: IPosition, verticalType: VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType): void { if (!Position.isIPosition(position)) { throw new Error('Invalid arguments'); } this._sendRevealRange( new Range(position.lineNumber, position.column, position.lineNumber, position.column), verticalType, revealHorizontal, scrollType ); } public getSelection(): Selection { if (!this.cursor) { return null; } return this.cursor.getSelection().clone(); } public getSelections(): Selection[] { if (!this.cursor) { return null; } let selections = this.cursor.getSelections(); let result: Selection[] = []; for (let i = 0, len = selections.length; i < len; i++) { result[i] = selections[i].clone(); } return result; } public setSelection(range: IRange): void; public setSelection(editorRange: Range): void; public setSelection(selection: ISelection): void; public setSelection(editorSelection: Selection): void; public setSelection(something: any): void { let isSelection = Selection.isISelection(something); let isRange = Range.isIRange(something); if (!isSelection && !isRange) { throw new Error('Invalid arguments'); } if (isSelection) { this._setSelectionImpl(<ISelection>something); } else if (isRange) { // act as if it was an IRange let selection: ISelection = { selectionStartLineNumber: something.startLineNumber, selectionStartColumn: something.startColumn, positionLineNumber: something.endLineNumber, positionColumn: something.endColumn }; this._setSelectionImpl(selection); } } private _setSelectionImpl(sel: ISelection): void { if (!this.cursor) { return; } let selection = new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn); this.cursor.setSelections('api', [selection]); } public revealLines(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLines( startLineNumber, endLineNumber, VerticalRevealType.Simple, scrollType ); } public revealLinesInCenter(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLines( startLineNumber, endLineNumber, VerticalRevealType.Center, scrollType ); } public revealLinesInCenterIfOutsideViewport(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLines( startLineNumber, endLineNumber, VerticalRevealType.CenterIfOutsideViewport, scrollType ); } private _revealLines(startLineNumber: number, endLineNumber: number, verticalType: VerticalRevealType, scrollType: editorCommon.ScrollType): void { if (typeof startLineNumber !== 'number' || typeof endLineNumber !== 'number') { throw new Error('Invalid arguments'); } this._sendRevealRange( new Range(startLineNumber, 1, endLineNumber, 1), verticalType, false, scrollType ); } public revealRange(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth, revealVerticalInCenter: boolean = false, revealHorizontal: boolean = true): void { this._revealRange( range, revealVerticalInCenter ? VerticalRevealType.Center : VerticalRevealType.Simple, revealHorizontal, scrollType ); } public revealRangeInCenter(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealRange( range, VerticalRevealType.Center, true, scrollType ); } public revealRangeInCenterIfOutsideViewport(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealRange( range, VerticalRevealType.CenterIfOutsideViewport, true, scrollType ); } public revealRangeAtTop(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealRange( range, VerticalRevealType.Top, true, scrollType ); } private _revealRange(range: IRange, verticalType: VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType): void { if (!Range.isIRange(range)) { throw new Error('Invalid arguments'); } this._sendRevealRange( Range.lift(range), verticalType, revealHorizontal, scrollType ); } public setSelections(ranges: ISelection[]): void { if (!this.cursor) { return; } if (!ranges || ranges.length === 0) { throw new Error('Invalid arguments'); } for (let i = 0, len = ranges.length; i < len; i++) { if (!Selection.isISelection(ranges[i])) { throw new Error('Invalid arguments'); } } this.cursor.setSelections('api', ranges); } public getScrollWidth(): number { if (!this.hasView) { return -1; } return this.viewModel.viewLayout.getScrollWidth(); } public getScrollLeft(): number { if (!this.hasView) { return -1; } return this.viewModel.viewLayout.getCurrentScrollLeft(); } public getScrollHeight(): number { if (!this.hasView) { return -1; } return this.viewModel.viewLayout.getScrollHeight(); } public getScrollTop(): number { if (!this.hasView) { return -1; } return this.viewModel.viewLayout.getCurrentScrollTop(); } public setScrollLeft(newScrollLeft: number): void { if (!this.hasView) { return; } if (typeof newScrollLeft !== 'number') { throw new Error('Invalid arguments'); } this.viewModel.viewLayout.setScrollPositionNow({ scrollLeft: newScrollLeft }); } public setScrollTop(newScrollTop: number): void { if (!this.hasView) { return; } if (typeof newScrollTop !== 'number') { throw new Error('Invalid arguments'); } this.viewModel.viewLayout.setScrollPositionNow({ scrollTop: newScrollTop }); } public setScrollPosition(position: editorCommon.INewScrollPosition): void { if (!this.hasView) { return; } this.viewModel.viewLayout.setScrollPositionNow(position); } public saveViewState(): editorCommon.ICodeEditorViewState { if (!this.cursor || !this.hasView) { return null; } const contributionsState: { [key: string]: any } = {}; const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const id = keys[i]; const contribution = this._contributions[id]; if (typeof contribution.saveViewState === 'function') { contributionsState[id] = contribution.saveViewState(); } } const cursorState = this.cursor.saveState(); const viewState = this.viewModel.saveState(); return { cursorState: cursorState, viewState: viewState, contributionsState: contributionsState }; } public restoreViewState(s: editorCommon.ICodeEditorViewState): void { if (!this.cursor || !this.hasView) { return; } if (s && s.cursorState && s.viewState) { let codeEditorState = <editorCommon.ICodeEditorViewState>s; let cursorState = <any>codeEditorState.cursorState; if (Array.isArray(cursorState)) { this.cursor.restoreState(<editorCommon.ICursorState[]>cursorState); } else { // Backwards compatibility this.cursor.restoreState([<editorCommon.ICursorState>cursorState]); } let contributionsState = s.contributionsState || {}; let keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { let id = keys[i]; let contribution = this._contributions[id]; if (typeof contribution.restoreViewState === 'function') { contribution.restoreViewState(contributionsState[id]); } } } } public onVisible(): void { } public onHide(): void { } public abstract layout(dimension?: editorCommon.IDimension): void; public abstract focus(): void; public abstract isFocused(): boolean; public abstract hasWidgetFocus(): boolean; public getContribution<T extends editorCommon.IEditorContribution>(id: string): T { return <T>(this._contributions[id] || null); } public getActions(): editorCommon.IEditorAction[] { let result: editorCommon.IEditorAction[] = []; let keys = Object.keys(this._actions); for (let i = 0, len = keys.length; i < len; i++) { let id = keys[i]; result.push(this._actions[id]); } return result; } public getSupportedActions(): editorCommon.IEditorAction[] { let result = this.getActions(); result = result.filter(action => action.isSupported()); return result; } public getAction(id: string): editorCommon.IEditorAction { return this._actions[id] || null; } public trigger(source: string, handlerId: string, payload: any): void { 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; } const startPosition = this.cursor.getSelection().getStartPosition(); this.cursor.trigger(source, handlerId, payload); const endPosition = this.cursor.getSelection().getStartPosition(); if (source === 'keyboard') { this._onDidPaste.fire( new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column) ); } return; } const action = this.getAction(handlerId); if (action) { TPromise.as(action.run()).then(null, onUnexpectedError); return; } if (!this.cursor) { return; } if (this._triggerEditorCommand(source, handlerId, payload)) { return; } this.cursor.trigger(source, handlerId, payload); } protected abstract _triggerEditorCommand(source: string, handlerId: string, payload: any): boolean; public _getCursors(): ICursors { return this.cursor; } public _getCursorConfiguration(): CursorConfiguration { return this.cursor.context.config; } public pushUndoStop(): boolean { if (!this.model) { return false; } if (this._configuration.editor.readOnly) { // read only editor => sorry! return false; } this.model.pushStackElement(); return true; } public executeEdits(source: string, edits: IIdentifiedSingleEditOperation[], endCursorState?: Selection[]): boolean { 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, () => { return endCursorState ? endCursorState : null; }); if (endCursorState) { this.cursor.setSelections(source, endCursorState); } return true; } public executeCommand(source: string, command: editorCommon.ICommand): void { if (!this.cursor) { return; } this.cursor.trigger(source, editorCommon.Handler.ExecuteCommand, command); } public executeCommands(source: string, commands: editorCommon.ICommand[]): void { if (!this.cursor) { return; } this.cursor.trigger(source, editorCommon.Handler.ExecuteCommands, commands); } public changeDecorations(callback: (changeAccessor: IModelDecorationsChangeAccessor) => any): any { 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); } public getLineDecorations(lineNumber: number): IModelDecoration[] { if (!this.model) { return null; } return this.model.getLineDecorations(lineNumber, this.id, this._configuration.editor.readOnly); } public deltaDecorations(oldDecorations: string[], newDecorations: IModelDeltaDecoration[]): string[] { if (!this.model) { return []; } if (oldDecorations.length === 0 && newDecorations.length === 0) { return oldDecorations; } return this.model.deltaDecorations(oldDecorations, newDecorations, this.id); } public setDecorations(decorationTypeKey: string, decorationOptions: editorCommon.IDecorationOptions[]): void { let newDecorationsSubTypes: { [key: string]: boolean } = {}; let oldDecorationsSubTypes = this._decorationTypeSubtypes[decorationTypeKey] || {}; this._decorationTypeSubtypes[decorationTypeKey] = newDecorationsSubTypes; let newModelDecorations: IModelDeltaDecoration[] = []; for (let decorationOption of decorationOptions) { let 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 let subType = 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; } let 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 (let subType in oldDecorationsSubTypes) { if (!newDecorationsSubTypes[subType]) { this._removeDecorationType(decorationTypeKey + '-' + subType); } } // update all decorations let oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey] || []; this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationsIds, newModelDecorations); } public setDecorationsFast(decorationTypeKey: string, ranges: IRange[]): void { // remove decoration sub types that are no longer used, deregister decoration type if necessary let oldDecorationsSubTypes = this._decorationTypeSubtypes[decorationTypeKey] || {}; for (let subType in oldDecorationsSubTypes) { this._removeDecorationType(decorationTypeKey + '-' + subType); } this._decorationTypeSubtypes[decorationTypeKey] = {}; const opts = ModelDecorationOptions.createDynamic(this._resolveDecorationOptions(decorationTypeKey, false)); let newModelDecorations: IModelDeltaDecoration[] = new Array<IModelDeltaDecoration>(ranges.length); for (let i = 0, len = ranges.length; i < len; i++) { newModelDecorations[i] = { range: ranges[i], options: opts }; } // update all decorations let oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey] || []; this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationsIds, newModelDecorations); } public removeDecorations(decorationTypeKey: string): void { // remove decorations for type and sub type let 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]; } } public getLayoutInfo(): editorOptions.EditorLayoutInfo { return this._configuration.editor.layoutInfo; } protected _attachModel(model: ITextModel): void { 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 ViewModel(this.id, this._configuration, this.model, (callback) => this._scheduleAtNextAnimationFrame(callback)); this.listenersToRemove.push(this.model.onDidChangeDecorations((e) => this._onDidChangeModelDecorations.fire(e))); this.listenersToRemove.push(this.model.onDidChangeLanguage((e) => { if (!this.model) { return; } this.domElement.setAttribute('data-mode-id', this.model.getLanguageIdentifier().language); this._onDidChangeModelLanguage.fire(e); })); this.listenersToRemove.push(this.model.onDidChangeLanguageConfiguration((e) => this._onDidChangeModelLanguageConfiguration.fire(e))); this.listenersToRemove.push(this.model.onDidChangeContent((e) => this._onDidChangeModelContent.fire(e))); this.listenersToRemove.push(this.model.onDidChangeOptions((e) => this._onDidChangeModelOptions.fire(e))); // Someone might destroy the model from under the editor, so prevent any exceptions by setting a null model this.listenersToRemove.push(this.model.onWillDispose(() => this.setModel(null))); this.cursor = new Cursor( this._configuration, this.model, this.viewModel ); this._createView(); this.listenersToRemove.push(this.cursor.onDidReachMaxCursorCount(() => { this._notificationService.warn(nls.localize('cursors.maximum', "The number of cursors has been limited to {0}.", Cursor.MAX_CURSOR_COUNT)); })); this.listenersToRemove.push(this.cursor.onDidChange((e: CursorStateChangedEvent) => { let positions: Position[] = []; for (let i = 0, len = e.selections.length; i < len; i++) { positions[i] = e.selections[i].getPosition(); } const e1: ICursorPositionChangedEvent = { position: positions[0], secondaryPositions: positions.slice(1), reason: e.reason, source: e.source }; this._onDidChangeCursorPosition.fire(e1); const e2: ICursorSelectionChangedEvent = { selection: e.selections[0], secondarySelections: e.selections.slice(1), source: e.source, reason: e.reason }; this._onDidChangeCursorSelection.fire(e2); })); } else { this.hasView = false; } } protected abstract _scheduleAtNextAnimationFrame(callback: () => void): IDisposable; protected abstract _createView(): void; protected _postDetachModelCleanup(detachedModel: ITextModel): void { if (detachedModel) { detachedModel.removeAllDecorationsWithOwnerId(this.id); } } protected _detachModel(): ITextModel { if (this.model) { this.model.onBeforeDetached(); } this.hasView = false; this.listenersToRemove = dispose(this.listenersToRemove); if (this.cursor) { this.cursor.dispose(); this.cursor = null; } if (this.viewModel) { this.viewModel.dispose(); this.viewModel = null; } let result = this.model; this.model = null; this.domElement.removeAttribute('data-mode-id'); return result; } protected abstract _registerDecorationType(key: string, options: editorCommon.IDecorationRenderOptions, parentTypeKey?: string): void; protected abstract _removeDecorationType(key: string): void; protected abstract _resolveDecorationOptions(typeKey: string, writable: boolean): IModelDecorationOptions; /* __GDPR__FRAGMENT__ "EditorTelemetryData" : {} */ public getTelemetryData(): { [key: string]: any; } { return null; } } const enum BooleanEventValue { NotSet, False, True } export class BooleanEventEmitter extends Disposable { private readonly _onDidChangeToTrue: Emitter<void> = this._register(new Emitter<void>()); public readonly onDidChangeToTrue: Event<void> = this._onDidChangeToTrue.event; private readonly _onDidChangeToFalse: Emitter<void> = this._register(new Emitter<void>()); public readonly onDidChangeToFalse: Event<void> = this._onDidChangeToFalse.event; private _value: BooleanEventValue; constructor() { super(); this._value = BooleanEventValue.NotSet; } public setValue(_value: boolean) { let value = (_value ? BooleanEventValue.True : BooleanEventValue.False); if (this._value === value) { return; } this._value = value; if (this._value === BooleanEventValue.True) { this._onDidChangeToTrue.fire(); } else if (this._value === BooleanEventValue.False) { this._onDidChangeToFalse.fire(); } } } class EditorContextKeysManager extends Disposable { private _editor: CommonCodeEditor; private _editorFocus: IContextKey<boolean>; private _textInputFocus: IContextKey<boolean>; private _editorTextFocus: IContextKey<boolean>; private _editorTabMovesFocus: IContextKey<boolean>; private _editorReadonly: IContextKey<boolean>; private _hasMultipleSelections: IContextKey<boolean>; private _hasNonEmptySelection: IContextKey<boolean>; constructor( editor: CommonCodeEditor, contextKeyService: IContextKeyService ) { super(); this._editor = editor; contextKeyService.createKey('editorId', editor.getId()); this._editorFocus = EditorContextKeys.focus.bindTo(contextKeyService); this._textInputFocus = EditorContextKeys.textInputFocus.bindTo(contextKeyService); this._editorTextFocus = EditorContextKeys.editorTextFocus.bindTo(contextKeyService); this._editorTabMovesFocus = EditorContextKeys.tabMovesFocus.bindTo(contextKeyService); this._editorReadonly = EditorContextKeys.readOnly.bindTo(contextKeyService); this._hasMultipleSelections = EditorContextKeys.hasMultipleSelections.bindTo(contextKeyService); this._hasNonEmptySelection = EditorContextKeys.hasNonEmptySelection.bindTo(contextKeyService); this._register(this._editor.onDidChangeConfiguration(() => this._updateFromConfig())); this._register(this._editor.onDidChangeCursorSelection(() => this._updateFromSelection())); this._register(this._editor.onDidFocusEditor(() => this._updateFromFocus())); this._register(this._editor.onDidBlurEditor(() => this._updateFromFocus())); this._register(this._editor.onDidFocusEditorText(() => this._updateFromFocus())); this._register(this._editor.onDidBlurEditorText(() => this._updateFromFocus())); this._updateFromConfig(); this._updateFromSelection(); this._updateFromFocus(); } private _updateFromConfig(): void { let config = this._editor.getConfiguration(); this._editorTabMovesFocus.set(config.tabFocusMode); this._editorReadonly.set(config.readOnly); } private _updateFromSelection(): void { let selections = this._editor.getSelections(); if (!selections) { this._hasMultipleSelections.reset(); this._hasNonEmptySelection.reset(); } else { this._hasMultipleSelections.set(selections.length > 1); this._hasNonEmptySelection.set(selections.some(s => !s.isEmpty())); } } private _updateFromFocus(): void { this._editorFocus.set(this._editor.hasWidgetFocus() && !this._editor.isSimpleWidget); this._editorTextFocus.set(this._editor.isFocused() && !this._editor.isSimpleWidget); this._textInputFocus.set(this._editor.isFocused()); } } export class EditorModeContext extends Disposable { private _editor: CommonCodeEditor; private _langId: IContextKey<string>; private _hasCompletionItemProvider: IContextKey<boolean>; private _hasCodeActionsProvider: IContextKey<boolean>; private _hasCodeLensProvider: IContextKey<boolean>; private _hasDefinitionProvider: IContextKey<boolean>; private _hasImplementationProvider: IContextKey<boolean>; private _hasTypeDefinitionProvider: IContextKey<boolean>; private _hasHoverProvider: IContextKey<boolean>; private _hasDocumentHighlightProvider: IContextKey<boolean>; private _hasDocumentSymbolProvider: IContextKey<boolean>; private _hasReferenceProvider: IContextKey<boolean>; private _hasRenameProvider: IContextKey<boolean>; private _hasDocumentFormattingProvider: IContextKey<boolean>; private _hasDocumentSelectionFormattingProvider: IContextKey<boolean>; private _hasSignatureHelpProvider: IContextKey<boolean>; private _isInWalkThrough: IContextKey<boolean>; constructor( editor: CommonCodeEditor, contextKeyService: IContextKeyService ) { super(); this._editor = editor; this._langId = EditorContextKeys.languageId.bindTo(contextKeyService); this._hasCompletionItemProvider = EditorContextKeys.hasCompletionItemProvider.bindTo(contextKeyService); this._hasCodeActionsProvider = EditorContextKeys.hasCodeActionsProvider.bindTo(contextKeyService); this._hasCodeLensProvider = EditorContextKeys.hasCodeLensProvider.bindTo(contextKeyService); this._hasDefinitionProvider = EditorContextKeys.hasDefinitionProvider.bindTo(contextKeyService); this._hasImplementationProvider = EditorContextKeys.hasImplementationProvider.bindTo(contextKeyService); this._hasTypeDefinitionProvider = EditorContextKeys.hasTypeDefinitionProvider.bindTo(contextKeyService); this._hasHoverProvider = EditorContextKeys.hasHoverProvider.bindTo(contextKeyService); this._hasDocumentHighlightProvider = EditorContextKeys.hasDocumentHighlightProvider.bindTo(contextKeyService); this._hasDocumentSymbolProvider = EditorContextKeys.hasDocumentSymbolProvider.bindTo(contextKeyService); this._hasReferenceProvider = EditorContextKeys.hasReferenceProvider.bindTo(contextKeyService); this._hasRenameProvider = EditorContextKeys.hasRenameProvider.bindTo(contextKeyService); this._hasDocumentFormattingProvider = EditorContextKeys.hasDocumentFormattingProvider.bindTo(contextKeyService); this._hasDocumentSelectionFormattingProvider = EditorContextKeys.hasDocumentSelectionFormattingProvider.bindTo(contextKeyService); this._hasSignatureHelpProvider = EditorContextKeys.hasSignatureHelpProvider.bindTo(contextKeyService); this._isInWalkThrough = EditorContextKeys.isInEmbeddedEditor.bindTo(contextKeyService); const update = () => this._update(); // update when model/mode changes this._register(editor.onDidChangeModel(update)); this._register(editor.onDidChangeModelLanguage(update)); // update when registries change this._register(modes.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(); } dispose() { super.dispose(); } reset() { 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(); } private _update() { const 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 === Schemas.walkThroughSnippet); } }
src/vs/editor/common/commonCodeEditor.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0015725655248388648, 0.00019801068992819637, 0.00016183085972443223, 0.0001709762727841735, 0.00014981174899730831 ]
{ "id": 6, "code_window": [ "import { setDisposableTimeout } from 'vs/base/common/async';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n", "import { IDisposable, dispose } from 'vs/base/common/lifecycle';\n", "import { alert } from 'vs/base/browser/ui/aria/aria';\n", "import { Range } from 'vs/editor/common/core/range';\n", "import * as editorCommon from 'vs/editor/common/editorCommon';\n", "import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions';\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "replace", "edit_start_line_idx": 10 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "smartSelect.grow": "Expandir selecciรณn", "smartSelect.shrink": "Reducir selecciรณn" }
i18n/esn/src/vs/editor/contrib/smartSelect/common/smartSelect.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0001735750847728923, 0.0001735750847728923, 0.0001735750847728923, 0.0001735750847728923, 0 ]
{ "id": 6, "code_window": [ "import { setDisposableTimeout } from 'vs/base/common/async';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n", "import { IDisposable, dispose } from 'vs/base/common/lifecycle';\n", "import { alert } from 'vs/base/browser/ui/aria/aria';\n", "import { Range } from 'vs/editor/common/core/range';\n", "import * as editorCommon from 'vs/editor/common/editorCommon';\n", "import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions';\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "replace", "edit_start_line_idx": 10 }
<svg width="16" height="16" xmlns="http://www.w3.org/2000/svg"><title>Layer 1</title><rect height="3" width="11" y="7" x="3" fill="#424242"/></svg>
src/vs/editor/browser/widget/media/deletion.svg
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017272582044824958, 0.00017272582044824958, 0.00017272582044824958, 0.00017272582044824958, 0 ]
{ "id": 6, "code_window": [ "import { setDisposableTimeout } from 'vs/base/common/async';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n", "import { IDisposable, dispose } from 'vs/base/common/lifecycle';\n", "import { alert } from 'vs/base/browser/ui/aria/aria';\n", "import { Range } from 'vs/editor/common/core/range';\n", "import * as editorCommon from 'vs/editor/common/editorCommon';\n", "import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions';\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "replace", "edit_start_line_idx": 10 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "displayName": "Bases du langage Pug", "description": "Fournit la coloration syntaxique et la correspondance des crochets dans les fichiers Pug." }
i18n/fra/extensions/pug/package.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0001775019190972671, 0.00017532327910885215, 0.0001731446391204372, 0.00017532327910885215, 0.0000021786399884149432 ]
{ "id": 7, "code_window": [ "import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry';\n", "import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';\n", "\n", "export class MessageController implements editorCommon.IEditorContribution {\n", "\n", "\tprivate static readonly _id = 'editor.contrib.messageController';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export class MessageController extends Disposable implements editorCommon.IEditorContribution {\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "replace", "edit_start_line_idx": 22 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Event, Emitter } from 'vs/base/common/event'; import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle'; import { TPromise } from 'vs/base/common/winjs.base'; import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IContextKey, IContextKeyServiceTarget, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { CommonEditorConfiguration } from 'vs/editor/common/config/commonEditorConfig'; import { Cursor, CursorStateChangedEvent } from 'vs/editor/common/controller/cursor'; import { CursorColumns, ICursors, CursorConfiguration } from 'vs/editor/common/controller/cursorCommon'; import { Position, IPosition } from 'vs/editor/common/core/position'; import { Range, IRange } from 'vs/editor/common/core/range'; import { Selection, ISelection } from 'vs/editor/common/core/selection'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { ViewModel } from 'vs/editor/common/viewModel/viewModelImpl'; import { hash } from 'vs/base/common/hash'; import { IModelContentChangedEvent, IModelDecorationsChangedEvent, IModelLanguageChangedEvent, IModelOptionsChangedEvent, IModelLanguageConfigurationChangedEvent } from 'vs/editor/common/model/textModelEvents'; import * as editorOptions from 'vs/editor/common/config/editorOptions'; import { ICursorPositionChangedEvent, ICursorSelectionChangedEvent } from 'vs/editor/common/controller/cursorEvents'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { VerticalRevealType } from 'vs/editor/common/view/viewEvents'; import { ModelDecorationOptions } from 'vs/editor/common/model/textModel'; import { IEditorWhitespace } from 'vs/editor/common/viewLayout/whitespaceComputer'; import * as modes from 'vs/editor/common/modes'; import { Schemas } from 'vs/base/common/network'; import { ITextModel, EndOfLinePreference, IIdentifiedSingleEditOperation, IModelDecorationsChangeAccessor, IModelDecoration, IModelDeltaDecoration, IModelDecorationOptions } from 'vs/editor/common/model'; import { INotificationService } from 'vs/platform/notification/common/notification'; let EDITOR_ID = 0; export abstract class CommonCodeEditor extends Disposable { private readonly _onDidDispose: Emitter<void> = this._register(new Emitter<void>()); public readonly onDidDispose: Event<void> = this._onDidDispose.event; private readonly _onDidChangeModelContent: Emitter<IModelContentChangedEvent> = this._register(new Emitter<IModelContentChangedEvent>()); public readonly onDidChangeModelContent: Event<IModelContentChangedEvent> = this._onDidChangeModelContent.event; private readonly _onDidChangeModelLanguage: Emitter<IModelLanguageChangedEvent> = this._register(new Emitter<IModelLanguageChangedEvent>()); public readonly onDidChangeModelLanguage: Event<IModelLanguageChangedEvent> = this._onDidChangeModelLanguage.event; private readonly _onDidChangeModelLanguageConfiguration: Emitter<IModelLanguageConfigurationChangedEvent> = this._register(new Emitter<IModelLanguageConfigurationChangedEvent>()); public readonly onDidChangeModelLanguageConfiguration: Event<IModelLanguageConfigurationChangedEvent> = this._onDidChangeModelLanguageConfiguration.event; private readonly _onDidChangeModelOptions: Emitter<IModelOptionsChangedEvent> = this._register(new Emitter<IModelOptionsChangedEvent>()); public readonly onDidChangeModelOptions: Event<IModelOptionsChangedEvent> = this._onDidChangeModelOptions.event; private readonly _onDidChangeModelDecorations: Emitter<IModelDecorationsChangedEvent> = this._register(new Emitter<IModelDecorationsChangedEvent>()); public readonly onDidChangeModelDecorations: Event<IModelDecorationsChangedEvent> = this._onDidChangeModelDecorations.event; private readonly _onDidChangeConfiguration: Emitter<editorOptions.IConfigurationChangedEvent> = this._register(new Emitter<editorOptions.IConfigurationChangedEvent>()); public readonly onDidChangeConfiguration: Event<editorOptions.IConfigurationChangedEvent> = this._onDidChangeConfiguration.event; protected readonly _onDidChangeModel: Emitter<editorCommon.IModelChangedEvent> = this._register(new Emitter<editorCommon.IModelChangedEvent>()); public readonly onDidChangeModel: Event<editorCommon.IModelChangedEvent> = this._onDidChangeModel.event; private readonly _onDidChangeCursorPosition: Emitter<ICursorPositionChangedEvent> = this._register(new Emitter<ICursorPositionChangedEvent>()); public readonly onDidChangeCursorPosition: Event<ICursorPositionChangedEvent> = this._onDidChangeCursorPosition.event; private readonly _onDidChangeCursorSelection: Emitter<ICursorSelectionChangedEvent> = this._register(new Emitter<ICursorSelectionChangedEvent>()); public readonly onDidChangeCursorSelection: Event<ICursorSelectionChangedEvent> = this._onDidChangeCursorSelection.event; private readonly _onDidLayoutChange: Emitter<editorOptions.EditorLayoutInfo> = this._register(new Emitter<editorOptions.EditorLayoutInfo>()); public readonly onDidLayoutChange: Event<editorOptions.EditorLayoutInfo> = this._onDidLayoutChange.event; protected _editorTextFocus: BooleanEventEmitter = this._register(new BooleanEventEmitter()); public readonly onDidFocusEditorText: Event<void> = this._editorTextFocus.onDidChangeToTrue; public readonly onDidBlurEditorText: Event<void> = this._editorTextFocus.onDidChangeToFalse; protected _editorFocus: BooleanEventEmitter = this._register(new BooleanEventEmitter()); public readonly onDidFocusEditor: Event<void> = this._editorFocus.onDidChangeToTrue; public readonly onDidBlurEditor: Event<void> = this._editorFocus.onDidChangeToFalse; private readonly _onWillType: Emitter<string> = this._register(new Emitter<string>()); public readonly onWillType = this._onWillType.event; private readonly _onDidType: Emitter<string> = this._register(new Emitter<string>()); public readonly onDidType = this._onDidType.event; private readonly _onDidPaste: Emitter<Range> = this._register(new Emitter<Range>()); public readonly onDidPaste = this._onDidPaste.event; public readonly isSimpleWidget: boolean; protected readonly domElement: IContextKeyServiceTarget; protected readonly id: number; protected readonly _configuration: CommonEditorConfiguration; protected _contributions: { [key: string]: editorCommon.IEditorContribution; }; protected _actions: { [key: string]: editorCommon.IEditorAction; }; // --- Members logically associated to a model protected model: ITextModel; protected listenersToRemove: IDisposable[]; protected hasView: boolean; protected viewModel: ViewModel; protected cursor: Cursor; protected readonly _instantiationService: IInstantiationService; protected readonly _contextKeyService: IContextKeyService; protected readonly _notificationService: INotificationService; /** * map from "parent" decoration type to live decoration ids. */ private _decorationTypeKeysToIds: { [decorationTypeKey: string]: string[] }; private _decorationTypeSubtypes: { [decorationTypeKey: string]: { [subtype: string]: boolean } }; constructor( domElement: IContextKeyServiceTarget, options: editorOptions.IEditorOptions, isSimpleWidget: boolean, instantiationService: IInstantiationService, contextKeyService: IContextKeyService, notificationService: INotificationService, ) { super(); this.domElement = domElement; this.id = (++EDITOR_ID); this._decorationTypeKeysToIds = {}; this._decorationTypeSubtypes = {}; this.isSimpleWidget = isSimpleWidget; options = options || {}; this._configuration = this._register(this._createConfiguration(options)); this._register(this._configuration.onDidChange((e) => { this._onDidChangeConfiguration.fire(e); if (e.layoutInfo) { this._onDidLayoutChange.fire(this._configuration.editor.layoutInfo); } })); this._contextKeyService = this._register(contextKeyService.createScoped(this.domElement)); this._notificationService = notificationService; this._register(new EditorContextKeysManager(this, this._contextKeyService)); this._register(new EditorModeContext(this, this._contextKeyService)); this._instantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService])); this._attachModel(null); this._contributions = {}; this._actions = {}; } protected abstract _createConfiguration(options: editorOptions.IEditorOptions): CommonEditorConfiguration; public getId(): string { return this.getEditorType() + ':' + this.id; } public getEditorType(): string { return editorCommon.EditorType.ICodeEditor; } public dispose(): void { let keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { let contributionId = keys[i]; this._contributions[contributionId].dispose(); } this._contributions = {}; // editor actions don't need to be disposed this._actions = {}; this._removeDecorationTypes(); this._postDetachModelCleanup(this._detachModel()); this._onDidDispose.fire(); super.dispose(); } public invokeWithinContext<T>(fn: (accessor: ServicesAccessor) => T): T { return this._instantiationService.invokeFunction(fn); } public updateOptions(newOptions: editorOptions.IEditorOptions): void { this._configuration.updateOptions(newOptions); } public getConfiguration(): editorOptions.InternalEditorOptions { return this._configuration.editor; } public getRawConfiguration(): editorOptions.IEditorOptions { return this._configuration.getRawOptions(); } public getValue(options: { preserveBOM: boolean; lineEnding: string; } = null): string { if (this.model) { let preserveBOM: boolean = (options && options.preserveBOM) ? true : false; let eolPreference = EndOfLinePreference.TextDefined; if (options && options.lineEnding && options.lineEnding === '\n') { eolPreference = EndOfLinePreference.LF; } else if (options && options.lineEnding && options.lineEnding === '\r\n') { eolPreference = EndOfLinePreference.CRLF; } return this.model.getValue(eolPreference, preserveBOM); } return ''; } public setValue(newValue: string): void { if (this.model) { this.model.setValue(newValue); } } public getModel(): ITextModel { return this.model; } public setModel(model: ITextModel = null): void { if (this.model === model) { // Current model is the new model return; } let detachedModel = this._detachModel(); this._attachModel(model); let e: editorCommon.IModelChangedEvent = { oldModelUrl: detachedModel ? detachedModel.uri : null, newModelUrl: model ? model.uri : null }; this._removeDecorationTypes(); this._onDidChangeModel.fire(e); this._postDetachModelCleanup(detachedModel); } private _removeDecorationTypes(): void { this._decorationTypeKeysToIds = {}; if (this._decorationTypeSubtypes) { for (let decorationType in this._decorationTypeSubtypes) { let subTypes = this._decorationTypeSubtypes[decorationType]; for (let subType in subTypes) { this._removeDecorationType(decorationType + '-' + subType); } } this._decorationTypeSubtypes = {}; } } public getVisibleRanges(): Range[] { if (!this.hasView) { return []; } return this.viewModel.getVisibleRanges(); } public getWhitespaces(): IEditorWhitespace[] { if (!this.hasView) { return []; } return this.viewModel.viewLayout.getWhitespaces(); } protected _getVerticalOffsetForPosition(modelLineNumber: number, modelColumn: number): number { let modelPosition = this.model.validatePosition({ lineNumber: modelLineNumber, column: modelColumn }); let viewPosition = this.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition); return this.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber); } public getTopForLineNumber(lineNumber: number): number { if (!this.hasView) { return -1; } return this._getVerticalOffsetForPosition(lineNumber, 1); } public getTopForPosition(lineNumber: number, column: number): number { if (!this.hasView) { return -1; } return this._getVerticalOffsetForPosition(lineNumber, column); } public setHiddenAreas(ranges: IRange[]): void { if (this.viewModel) { this.viewModel.setHiddenAreas(ranges.map(r => Range.lift(r))); } } public getVisibleColumnFromPosition(rawPosition: IPosition): number { if (!this.model) { return rawPosition.column; } let position = this.model.validatePosition(rawPosition); let tabSize = this.model.getOptions().tabSize; return CursorColumns.visibleColumnFromColumn(this.model.getLineContent(position.lineNumber), position.column, tabSize) + 1; } public getPosition(): Position { if (!this.cursor) { return null; } return this.cursor.getPosition().clone(); } public setPosition(position: IPosition): void { if (!this.cursor) { return; } if (!Position.isIPosition(position)) { throw new Error('Invalid arguments'); } this.cursor.setSelections('api', [{ selectionStartLineNumber: position.lineNumber, selectionStartColumn: position.column, positionLineNumber: position.lineNumber, positionColumn: position.column }]); } private _sendRevealRange(modelRange: Range, verticalType: VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType): void { if (!this.model || !this.cursor) { return; } if (!Range.isIRange(modelRange)) { throw new Error('Invalid arguments'); } const validatedModelRange = this.model.validateRange(modelRange); const viewRange = this.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange); this.cursor.emitCursorRevealRange(viewRange, verticalType, revealHorizontal, scrollType); } public revealLine(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLine(lineNumber, VerticalRevealType.Simple, scrollType); } public revealLineInCenter(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLine(lineNumber, VerticalRevealType.Center, scrollType); } public revealLineInCenterIfOutsideViewport(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLine(lineNumber, VerticalRevealType.CenterIfOutsideViewport, scrollType); } private _revealLine(lineNumber: number, revealType: VerticalRevealType, scrollType: editorCommon.ScrollType): void { if (typeof lineNumber !== 'number') { throw new Error('Invalid arguments'); } this._sendRevealRange( new Range(lineNumber, 1, lineNumber, 1), revealType, false, scrollType ); } public revealPosition(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealPosition( position, VerticalRevealType.Simple, true, scrollType ); } public revealPositionInCenter(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealPosition( position, VerticalRevealType.Center, true, scrollType ); } public revealPositionInCenterIfOutsideViewport(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealPosition( position, VerticalRevealType.CenterIfOutsideViewport, true, scrollType ); } private _revealPosition(position: IPosition, verticalType: VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType): void { if (!Position.isIPosition(position)) { throw new Error('Invalid arguments'); } this._sendRevealRange( new Range(position.lineNumber, position.column, position.lineNumber, position.column), verticalType, revealHorizontal, scrollType ); } public getSelection(): Selection { if (!this.cursor) { return null; } return this.cursor.getSelection().clone(); } public getSelections(): Selection[] { if (!this.cursor) { return null; } let selections = this.cursor.getSelections(); let result: Selection[] = []; for (let i = 0, len = selections.length; i < len; i++) { result[i] = selections[i].clone(); } return result; } public setSelection(range: IRange): void; public setSelection(editorRange: Range): void; public setSelection(selection: ISelection): void; public setSelection(editorSelection: Selection): void; public setSelection(something: any): void { let isSelection = Selection.isISelection(something); let isRange = Range.isIRange(something); if (!isSelection && !isRange) { throw new Error('Invalid arguments'); } if (isSelection) { this._setSelectionImpl(<ISelection>something); } else if (isRange) { // act as if it was an IRange let selection: ISelection = { selectionStartLineNumber: something.startLineNumber, selectionStartColumn: something.startColumn, positionLineNumber: something.endLineNumber, positionColumn: something.endColumn }; this._setSelectionImpl(selection); } } private _setSelectionImpl(sel: ISelection): void { if (!this.cursor) { return; } let selection = new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn); this.cursor.setSelections('api', [selection]); } public revealLines(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLines( startLineNumber, endLineNumber, VerticalRevealType.Simple, scrollType ); } public revealLinesInCenter(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLines( startLineNumber, endLineNumber, VerticalRevealType.Center, scrollType ); } public revealLinesInCenterIfOutsideViewport(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealLines( startLineNumber, endLineNumber, VerticalRevealType.CenterIfOutsideViewport, scrollType ); } private _revealLines(startLineNumber: number, endLineNumber: number, verticalType: VerticalRevealType, scrollType: editorCommon.ScrollType): void { if (typeof startLineNumber !== 'number' || typeof endLineNumber !== 'number') { throw new Error('Invalid arguments'); } this._sendRevealRange( new Range(startLineNumber, 1, endLineNumber, 1), verticalType, false, scrollType ); } public revealRange(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth, revealVerticalInCenter: boolean = false, revealHorizontal: boolean = true): void { this._revealRange( range, revealVerticalInCenter ? VerticalRevealType.Center : VerticalRevealType.Simple, revealHorizontal, scrollType ); } public revealRangeInCenter(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealRange( range, VerticalRevealType.Center, true, scrollType ); } public revealRangeInCenterIfOutsideViewport(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealRange( range, VerticalRevealType.CenterIfOutsideViewport, true, scrollType ); } public revealRangeAtTop(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void { this._revealRange( range, VerticalRevealType.Top, true, scrollType ); } private _revealRange(range: IRange, verticalType: VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType): void { if (!Range.isIRange(range)) { throw new Error('Invalid arguments'); } this._sendRevealRange( Range.lift(range), verticalType, revealHorizontal, scrollType ); } public setSelections(ranges: ISelection[]): void { if (!this.cursor) { return; } if (!ranges || ranges.length === 0) { throw new Error('Invalid arguments'); } for (let i = 0, len = ranges.length; i < len; i++) { if (!Selection.isISelection(ranges[i])) { throw new Error('Invalid arguments'); } } this.cursor.setSelections('api', ranges); } public getScrollWidth(): number { if (!this.hasView) { return -1; } return this.viewModel.viewLayout.getScrollWidth(); } public getScrollLeft(): number { if (!this.hasView) { return -1; } return this.viewModel.viewLayout.getCurrentScrollLeft(); } public getScrollHeight(): number { if (!this.hasView) { return -1; } return this.viewModel.viewLayout.getScrollHeight(); } public getScrollTop(): number { if (!this.hasView) { return -1; } return this.viewModel.viewLayout.getCurrentScrollTop(); } public setScrollLeft(newScrollLeft: number): void { if (!this.hasView) { return; } if (typeof newScrollLeft !== 'number') { throw new Error('Invalid arguments'); } this.viewModel.viewLayout.setScrollPositionNow({ scrollLeft: newScrollLeft }); } public setScrollTop(newScrollTop: number): void { if (!this.hasView) { return; } if (typeof newScrollTop !== 'number') { throw new Error('Invalid arguments'); } this.viewModel.viewLayout.setScrollPositionNow({ scrollTop: newScrollTop }); } public setScrollPosition(position: editorCommon.INewScrollPosition): void { if (!this.hasView) { return; } this.viewModel.viewLayout.setScrollPositionNow(position); } public saveViewState(): editorCommon.ICodeEditorViewState { if (!this.cursor || !this.hasView) { return null; } const contributionsState: { [key: string]: any } = {}; const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const id = keys[i]; const contribution = this._contributions[id]; if (typeof contribution.saveViewState === 'function') { contributionsState[id] = contribution.saveViewState(); } } const cursorState = this.cursor.saveState(); const viewState = this.viewModel.saveState(); return { cursorState: cursorState, viewState: viewState, contributionsState: contributionsState }; } public restoreViewState(s: editorCommon.ICodeEditorViewState): void { if (!this.cursor || !this.hasView) { return; } if (s && s.cursorState && s.viewState) { let codeEditorState = <editorCommon.ICodeEditorViewState>s; let cursorState = <any>codeEditorState.cursorState; if (Array.isArray(cursorState)) { this.cursor.restoreState(<editorCommon.ICursorState[]>cursorState); } else { // Backwards compatibility this.cursor.restoreState([<editorCommon.ICursorState>cursorState]); } let contributionsState = s.contributionsState || {}; let keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { let id = keys[i]; let contribution = this._contributions[id]; if (typeof contribution.restoreViewState === 'function') { contribution.restoreViewState(contributionsState[id]); } } } } public onVisible(): void { } public onHide(): void { } public abstract layout(dimension?: editorCommon.IDimension): void; public abstract focus(): void; public abstract isFocused(): boolean; public abstract hasWidgetFocus(): boolean; public getContribution<T extends editorCommon.IEditorContribution>(id: string): T { return <T>(this._contributions[id] || null); } public getActions(): editorCommon.IEditorAction[] { let result: editorCommon.IEditorAction[] = []; let keys = Object.keys(this._actions); for (let i = 0, len = keys.length; i < len; i++) { let id = keys[i]; result.push(this._actions[id]); } return result; } public getSupportedActions(): editorCommon.IEditorAction[] { let result = this.getActions(); result = result.filter(action => action.isSupported()); return result; } public getAction(id: string): editorCommon.IEditorAction { return this._actions[id] || null; } public trigger(source: string, handlerId: string, payload: any): void { 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; } const startPosition = this.cursor.getSelection().getStartPosition(); this.cursor.trigger(source, handlerId, payload); const endPosition = this.cursor.getSelection().getStartPosition(); if (source === 'keyboard') { this._onDidPaste.fire( new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column) ); } return; } const action = this.getAction(handlerId); if (action) { TPromise.as(action.run()).then(null, onUnexpectedError); return; } if (!this.cursor) { return; } if (this._triggerEditorCommand(source, handlerId, payload)) { return; } this.cursor.trigger(source, handlerId, payload); } protected abstract _triggerEditorCommand(source: string, handlerId: string, payload: any): boolean; public _getCursors(): ICursors { return this.cursor; } public _getCursorConfiguration(): CursorConfiguration { return this.cursor.context.config; } public pushUndoStop(): boolean { if (!this.model) { return false; } if (this._configuration.editor.readOnly) { // read only editor => sorry! return false; } this.model.pushStackElement(); return true; } public executeEdits(source: string, edits: IIdentifiedSingleEditOperation[], endCursorState?: Selection[]): boolean { 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, () => { return endCursorState ? endCursorState : null; }); if (endCursorState) { this.cursor.setSelections(source, endCursorState); } return true; } public executeCommand(source: string, command: editorCommon.ICommand): void { if (!this.cursor) { return; } this.cursor.trigger(source, editorCommon.Handler.ExecuteCommand, command); } public executeCommands(source: string, commands: editorCommon.ICommand[]): void { if (!this.cursor) { return; } this.cursor.trigger(source, editorCommon.Handler.ExecuteCommands, commands); } public changeDecorations(callback: (changeAccessor: IModelDecorationsChangeAccessor) => any): any { 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); } public getLineDecorations(lineNumber: number): IModelDecoration[] { if (!this.model) { return null; } return this.model.getLineDecorations(lineNumber, this.id, this._configuration.editor.readOnly); } public deltaDecorations(oldDecorations: string[], newDecorations: IModelDeltaDecoration[]): string[] { if (!this.model) { return []; } if (oldDecorations.length === 0 && newDecorations.length === 0) { return oldDecorations; } return this.model.deltaDecorations(oldDecorations, newDecorations, this.id); } public setDecorations(decorationTypeKey: string, decorationOptions: editorCommon.IDecorationOptions[]): void { let newDecorationsSubTypes: { [key: string]: boolean } = {}; let oldDecorationsSubTypes = this._decorationTypeSubtypes[decorationTypeKey] || {}; this._decorationTypeSubtypes[decorationTypeKey] = newDecorationsSubTypes; let newModelDecorations: IModelDeltaDecoration[] = []; for (let decorationOption of decorationOptions) { let 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 let subType = 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; } let 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 (let subType in oldDecorationsSubTypes) { if (!newDecorationsSubTypes[subType]) { this._removeDecorationType(decorationTypeKey + '-' + subType); } } // update all decorations let oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey] || []; this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationsIds, newModelDecorations); } public setDecorationsFast(decorationTypeKey: string, ranges: IRange[]): void { // remove decoration sub types that are no longer used, deregister decoration type if necessary let oldDecorationsSubTypes = this._decorationTypeSubtypes[decorationTypeKey] || {}; for (let subType in oldDecorationsSubTypes) { this._removeDecorationType(decorationTypeKey + '-' + subType); } this._decorationTypeSubtypes[decorationTypeKey] = {}; const opts = ModelDecorationOptions.createDynamic(this._resolveDecorationOptions(decorationTypeKey, false)); let newModelDecorations: IModelDeltaDecoration[] = new Array<IModelDeltaDecoration>(ranges.length); for (let i = 0, len = ranges.length; i < len; i++) { newModelDecorations[i] = { range: ranges[i], options: opts }; } // update all decorations let oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey] || []; this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationsIds, newModelDecorations); } public removeDecorations(decorationTypeKey: string): void { // remove decorations for type and sub type let 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]; } } public getLayoutInfo(): editorOptions.EditorLayoutInfo { return this._configuration.editor.layoutInfo; } protected _attachModel(model: ITextModel): void { 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 ViewModel(this.id, this._configuration, this.model, (callback) => this._scheduleAtNextAnimationFrame(callback)); this.listenersToRemove.push(this.model.onDidChangeDecorations((e) => this._onDidChangeModelDecorations.fire(e))); this.listenersToRemove.push(this.model.onDidChangeLanguage((e) => { if (!this.model) { return; } this.domElement.setAttribute('data-mode-id', this.model.getLanguageIdentifier().language); this._onDidChangeModelLanguage.fire(e); })); this.listenersToRemove.push(this.model.onDidChangeLanguageConfiguration((e) => this._onDidChangeModelLanguageConfiguration.fire(e))); this.listenersToRemove.push(this.model.onDidChangeContent((e) => this._onDidChangeModelContent.fire(e))); this.listenersToRemove.push(this.model.onDidChangeOptions((e) => this._onDidChangeModelOptions.fire(e))); // Someone might destroy the model from under the editor, so prevent any exceptions by setting a null model this.listenersToRemove.push(this.model.onWillDispose(() => this.setModel(null))); this.cursor = new Cursor( this._configuration, this.model, this.viewModel ); this._createView(); this.listenersToRemove.push(this.cursor.onDidReachMaxCursorCount(() => { this._notificationService.warn(nls.localize('cursors.maximum', "The number of cursors has been limited to {0}.", Cursor.MAX_CURSOR_COUNT)); })); this.listenersToRemove.push(this.cursor.onDidChange((e: CursorStateChangedEvent) => { let positions: Position[] = []; for (let i = 0, len = e.selections.length; i < len; i++) { positions[i] = e.selections[i].getPosition(); } const e1: ICursorPositionChangedEvent = { position: positions[0], secondaryPositions: positions.slice(1), reason: e.reason, source: e.source }; this._onDidChangeCursorPosition.fire(e1); const e2: ICursorSelectionChangedEvent = { selection: e.selections[0], secondarySelections: e.selections.slice(1), source: e.source, reason: e.reason }; this._onDidChangeCursorSelection.fire(e2); })); } else { this.hasView = false; } } protected abstract _scheduleAtNextAnimationFrame(callback: () => void): IDisposable; protected abstract _createView(): void; protected _postDetachModelCleanup(detachedModel: ITextModel): void { if (detachedModel) { detachedModel.removeAllDecorationsWithOwnerId(this.id); } } protected _detachModel(): ITextModel { if (this.model) { this.model.onBeforeDetached(); } this.hasView = false; this.listenersToRemove = dispose(this.listenersToRemove); if (this.cursor) { this.cursor.dispose(); this.cursor = null; } if (this.viewModel) { this.viewModel.dispose(); this.viewModel = null; } let result = this.model; this.model = null; this.domElement.removeAttribute('data-mode-id'); return result; } protected abstract _registerDecorationType(key: string, options: editorCommon.IDecorationRenderOptions, parentTypeKey?: string): void; protected abstract _removeDecorationType(key: string): void; protected abstract _resolveDecorationOptions(typeKey: string, writable: boolean): IModelDecorationOptions; /* __GDPR__FRAGMENT__ "EditorTelemetryData" : {} */ public getTelemetryData(): { [key: string]: any; } { return null; } } const enum BooleanEventValue { NotSet, False, True } export class BooleanEventEmitter extends Disposable { private readonly _onDidChangeToTrue: Emitter<void> = this._register(new Emitter<void>()); public readonly onDidChangeToTrue: Event<void> = this._onDidChangeToTrue.event; private readonly _onDidChangeToFalse: Emitter<void> = this._register(new Emitter<void>()); public readonly onDidChangeToFalse: Event<void> = this._onDidChangeToFalse.event; private _value: BooleanEventValue; constructor() { super(); this._value = BooleanEventValue.NotSet; } public setValue(_value: boolean) { let value = (_value ? BooleanEventValue.True : BooleanEventValue.False); if (this._value === value) { return; } this._value = value; if (this._value === BooleanEventValue.True) { this._onDidChangeToTrue.fire(); } else if (this._value === BooleanEventValue.False) { this._onDidChangeToFalse.fire(); } } } class EditorContextKeysManager extends Disposable { private _editor: CommonCodeEditor; private _editorFocus: IContextKey<boolean>; private _textInputFocus: IContextKey<boolean>; private _editorTextFocus: IContextKey<boolean>; private _editorTabMovesFocus: IContextKey<boolean>; private _editorReadonly: IContextKey<boolean>; private _hasMultipleSelections: IContextKey<boolean>; private _hasNonEmptySelection: IContextKey<boolean>; constructor( editor: CommonCodeEditor, contextKeyService: IContextKeyService ) { super(); this._editor = editor; contextKeyService.createKey('editorId', editor.getId()); this._editorFocus = EditorContextKeys.focus.bindTo(contextKeyService); this._textInputFocus = EditorContextKeys.textInputFocus.bindTo(contextKeyService); this._editorTextFocus = EditorContextKeys.editorTextFocus.bindTo(contextKeyService); this._editorTabMovesFocus = EditorContextKeys.tabMovesFocus.bindTo(contextKeyService); this._editorReadonly = EditorContextKeys.readOnly.bindTo(contextKeyService); this._hasMultipleSelections = EditorContextKeys.hasMultipleSelections.bindTo(contextKeyService); this._hasNonEmptySelection = EditorContextKeys.hasNonEmptySelection.bindTo(contextKeyService); this._register(this._editor.onDidChangeConfiguration(() => this._updateFromConfig())); this._register(this._editor.onDidChangeCursorSelection(() => this._updateFromSelection())); this._register(this._editor.onDidFocusEditor(() => this._updateFromFocus())); this._register(this._editor.onDidBlurEditor(() => this._updateFromFocus())); this._register(this._editor.onDidFocusEditorText(() => this._updateFromFocus())); this._register(this._editor.onDidBlurEditorText(() => this._updateFromFocus())); this._updateFromConfig(); this._updateFromSelection(); this._updateFromFocus(); } private _updateFromConfig(): void { let config = this._editor.getConfiguration(); this._editorTabMovesFocus.set(config.tabFocusMode); this._editorReadonly.set(config.readOnly); } private _updateFromSelection(): void { let selections = this._editor.getSelections(); if (!selections) { this._hasMultipleSelections.reset(); this._hasNonEmptySelection.reset(); } else { this._hasMultipleSelections.set(selections.length > 1); this._hasNonEmptySelection.set(selections.some(s => !s.isEmpty())); } } private _updateFromFocus(): void { this._editorFocus.set(this._editor.hasWidgetFocus() && !this._editor.isSimpleWidget); this._editorTextFocus.set(this._editor.isFocused() && !this._editor.isSimpleWidget); this._textInputFocus.set(this._editor.isFocused()); } } export class EditorModeContext extends Disposable { private _editor: CommonCodeEditor; private _langId: IContextKey<string>; private _hasCompletionItemProvider: IContextKey<boolean>; private _hasCodeActionsProvider: IContextKey<boolean>; private _hasCodeLensProvider: IContextKey<boolean>; private _hasDefinitionProvider: IContextKey<boolean>; private _hasImplementationProvider: IContextKey<boolean>; private _hasTypeDefinitionProvider: IContextKey<boolean>; private _hasHoverProvider: IContextKey<boolean>; private _hasDocumentHighlightProvider: IContextKey<boolean>; private _hasDocumentSymbolProvider: IContextKey<boolean>; private _hasReferenceProvider: IContextKey<boolean>; private _hasRenameProvider: IContextKey<boolean>; private _hasDocumentFormattingProvider: IContextKey<boolean>; private _hasDocumentSelectionFormattingProvider: IContextKey<boolean>; private _hasSignatureHelpProvider: IContextKey<boolean>; private _isInWalkThrough: IContextKey<boolean>; constructor( editor: CommonCodeEditor, contextKeyService: IContextKeyService ) { super(); this._editor = editor; this._langId = EditorContextKeys.languageId.bindTo(contextKeyService); this._hasCompletionItemProvider = EditorContextKeys.hasCompletionItemProvider.bindTo(contextKeyService); this._hasCodeActionsProvider = EditorContextKeys.hasCodeActionsProvider.bindTo(contextKeyService); this._hasCodeLensProvider = EditorContextKeys.hasCodeLensProvider.bindTo(contextKeyService); this._hasDefinitionProvider = EditorContextKeys.hasDefinitionProvider.bindTo(contextKeyService); this._hasImplementationProvider = EditorContextKeys.hasImplementationProvider.bindTo(contextKeyService); this._hasTypeDefinitionProvider = EditorContextKeys.hasTypeDefinitionProvider.bindTo(contextKeyService); this._hasHoverProvider = EditorContextKeys.hasHoverProvider.bindTo(contextKeyService); this._hasDocumentHighlightProvider = EditorContextKeys.hasDocumentHighlightProvider.bindTo(contextKeyService); this._hasDocumentSymbolProvider = EditorContextKeys.hasDocumentSymbolProvider.bindTo(contextKeyService); this._hasReferenceProvider = EditorContextKeys.hasReferenceProvider.bindTo(contextKeyService); this._hasRenameProvider = EditorContextKeys.hasRenameProvider.bindTo(contextKeyService); this._hasDocumentFormattingProvider = EditorContextKeys.hasDocumentFormattingProvider.bindTo(contextKeyService); this._hasDocumentSelectionFormattingProvider = EditorContextKeys.hasDocumentSelectionFormattingProvider.bindTo(contextKeyService); this._hasSignatureHelpProvider = EditorContextKeys.hasSignatureHelpProvider.bindTo(contextKeyService); this._isInWalkThrough = EditorContextKeys.isInEmbeddedEditor.bindTo(contextKeyService); const update = () => this._update(); // update when model/mode changes this._register(editor.onDidChangeModel(update)); this._register(editor.onDidChangeModelLanguage(update)); // update when registries change this._register(modes.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(); } dispose() { super.dispose(); } reset() { 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(); } private _update() { const 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 === Schemas.walkThroughSnippet); } }
src/vs/editor/common/commonCodeEditor.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0020323735661804676, 0.00019529448763933033, 0.0001626666053198278, 0.00017317949095740914, 0.00017210982332471758 ]
{ "id": 7, "code_window": [ "import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry';\n", "import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';\n", "\n", "export class MessageController implements editorCommon.IEditorContribution {\n", "\n", "\tprivate static readonly _id = 'editor.contrib.messageController';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export class MessageController extends Disposable implements editorCommon.IEditorContribution {\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "replace", "edit_start_line_idx": 22 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { Uri } from 'vscode'; export interface GitUriParams { path: string; ref: string; submoduleOf?: string; } export function fromGitUri(uri: Uri): GitUriParams { return JSON.parse(uri.query); } export interface GitUriOptions { replaceFileExtension?: boolean; submoduleOf?: string; } // As a mitigation for extensions like ESLint showing warnings and errors // for git URIs, let's change the file extension of these uris to .git, // when `replaceFileExtension` is true. export function toGitUri(uri: Uri, ref: string, options: GitUriOptions = {}): Uri { const params: GitUriParams = { path: uri.fsPath, ref }; if (options.submoduleOf) { params.submoduleOf = options.submoduleOf; } let path = uri.path; if (options.replaceFileExtension) { path = `${path}.git`; } else if (options.submoduleOf) { path = `${path}.diff`; } return uri.with({ scheme: 'git', path, query: JSON.stringify(params) }); }
extensions/git/src/uri.ts
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017653629765845835, 0.00017481511167716235, 0.0001739045837894082, 0.00017467609723098576, 8.913816031963506e-7 ]
{ "id": 7, "code_window": [ "import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry';\n", "import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';\n", "\n", "export class MessageController implements editorCommon.IEditorContribution {\n", "\n", "\tprivate static readonly _id = 'editor.contrib.messageController';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export class MessageController extends Disposable implements editorCommon.IEditorContribution {\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "replace", "edit_start_line_idx": 22 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { TPromise } from 'vs/base/common/winjs.base'; import * as nls from 'vs/nls'; import * as objects from 'vs/base/common/objects'; import * as DOM from 'vs/base/browser/dom'; import * as path from 'path'; import URI from 'vs/base/common/uri'; import { once } from 'vs/base/common/functional'; import * as paths from 'vs/base/common/paths'; import * as resources from 'vs/base/common/resources'; import * as errors from 'vs/base/common/errors'; import { IAction, ActionRunner as BaseActionRunner, IActionRunner } from 'vs/base/common/actions'; import * as comparers from 'vs/base/common/comparers'; import { InputBox, MessageType } from 'vs/base/browser/ui/inputbox/inputBox'; import { isMacintosh, isLinux } from 'vs/base/common/platform'; import * as glob from 'vs/base/common/glob'; import { FileLabel, IFileLabelOptions } from 'vs/workbench/browser/labels'; import { IDisposable, dispose, empty as EmptyDisposable } from 'vs/base/common/lifecycle'; import { IFilesConfiguration, SortOrder } from 'vs/workbench/parts/files/common/files'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { FileOperationError, FileOperationResult, IFileService, FileKind } from 'vs/platform/files/common/files'; import { ResourceMap } from 'vs/base/common/map'; import { DuplicateFileAction, AddFilesAction, IEditableData, IFileViewletState, FileCopiedContext } from 'vs/workbench/parts/files/electron-browser/fileActions'; import { IDataSource, ITree, IAccessibilityProvider, IRenderer, ContextMenuEvent, ISorter, IFilter, IDragAndDropData, IDragOverReaction, DRAG_OVER_ACCEPT_BUBBLE_DOWN, DRAG_OVER_ACCEPT_BUBBLE_DOWN_COPY, DRAG_OVER_ACCEPT_BUBBLE_UP, DRAG_OVER_ACCEPT_BUBBLE_UP_COPY, DRAG_OVER_REJECT } from 'vs/base/parts/tree/browser/tree'; import { DesktopDragAndDropData, ExternalElementsDragAndDropData } from 'vs/base/parts/tree/browser/treeDnd'; import { ClickBehavior } from 'vs/base/parts/tree/browser/treeDefaults'; import { ExplorerItem, NewStatPlaceholder, Model } from 'vs/workbench/parts/files/common/explorerModel'; import { DragMouseEvent, IMouseEvent } from 'vs/base/browser/mouseEvent'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { IMenuService, IMenu, MenuId } from 'vs/platform/actions/common/actions'; import { fillInActions } from 'vs/platform/actions/browser/menuItemActionItem'; import { IBackupFileService } from 'vs/workbench/services/backup/common/backup'; import { attachInputBoxStyler } from 'vs/platform/theme/common/styler'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IWindowService } from 'vs/platform/windows/common/windows'; import { IWorkspaceEditingService } from 'vs/workbench/services/workspace/common/workspaceEditing'; import { extractResources, SimpleFileResourceDragAndDrop, CodeDataTransfers, fillResourceDataTransfers } from 'vs/workbench/browser/dnd'; import { WorkbenchTree, WorkbenchTreeController } from 'vs/platform/list/browser/listService'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { DataTransfers } from 'vs/base/browser/dnd'; import { Schemas } from 'vs/base/common/network'; import { IWorkspaceFolderCreationData } from 'vs/platform/workspaces/common/workspaces'; import { rtrim } from 'vs/base/common/strings'; import { IDialogService, IConfirmationResult, IConfirmation, getConfirmMessage } from 'vs/platform/dialogs/common/dialogs'; import { INotificationService } from 'vs/platform/notification/common/notification'; export class FileDataSource implements IDataSource { constructor( @IProgressService private progressService: IProgressService, @INotificationService private notificationService: INotificationService, @IFileService private fileService: IFileService, @IPartService private partService: IPartService ) { } public getId(tree: ITree, stat: ExplorerItem | Model): string { if (stat instanceof Model) { return 'model'; } return `${stat.root.resource.toString()}:${stat.getId()}`; } public hasChildren(tree: ITree, stat: ExplorerItem | Model): boolean { return stat instanceof Model || (stat instanceof ExplorerItem && stat.isDirectory); } public getChildren(tree: ITree, stat: ExplorerItem | Model): TPromise<ExplorerItem[]> { if (stat instanceof Model) { return TPromise.as(stat.roots); } // Return early if stat is already resolved if (stat.isDirectoryResolved) { return TPromise.as(stat.getChildrenArray()); } // Resolve children and add to fileStat for future lookup else { // Resolve const promise = this.fileService.resolveFile(stat.resource, { resolveSingleChildDescendants: true }).then(dirStat => { // Convert to view model const modelDirStat = ExplorerItem.create(dirStat, stat.root); // Add children to folder const children = modelDirStat.getChildrenArray(); if (children) { children.forEach(child => { stat.addChild(child); }); } stat.isDirectoryResolved = true; return stat.getChildrenArray(); }, (e: any) => { // Do not show error for roots since we already use an explorer decoration to notify user if (!(stat instanceof ExplorerItem && stat.isRoot)) { this.notificationService.error(e); } return []; // we could not resolve any children because of an error }); this.progressService.showWhile(promise, this.partService.isCreated() ? 800 : 3200 /* less ugly initial startup */); return promise; } } public getParent(tree: ITree, stat: ExplorerItem | Model): TPromise<ExplorerItem> { if (!stat) { return TPromise.as(null); // can be null if nothing selected in the tree } // Return if root reached if (tree.getInput() === stat) { return TPromise.as(null); } // Return if parent already resolved if (stat instanceof ExplorerItem && stat.parent) { return TPromise.as(stat.parent); } // We never actually resolve the parent from the disk for performance reasons. It wouldnt make // any sense to resolve parent by parent with requests to walk up the chain. Instead, the explorer // makes sure to properly resolve a deep path to a specific file and merges the result with the model. return TPromise.as(null); } } export class FileViewletState implements IFileViewletState { private editableStats: ResourceMap<IEditableData>; constructor() { this.editableStats = new ResourceMap<IEditableData>(); } public getEditableData(stat: ExplorerItem): IEditableData { return this.editableStats.get(stat.resource); } public setEditable(stat: ExplorerItem, editableData: IEditableData): void { if (editableData) { this.editableStats.set(stat.resource, editableData); } } public clearEditable(stat: ExplorerItem): void { this.editableStats.delete(stat.resource); } } export class ActionRunner extends BaseActionRunner implements IActionRunner { private viewletState: FileViewletState; constructor(state: FileViewletState) { super(); this.viewletState = state; } public run(action: IAction, context?: any): TPromise<any> { return super.run(action, { viewletState: this.viewletState }); } } export interface IFileTemplateData { elementDisposable: IDisposable; label: FileLabel; container: HTMLElement; } // Explorer Renderer export class FileRenderer implements IRenderer { private static readonly ITEM_HEIGHT = 22; private static readonly FILE_TEMPLATE_ID = 'file'; private state: FileViewletState; private config: IFilesConfiguration; private configListener: IDisposable; constructor( state: FileViewletState, @IContextViewService private contextViewService: IContextViewService, @IInstantiationService private instantiationService: IInstantiationService, @IThemeService private themeService: IThemeService, @IConfigurationService private configurationService: IConfigurationService, @IWorkspaceContextService private contextService: IWorkspaceContextService ) { this.state = state; this.config = this.configurationService.getValue<IFilesConfiguration>(); this.configListener = this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('explorer')) { this.config = this.configurationService.getValue(); } }); } dispose(): void { this.configListener.dispose(); } public getHeight(tree: ITree, element: any): number { return FileRenderer.ITEM_HEIGHT; } public getTemplateId(tree: ITree, element: any): string { return FileRenderer.FILE_TEMPLATE_ID; } public disposeTemplate(tree: ITree, templateId: string, templateData: IFileTemplateData): void { templateData.elementDisposable.dispose(); templateData.label.dispose(); } public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): IFileTemplateData { const elementDisposable = EmptyDisposable; const label = this.instantiationService.createInstance(FileLabel, container, void 0); return { elementDisposable, label, container }; } public renderElement(tree: ITree, stat: ExplorerItem, templateId: string, templateData: IFileTemplateData): void { templateData.elementDisposable.dispose(); const editableData: IEditableData = this.state.getEditableData(stat); // File Label if (!editableData) { templateData.label.element.style.display = 'flex'; const extraClasses = ['explorer-item']; templateData.label.setFile(stat.resource, { hidePath: true, fileKind: stat.isRoot ? FileKind.ROOT_FOLDER : stat.isDirectory ? FileKind.FOLDER : FileKind.FILE, extraClasses, fileDecorations: this.config.explorer.decorations }); templateData.elementDisposable = templateData.label.onDidRender(() => { tree.updateWidth(stat); }); } // Input Box else { templateData.label.element.style.display = 'none'; this.renderInputBox(templateData.container, tree, stat, editableData); templateData.elementDisposable = EmptyDisposable; } } private renderInputBox(container: HTMLElement, tree: ITree, stat: ExplorerItem, editableData: IEditableData): void { // Use a file label only for the icon next to the input box const label = this.instantiationService.createInstance(FileLabel, container, void 0); const extraClasses = ['explorer-item', 'explorer-item-edited']; const fileKind = stat.isRoot ? FileKind.ROOT_FOLDER : (stat.isDirectory || (stat instanceof NewStatPlaceholder && stat.isDirectoryPlaceholder())) ? FileKind.FOLDER : FileKind.FILE; const labelOptions: IFileLabelOptions = { hidePath: true, hideLabel: true, fileKind, extraClasses }; label.setFile(stat.resource, labelOptions); // Input field for name const inputBox = new InputBox(label.element, this.contextViewService, { validationOptions: { validation: editableData.validator }, ariaLabel: nls.localize('fileInputAriaLabel', "Type file name. Press Enter to confirm or Escape to cancel.") }); const styler = attachInputBoxStyler(inputBox, this.themeService); const parent = resources.dirname(stat.resource); inputBox.onDidChange(value => { label.setFile(parent.with({ path: paths.join(parent.path, value) }), labelOptions); // update label icon while typing! }); const value = stat.name || ''; const lastDot = value.lastIndexOf('.'); inputBox.value = value; inputBox.select({ start: 0, end: lastDot > 0 && !stat.isDirectory ? lastDot : value.length }); inputBox.focus(); const done = once((commit: boolean, blur: boolean) => { tree.clearHighlight(); if (commit && inputBox.value) { editableData.action.run({ value: inputBox.value }); } setTimeout(() => { if (!blur) { // https://github.com/Microsoft/vscode/issues/20269 tree.domFocus(); } dispose(toDispose); container.removeChild(label.element); }, 0); }); const toDispose = [ inputBox, DOM.addStandardDisposableListener(inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: IKeyboardEvent) => { if (e.equals(KeyCode.Enter)) { if (inputBox.validate()) { done(true, false); } } else if (e.equals(KeyCode.Escape)) { done(false, false); } }), DOM.addStandardDisposableListener(inputBox.inputElement, DOM.EventType.KEY_UP, (e: IKeyboardEvent) => { const initialRelPath: string = path.relative(stat.root.resource.fsPath, stat.parent.resource.fsPath); let projectFolderName: string = ''; if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) { projectFolderName = paths.basename(stat.root.resource.fsPath); // show root folder name in multi-folder project } this.displayCurrentPath(inputBox, initialRelPath, fileKind, projectFolderName); }), DOM.addDisposableListener(inputBox.inputElement, DOM.EventType.BLUR, () => { done(inputBox.isInputValid(), true); }), label, styler ]; } private displayCurrentPath(inputBox: InputBox, initialRelPath: string, fileKind: FileKind, projectFolderName: string = '') { if (inputBox.validate()) { const value = inputBox.value; if (value && value.search(/[\\/]/) !== -1) { // only show if there's a slash let displayPath = path.normalize(path.join(projectFolderName, initialRelPath, value)); displayPath = rtrim(displayPath, paths.nativeSep); const fileType: string = FileKind[fileKind].toLowerCase(); inputBox.showMessage({ type: MessageType.INFO, content: nls.localize('constructedPath', "Create {0} in **{1}**", fileType, displayPath), formatContent: true }); } else { // fixes #46744: inputbox hides again if all slashes are removed inputBox.hideMessage(); } } } } // Explorer Accessibility Provider export class FileAccessibilityProvider implements IAccessibilityProvider { public getAriaLabel(tree: ITree, stat: ExplorerItem): string { return nls.localize('filesExplorerViewerAriaLabel', "{0}, Files Explorer", stat.name); } } // Explorer Controller export class FileController extends WorkbenchTreeController implements IDisposable { private fileCopiedContextKey: IContextKey<boolean>; private contributedContextMenu: IMenu; private toDispose: IDisposable[]; private previousSelectionRangeStop: ExplorerItem; constructor( @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IContextMenuService private contextMenuService: IContextMenuService, @ITelemetryService private telemetryService: ITelemetryService, @IMenuService private menuService: IMenuService, @IContextKeyService contextKeyService: IContextKeyService, @IClipboardService private clipboardService: IClipboardService, @IConfigurationService configurationService: IConfigurationService ) { super({ clickBehavior: ClickBehavior.ON_MOUSE_UP /* do not change to not break DND */ }, configurationService); this.fileCopiedContextKey = FileCopiedContext.bindTo(contextKeyService); this.toDispose = []; } public onLeftClick(tree: WorkbenchTree, stat: ExplorerItem | Model, event: IMouseEvent, origin: string = 'mouse'): boolean { const payload = { origin: origin }; const isDoubleClick = (origin === 'mouse' && event.detail === 2); // Handle Highlight Mode if (tree.getHighlight()) { // Cancel Event event.preventDefault(); event.stopPropagation(); tree.clearHighlight(payload); return false; } // Handle root if (stat instanceof Model) { tree.clearFocus(payload); tree.clearSelection(payload); return false; } // Cancel Event const isMouseDown = event && event.browserEvent && event.browserEvent.type === 'mousedown'; if (!isMouseDown) { event.preventDefault(); // we cannot preventDefault onMouseDown because this would break DND otherwise } event.stopPropagation(); // Set DOM focus tree.domFocus(); if (stat instanceof NewStatPlaceholder) { return true; } // Allow to multiselect if ((tree.useAltAsMultipleSelectionModifier && event.altKey) || !tree.useAltAsMultipleSelectionModifier && (event.ctrlKey || event.metaKey)) { const selection = tree.getSelection(); this.previousSelectionRangeStop = undefined; if (selection.indexOf(stat) >= 0) { tree.setSelection(selection.filter(s => s !== stat)); } else { tree.setSelection(selection.concat(stat)); tree.setFocus(stat, payload); } } // Allow to unselect else if (event.shiftKey) { const focus = tree.getFocus(); if (focus) { if (this.previousSelectionRangeStop) { tree.deselectRange(stat, this.previousSelectionRangeStop); } tree.selectRange(focus, stat, payload); this.previousSelectionRangeStop = stat; } } // Select, Focus and open files else { // Expand / Collapse if (isDoubleClick || this.openOnSingleClick || this.isClickOnTwistie(event)) { tree.toggleExpansion(stat, event.altKey); this.previousSelectionRangeStop = undefined; } const preserveFocus = !isDoubleClick; tree.setFocus(stat, payload); if (isDoubleClick) { event.preventDefault(); // focus moves to editor, we need to prevent default } tree.setSelection([stat], payload); if (!stat.isDirectory && (isDoubleClick || this.openOnSingleClick)) { let sideBySide = false; if (event) { sideBySide = tree.useAltAsMultipleSelectionModifier ? (event.ctrlKey || event.metaKey) : event.altKey; } this.openEditor(stat, { preserveFocus, sideBySide, pinned: isDoubleClick }); } } return true; } public onContextMenu(tree: WorkbenchTree, stat: ExplorerItem | Model, event: ContextMenuEvent): boolean { if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return false; } event.preventDefault(); event.stopPropagation(); tree.setFocus(stat); // update dynamic contexts this.fileCopiedContextKey.set(this.clipboardService.hasFiles()); if (!this.contributedContextMenu) { this.contributedContextMenu = this.menuService.createMenu(MenuId.ExplorerContext, tree.contextKeyService); this.toDispose.push(this.contributedContextMenu); } const anchor = { x: event.posx, y: event.posy }; const selection = tree.getSelection(); this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => { const actions: IAction[] = []; fillInActions(this.contributedContextMenu, { arg: stat instanceof ExplorerItem ? stat.resource : {}, shouldForwardArgs: true }, actions, this.contextMenuService); return TPromise.as(actions); }, onHide: (wasCancelled?: boolean) => { if (wasCancelled) { tree.domFocus(); } }, getActionsContext: () => selection && selection.indexOf(stat) >= 0 ? selection.map((fs: ExplorerItem) => fs.resource) : stat instanceof ExplorerItem ? [stat.resource] : [] }); return true; } public openEditor(stat: ExplorerItem, options: { preserveFocus: boolean; sideBySide: boolean; pinned: boolean; }): void { if (stat && !stat.isDirectory) { /* __GDPR__ "workbenchActionExecuted" : { "id" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "from": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('workbenchActionExecuted', { id: 'workbench.files.openFile', from: 'explorer' }); this.editorService.openEditor({ resource: stat.resource, options }, options.sideBySide).done(null, errors.onUnexpectedError); } } public dispose(): void { this.toDispose = dispose(this.toDispose); } } // Explorer Sorter export class FileSorter implements ISorter { private toDispose: IDisposable[]; private sortOrder: SortOrder; constructor( @IConfigurationService private configurationService: IConfigurationService, @IWorkspaceContextService private contextService: IWorkspaceContextService ) { this.toDispose = []; this.updateSortOrder(); this.registerListeners(); } private registerListeners(): void { this.toDispose.push(this.configurationService.onDidChangeConfiguration(e => this.updateSortOrder())); } private updateSortOrder(): void { this.sortOrder = this.configurationService.getValue('explorer.sortOrder') || 'default'; } public compare(tree: ITree, statA: ExplorerItem, statB: ExplorerItem): number { // Do not sort roots if (statA.isRoot) { if (statB.isRoot) { return this.contextService.getWorkspaceFolder(statA.resource).index - this.contextService.getWorkspaceFolder(statB.resource).index; } return -1; } if (statB.isRoot) { return 1; } // Sort Directories switch (this.sortOrder) { case 'type': if (statA.isDirectory && !statB.isDirectory) { return -1; } if (statB.isDirectory && !statA.isDirectory) { return 1; } if (statA.isDirectory && statB.isDirectory) { return comparers.compareFileNames(statA.name, statB.name); } break; case 'filesFirst': if (statA.isDirectory && !statB.isDirectory) { return 1; } if (statB.isDirectory && !statA.isDirectory) { return -1; } break; case 'mixed': break; // not sorting when "mixed" is on default: /* 'default', 'modified' */ if (statA.isDirectory && !statB.isDirectory) { return -1; } if (statB.isDirectory && !statA.isDirectory) { return 1; } break; } // Sort "New File/Folder" placeholders if (statA instanceof NewStatPlaceholder) { return -1; } if (statB instanceof NewStatPlaceholder) { return 1; } // Sort Files switch (this.sortOrder) { case 'type': return comparers.compareFileExtensions(statA.name, statB.name); case 'modified': if (statA.mtime !== statB.mtime) { return statA.mtime < statB.mtime ? 1 : -1; } return comparers.compareFileNames(statA.name, statB.name); default: /* 'default', 'mixed', 'filesFirst' */ return comparers.compareFileNames(statA.name, statB.name); } } public dispose(): void { this.toDispose = dispose(this.toDispose); } } // Explorer Filter export class FileFilter implements IFilter { private static readonly MAX_SIBLINGS_FILTER_THRESHOLD = 2000; private hiddenExpressionPerRoot: Map<string, glob.IExpression>; private workspaceFolderChangeListener: IDisposable; constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService, @IConfigurationService private configurationService: IConfigurationService ) { this.hiddenExpressionPerRoot = new Map<string, glob.IExpression>(); this.registerListeners(); } public registerListeners(): void { this.workspaceFolderChangeListener = this.contextService.onDidChangeWorkspaceFolders(() => this.updateConfiguration()); } public updateConfiguration(): boolean { let needsRefresh = false; this.contextService.getWorkspace().folders.forEach(folder => { const configuration = this.configurationService.getValue<IFilesConfiguration>({ resource: folder.uri }); const excludesConfig = (configuration && configuration.files && configuration.files.exclude) || Object.create(null); needsRefresh = needsRefresh || !objects.equals(this.hiddenExpressionPerRoot.get(folder.uri.toString()), excludesConfig); this.hiddenExpressionPerRoot.set(folder.uri.toString(), objects.deepClone(excludesConfig)); // do not keep the config, as it gets mutated under our hoods }); return needsRefresh; } public isVisible(tree: ITree, stat: ExplorerItem): boolean { return this.doIsVisible(stat); } private doIsVisible(stat: ExplorerItem): boolean { if (stat instanceof NewStatPlaceholder || stat.isRoot) { return true; // always visible } // Workaround for O(N^2) complexity (https://github.com/Microsoft/vscode/issues/9962) let siblingsFn: () => string[]; let siblingCount = stat.parent && stat.parent.getChildrenCount(); if (siblingCount && siblingCount > FileFilter.MAX_SIBLINGS_FILTER_THRESHOLD) { siblingsFn = () => void 0; } else { siblingsFn = () => stat.parent ? stat.parent.getChildrenNames() : void 0; } // Hide those that match Hidden Patterns const expression = this.hiddenExpressionPerRoot.get(stat.root.resource.toString()) || Object.create(null); if (glob.match(expression, paths.normalize(path.relative(stat.root.resource.fsPath, stat.resource.fsPath), true), siblingsFn)) { return false; // hidden through pattern } return true; } public dispose(): void { this.workspaceFolderChangeListener = dispose(this.workspaceFolderChangeListener); } } // Explorer Drag And Drop Controller export class FileDragAndDrop extends SimpleFileResourceDragAndDrop { private static readonly CONFIRM_DND_SETTING_KEY = 'explorer.confirmDragAndDrop'; private toDispose: IDisposable[]; private dropEnabled: boolean; constructor( @INotificationService private notificationService: INotificationService, @IDialogService private dialogService: IDialogService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IFileService private fileService: IFileService, @IConfigurationService private configurationService: IConfigurationService, @IInstantiationService instantiationService: IInstantiationService, @ITextFileService private textFileService: ITextFileService, @IBackupFileService private backupFileService: IBackupFileService, @IWindowService private windowService: IWindowService, @IWorkspaceEditingService private workspaceEditingService: IWorkspaceEditingService ) { super(stat => this.statToResource(stat), instantiationService); this.toDispose = []; this.updateDropEnablement(); this.registerListeners(); } private statToResource(stat: ExplorerItem): URI { if (stat.isDirectory) { return URI.from({ scheme: 'folder', path: stat.resource.path }); // indicates that we are dragging a folder } return stat.resource; } private registerListeners(): void { this.toDispose.push(this.configurationService.onDidChangeConfiguration(e => this.updateDropEnablement())); } private updateDropEnablement(): void { this.dropEnabled = this.configurationService.getValue('explorer.enableDragAndDrop'); } public onDragStart(tree: ITree, data: IDragAndDropData, originalEvent: DragMouseEvent): void { const sources: ExplorerItem[] = data.getData(); if (sources && sources.length) { // When dragging folders, make sure to collapse them to free up some space sources.forEach(s => { if (s.isDirectory && tree.isExpanded(s)) { tree.collapse(s, false); } }); // Apply some datatransfer types to allow for dragging the element outside of the application this.instantiationService.invokeFunction(fillResourceDataTransfers, sources, originalEvent); // The only custom data transfer we set from the explorer is a file transfer // to be able to DND between multiple code file explorers across windows const fileResources = sources.filter(s => !s.isDirectory && s.resource.scheme === Schemas.file).map(r => r.resource.fsPath); if (fileResources.length) { originalEvent.dataTransfer.setData(CodeDataTransfers.FILES, JSON.stringify(fileResources)); } } } public onDragOver(tree: ITree, data: IDragAndDropData, target: ExplorerItem | Model, originalEvent: DragMouseEvent): IDragOverReaction { if (!this.dropEnabled) { return DRAG_OVER_REJECT; } const isCopy = originalEvent && ((originalEvent.ctrlKey && !isMacintosh) || (originalEvent.altKey && isMacintosh)); const fromDesktop = data instanceof DesktopDragAndDropData; // Desktop DND if (fromDesktop) { const types: string[] = originalEvent.dataTransfer.types; const typesArray: string[] = []; for (let i = 0; i < types.length; i++) { typesArray.push(types[i].toLowerCase()); // somehow the types are lowercase } if (typesArray.indexOf(DataTransfers.FILES.toLowerCase()) === -1 && typesArray.indexOf(CodeDataTransfers.FILES.toLowerCase()) === -1) { return DRAG_OVER_REJECT; } } // Other-Tree DND else if (data instanceof ExternalElementsDragAndDropData) { return DRAG_OVER_REJECT; } // In-Explorer DND else { const sources: ExplorerItem[] = data.getData(); if (target instanceof Model) { if (sources[0].isRoot) { return DRAG_OVER_ACCEPT_BUBBLE_DOWN(false); } return DRAG_OVER_REJECT; } if (!Array.isArray(sources)) { return DRAG_OVER_REJECT; } if (sources.some((source) => { if (source instanceof NewStatPlaceholder) { return true; // NewStatPlaceholders can not be moved } if (source.isRoot && target instanceof ExplorerItem && !target.isRoot) { return true; // Root folder can not be moved to a non root file stat. } if (source.resource.toString() === target.resource.toString()) { return true; // Can not move anything onto itself } if (!isCopy && resources.dirname(source.resource).toString() === target.resource.toString()) { return true; // Can not move a file to the same parent unless we copy } if (resources.isEqualOrParent(target.resource, source.resource, !isLinux /* ignorecase */)) { return true; // Can not move a parent folder into one of its children } return false; })) { return DRAG_OVER_REJECT; } } // All (target = model) if (target instanceof Model) { return this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE ? DRAG_OVER_ACCEPT_BUBBLE_DOWN_COPY(false) : DRAG_OVER_REJECT; // can only drop folders to workspace } // All (target = file/folder) else { if (target.isDirectory) { return fromDesktop || isCopy ? DRAG_OVER_ACCEPT_BUBBLE_DOWN_COPY(true) : DRAG_OVER_ACCEPT_BUBBLE_DOWN(true); } if (this.contextService.getWorkspace().folders.every(folder => folder.uri.toString() !== target.resource.toString())) { return fromDesktop || isCopy ? DRAG_OVER_ACCEPT_BUBBLE_UP_COPY : DRAG_OVER_ACCEPT_BUBBLE_UP; } } return DRAG_OVER_REJECT; } public drop(tree: ITree, data: IDragAndDropData, target: ExplorerItem | Model, originalEvent: DragMouseEvent): void { let promise: TPromise<void> = TPromise.as(null); // Desktop DND (Import file) if (data instanceof DesktopDragAndDropData) { promise = this.handleExternalDrop(tree, data, target, originalEvent); } // In-Explorer DND (Move/Copy file) else { promise = this.handleExplorerDrop(tree, data, target, originalEvent); } promise.done(null, errors.onUnexpectedError); } private handleExternalDrop(tree: ITree, data: DesktopDragAndDropData, target: ExplorerItem | Model, originalEvent: DragMouseEvent): TPromise<void> { const droppedResources = extractResources(originalEvent.browserEvent as DragEvent, true); // Check for dropped external files to be folders return this.fileService.resolveFiles(droppedResources).then(result => { // Pass focus to window this.windowService.focusWindow(); // Handle folders by adding to workspace if we are in workspace context const folders = result.filter(r => r.success && r.stat.isDirectory).map(result => ({ uri: result.stat.resource })); if (folders.length > 0) { // If we are in no-workspace context, ask for confirmation to create a workspace let confirmedPromise: TPromise<IConfirmationResult> = TPromise.wrap({ confirmed: true }); if (this.contextService.getWorkbenchState() !== WorkbenchState.WORKSPACE) { confirmedPromise = this.dialogService.confirm({ message: folders.length > 1 ? nls.localize('dropFolders', "Do you want to add the folders to the workspace?") : nls.localize('dropFolder', "Do you want to add the folder to the workspace?"), type: 'question', primaryButton: folders.length > 1 ? nls.localize('addFolders', "&&Add Folders") : nls.localize('addFolder', "&&Add Folder") }); } return confirmedPromise.then(res => { if (res.confirmed) { return this.workspaceEditingService.addFolders(folders); } return void 0; }); } // Handle dropped files (only support FileStat as target) else if (target instanceof ExplorerItem) { const addFilesAction = this.instantiationService.createInstance(AddFilesAction, tree, target, null); return addFilesAction.run(droppedResources.map(res => res.resource)); } return void 0; }); } private handleExplorerDrop(tree: ITree, data: IDragAndDropData, target: ExplorerItem | Model, originalEvent: DragMouseEvent): TPromise<void> { const sources: ExplorerItem[] = resources.distinctParents(data.getData(), s => s.resource); const isCopy = (originalEvent.ctrlKey && !isMacintosh) || (originalEvent.altKey && isMacintosh); let confirmPromise: TPromise<IConfirmationResult>; // Handle confirm setting const confirmDragAndDrop = !isCopy && this.configurationService.getValue<boolean>(FileDragAndDrop.CONFIRM_DND_SETTING_KEY); if (confirmDragAndDrop) { confirmPromise = this.dialogService.confirm({ message: sources.length > 1 && sources.every(s => s.isRoot) ? nls.localize('confirmRootsMove', "Are you sure you want to change the order of multiple root folders in your workspace?") : sources.length > 1 ? getConfirmMessage(nls.localize('confirmMultiMove', "Are you sure you want to move the following {0} files?", sources.length), sources.map(s => s.resource)) : sources[0].isRoot ? nls.localize('confirmRootMove', "Are you sure you want to change the order of root folder '{0}' in your workspace?", sources[0].name) : nls.localize('confirmMove', "Are you sure you want to move '{0}'?", sources[0].name), checkbox: { label: nls.localize('doNotAskAgain', "Do not ask me again") }, type: 'question', primaryButton: nls.localize({ key: 'moveButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Move") }); } else { confirmPromise = TPromise.as({ confirmed: true } as IConfirmationResult); } return confirmPromise.then(res => { // Check for confirmation checkbox let updateConfirmSettingsPromise: TPromise<void> = TPromise.as(void 0); if (res.confirmed && res.checkboxChecked === true) { updateConfirmSettingsPromise = this.configurationService.updateValue(FileDragAndDrop.CONFIRM_DND_SETTING_KEY, false, ConfigurationTarget.USER); } return updateConfirmSettingsPromise.then(() => { if (res.confirmed) { const rootDropPromise = this.doHandleRootDrop(sources.filter(s => s.isRoot), target); return TPromise.join(sources.filter(s => !s.isRoot).map(source => this.doHandleExplorerDrop(tree, source, target, isCopy)).concat(rootDropPromise)).then(() => void 0); } return TPromise.as(void 0); }); }); } private doHandleRootDrop(roots: ExplorerItem[], target: ExplorerItem | Model): TPromise<void> { if (roots.length === 0) { return TPromise.as(undefined); } const folders = this.contextService.getWorkspace().folders; let targetIndex: number; const workspaceCreationData: IWorkspaceFolderCreationData[] = []; const rootsToMove: IWorkspaceFolderCreationData[] = []; for (let index = 0; index < folders.length; index++) { const data = { uri: folders[index].uri }; if (target instanceof ExplorerItem && folders[index].uri.toString() === target.resource.toString()) { targetIndex = workspaceCreationData.length; } if (roots.every(r => r.resource.toString() !== folders[index].uri.toString())) { workspaceCreationData.push(data); } else { rootsToMove.push(data); } } if (target instanceof Model) { targetIndex = workspaceCreationData.length; } workspaceCreationData.splice(targetIndex, 0, ...rootsToMove); return this.workspaceEditingService.updateFolders(0, workspaceCreationData.length, workspaceCreationData); } private doHandleExplorerDrop(tree: ITree, source: ExplorerItem, target: ExplorerItem | Model, isCopy: boolean): TPromise<void> { return tree.expand(target).then(() => { // Reuse duplicate action if user copies if (isCopy) { return this.instantiationService.createInstance(DuplicateFileAction, tree, source, target).run(); } const dirtyMoved: URI[] = []; // Success: load all files that are dirty again to restore their dirty contents // Error: discard any backups created during the process const onSuccess = () => TPromise.join(dirtyMoved.map(t => this.textFileService.models.loadOrCreate(t))); const onError = (error?: Error, showError?: boolean) => { if (showError) { this.notificationService.error(error); } return TPromise.join(dirtyMoved.map(d => this.backupFileService.discardResourceBackup(d))); }; if (!(target instanceof ExplorerItem)) { return TPromise.as(void 0); } // 1. check for dirty files that are being moved and backup to new target const dirty = this.textFileService.getDirty().filter(d => resources.isEqualOrParent(d, source.resource, !isLinux /* ignorecase */)); return TPromise.join(dirty.map(d => { let moved: URI; // If the dirty file itself got moved, just reparent it to the target folder if (source.resource.toString() === d.toString()) { moved = target.resource.with({ path: paths.join(target.resource.path, source.name) }); } // Otherwise, a parent of the dirty resource got moved, so we have to reparent more complicated. Example: else { moved = target.resource.with({ path: paths.join(target.resource.path, d.path.substr(source.parent.resource.path.length + 1)) }); } dirtyMoved.push(moved); const model = this.textFileService.models.get(d); return this.backupFileService.backupResource(moved, model.createSnapshot(), model.getVersionId()); })) // 2. soft revert all dirty since we have backed up their contents .then(() => this.textFileService.revertAll(dirty, { soft: true /* do not attempt to load content from disk */ })) // 3.) run the move operation .then(() => { const targetResource = target.resource.with({ path: paths.join(target.resource.path, source.name) }); return this.fileService.moveFile(source.resource, targetResource).then(null, error => { // Conflict if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_MOVE_CONFLICT) { const confirm: IConfirmation = { message: nls.localize('confirmOverwriteMessage', "'{0}' already exists in the destination folder. Do you want to replace it?", source.name), detail: nls.localize('irreversible', "This action is irreversible!"), primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"), type: 'warning' }; // Move with overwrite if the user confirms return this.dialogService.confirm(confirm).then(res => { if (res.confirmed) { const targetDirty = this.textFileService.getDirty().filter(d => resources.isEqualOrParent(d, targetResource, !isLinux /* ignorecase */)); // Make sure to revert all dirty in target first to be able to overwrite properly return this.textFileService.revertAll(targetDirty, { soft: true /* do not attempt to load content from disk */ }).then(() => { // Then continue to do the move operation return this.fileService.moveFile(source.resource, targetResource, true).then(onSuccess, error => onError(error, true)); }); } return onError(); }); } return onError(error, true); }); }) // 4.) resolve those that were dirty to load their previous dirty contents from disk .then(onSuccess, onError); }, errors.onUnexpectedError); } }
src/vs/workbench/parts/files/electron-browser/views/explorerViewer.ts
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017960126569960266, 0.00017348761321045458, 0.0001624099531909451, 0.00017452020256314427, 0.0000032731481951486785 ]
{ "id": 7, "code_window": [ "import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry';\n", "import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';\n", "\n", "export class MessageController implements editorCommon.IEditorContribution {\n", "\n", "\tprivate static readonly _id = 'editor.contrib.messageController';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export class MessageController extends Disposable implements editorCommon.IEditorContribution {\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "replace", "edit_start_line_idx": 22 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IExtensionService, IExtensionDescription, ProfileSession, IExtensionHostProfile, ProfileSegmentId } from 'vs/workbench/services/extensions/common/extensions'; import { TPromise } from 'vs/base/common/winjs.base'; import { TernarySearchTree } from 'vs/base/common/map'; import { realpathSync } from 'vs/base/node/extfs'; import { Profile, ProfileNode } from 'v8-inspect-profiler'; export class ExtensionHostProfiler { constructor(private readonly _port: number, @IExtensionService private readonly _extensionService: IExtensionService) { } public start(): TPromise<ProfileSession> { return TPromise.wrap(import('v8-inspect-profiler')).then(profiler => { return profiler.startProfiling({ port: this._port }).then(session => { return { stop: () => { return TPromise.wrap(session.stop()).then(profile => { return this._extensionService.getExtensions().then(extensions => { return this.distill(profile.profile, extensions); }); }); } }; }); }); } private distill(profile: Profile, extensions: IExtensionDescription[]): IExtensionHostProfile { let searchTree = TernarySearchTree.forPaths<IExtensionDescription>(); for (let extension of extensions) { searchTree.set(realpathSync(extension.extensionFolderPath), extension); } let nodes = profile.nodes; let idsToNodes = new Map<number, ProfileNode>(); let idsToSegmentId = new Map<number, ProfileSegmentId>(); for (let node of nodes) { idsToNodes.set(node.id, node); } function visit(node: ProfileNode, segmentId: ProfileSegmentId) { if (!segmentId) { switch (node.callFrame.functionName) { case '(root)': break; case '(program)': segmentId = 'program'; break; case '(garbage collector)': segmentId = 'gc'; break; default: segmentId = 'self'; break; } } else if (segmentId === 'self' && node.callFrame.url) { let extension = searchTree.findSubstr(node.callFrame.url); if (extension) { segmentId = extension.id; } } idsToSegmentId.set(node.id, segmentId); if (node.children) { for (let child of node.children) { visit(idsToNodes.get(child), segmentId); } } } visit(nodes[0], null); let samples = profile.samples; let timeDeltas = profile.timeDeltas; let distilledDeltas: number[] = []; let distilledIds: ProfileSegmentId[] = []; let currSegmentTime = 0; let currSegmentId = void 0; for (let i = 0; i < samples.length; i++) { let id = samples[i]; let segmentId = idsToSegmentId.get(id); if (segmentId !== currSegmentId) { if (currSegmentId) { distilledIds.push(currSegmentId); distilledDeltas.push(currSegmentTime); } currSegmentId = segmentId; currSegmentTime = 0; } currSegmentTime += timeDeltas[i]; } if (currSegmentId) { distilledIds.push(currSegmentId); distilledDeltas.push(currSegmentTime); } idsToNodes = null; idsToSegmentId = null; searchTree = null; return { startTime: profile.startTime, endTime: profile.endTime, deltas: distilledDeltas, ids: distilledIds, data: profile, getAggregatedTimes: () => { let segmentsToTime = new Map<ProfileSegmentId, number>(); for (let i = 0; i < distilledIds.length; i++) { let id = distilledIds[i]; segmentsToTime.set(id, (segmentsToTime.get(id) || 0) + distilledDeltas[i]); } return segmentsToTime; } }; } }
src/vs/workbench/services/extensions/electron-browser/extensionHostProfiler.ts
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017655060219112784, 0.0001742819877108559, 0.00017083383863791823, 0.00017499245586805046, 0.0000019354638425284065 ]
{ "id": 8, "code_window": [ "\n", "\tconstructor(\n", "\t\teditor: ICodeEditor,\n", "\t\t@IContextKeyService contextKeyService: IContextKeyService\n", "\t) {\n", "\t\tthis._editor = editor;\n", "\t\tthis._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\tsuper();\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 45 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import * as strings from 'vs/base/common/strings'; import { onUnexpectedError } from 'vs/base/common/errors'; import { CursorCollection } from 'vs/editor/common/controller/cursorCollection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { Selection, SelectionDirection, ISelection } from 'vs/editor/common/core/selection'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { CursorColumns, CursorConfiguration, EditOperationResult, CursorContext, CursorState, RevealTarget, IColumnSelectData, ICursors, EditOperationType } from 'vs/editor/common/controller/cursorCommon'; import { DeleteOperations } from 'vs/editor/common/controller/cursorDeleteOperations'; import { TypeOperations } from 'vs/editor/common/controller/cursorTypeOperations'; import { RawContentChangedType } from 'vs/editor/common/model/textModelEvents'; import { CursorChangeReason } from 'vs/editor/common/controller/cursorEvents'; import { IViewModel } from 'vs/editor/common/viewModel/viewModel'; import * as viewEvents from 'vs/editor/common/view/viewEvents'; import { Event, Emitter } from 'vs/base/common/event'; import { ITextModel, IIdentifiedSingleEditOperation, TrackedRangeStickiness } from 'vs/editor/common/model'; function containsLineMappingChanged(events: viewEvents.ViewEvent[]): boolean { for (let i = 0, len = events.length; i < len; i++) { if (events[i].type === viewEvents.ViewEventType.ViewLineMappingChanged) { return true; } } return false; } export class CursorStateChangedEvent { /** * The new selections. * The primary selection is always at index 0. */ readonly selections: Selection[]; /** * Source of the call that caused the event. */ readonly source: string; /** * Reason. */ readonly reason: CursorChangeReason; constructor(selections: Selection[], source: string, reason: CursorChangeReason) { this.selections = selections; this.source = source; this.reason = reason; } } /** * A snapshot of the cursor and the model state */ export class CursorModelState { public readonly modelVersionId: number; public readonly cursorState: CursorState[]; constructor(model: ITextModel, cursor: Cursor) { this.modelVersionId = model.getVersionId(); this.cursorState = cursor.getAll(); } public equals(other: CursorModelState): boolean { if (!other) { return false; } if (this.modelVersionId !== other.modelVersionId) { return false; } if (this.cursorState.length !== other.cursorState.length) { return false; } for (let i = 0, len = this.cursorState.length; i < len; i++) { if (!this.cursorState[i].equals(other.cursorState[i])) { return false; } } return true; } } export class Cursor extends viewEvents.ViewEventEmitter implements ICursors { public static MAX_CURSOR_COUNT = 10000; private readonly _onDidReachMaxCursorCount: Emitter<void> = this._register(new Emitter<void>()); public readonly onDidReachMaxCursorCount: Event<void> = this._onDidReachMaxCursorCount.event; private readonly _onDidChange: Emitter<CursorStateChangedEvent> = this._register(new Emitter<CursorStateChangedEvent>()); public readonly onDidChange: Event<CursorStateChangedEvent> = this._onDidChange.event; private readonly _configuration: editorCommon.IConfiguration; private readonly _model: ITextModel; private _knownModelVersionId: number; private readonly _viewModel: IViewModel; public context: CursorContext; private _cursors: CursorCollection; private _isHandling: boolean; private _isDoingComposition: boolean; private _columnSelectData: IColumnSelectData; private _prevEditOperationType: EditOperationType; constructor(configuration: editorCommon.IConfiguration, model: ITextModel, viewModel: IViewModel) { super(); this._configuration = configuration; this._model = model; this._knownModelVersionId = this._model.getVersionId(); this._viewModel = viewModel; this.context = new CursorContext(this._configuration, this._model, this._viewModel); this._cursors = new CursorCollection(this.context); this._isHandling = false; this._isDoingComposition = false; this._columnSelectData = null; this._prevEditOperationType = EditOperationType.Other; this._register(this._model.onDidChangeRawContent((e) => { this._knownModelVersionId = e.versionId; if (this._isHandling) { return; } let hadFlushEvent = e.containsEvent(RawContentChangedType.Flush); this._onModelContentChanged(hadFlushEvent); })); this._register(viewModel.addEventListener((events: viewEvents.ViewEvent[]) => { if (!containsLineMappingChanged(events)) { return; } if (this._knownModelVersionId !== this._model.getVersionId()) { // There are model change events that I didn't yet receive. // // This can happen when editing the model, and the view model receives the change events first, // and the view model emits line mapping changed events, all before the cursor gets a chance to // recover from markers. // // The model change listener above will be called soon and we'll ensure a valid cursor state there. return; } // Ensure valid state this.setStates('viewModel', CursorChangeReason.NotSet, this.getAll()); })); const updateCursorContext = () => { this.context = new CursorContext(this._configuration, this._model, this._viewModel); this._cursors.updateContext(this.context); }; this._register(this._model.onDidChangeLanguage((e) => { updateCursorContext(); })); this._register(this._model.onDidChangeLanguageConfiguration(() => { updateCursorContext(); })); this._register(this._model.onDidChangeOptions(() => { updateCursorContext(); })); this._register(this._configuration.onDidChange((e) => { if (CursorConfiguration.shouldRecreate(e)) { updateCursorContext(); } })); } public dispose(): void { this._cursors.dispose(); super.dispose(); } // ------ some getters/setters public getPrimaryCursor(): CursorState { return this._cursors.getPrimaryCursor(); } public getLastAddedCursorIndex(): number { return this._cursors.getLastAddedCursorIndex(); } public getAll(): CursorState[] { return this._cursors.getAll(); } public setStates(source: string, reason: CursorChangeReason, states: CursorState[]): void { if (states.length > Cursor.MAX_CURSOR_COUNT) { states = states.slice(0, Cursor.MAX_CURSOR_COUNT); this._onDidReachMaxCursorCount.fire(void 0); } const oldState = new CursorModelState(this._model, this); this._cursors.setStates(states); this._cursors.normalize(); this._columnSelectData = null; this._emitStateChangedIfNecessary(source, reason, oldState); } public setColumnSelectData(columnSelectData: IColumnSelectData): void { this._columnSelectData = columnSelectData; } public reveal(horizontal: boolean, target: RevealTarget, scrollType: editorCommon.ScrollType): void { this._revealRange(target, viewEvents.VerticalRevealType.Simple, horizontal, scrollType); } public revealRange(revealHorizontal: boolean, viewRange: Range, verticalType: viewEvents.VerticalRevealType, scrollType: editorCommon.ScrollType) { this.emitCursorRevealRange(viewRange, verticalType, revealHorizontal, scrollType); } public scrollTo(desiredScrollTop: number): void { this._viewModel.viewLayout.setScrollPositionSmooth({ scrollTop: desiredScrollTop }); } public saveState(): editorCommon.ICursorState[] { let result: editorCommon.ICursorState[] = []; const selections = this._cursors.getSelections(); for (let i = 0, len = selections.length; i < len; i++) { const selection = selections[i]; result.push({ inSelectionMode: !selection.isEmpty(), selectionStart: { lineNumber: selection.selectionStartLineNumber, column: selection.selectionStartColumn, }, position: { lineNumber: selection.positionLineNumber, column: selection.positionColumn, } }); } return result; } public restoreState(states: editorCommon.ICursorState[]): void { let desiredSelections: ISelection[] = []; for (let i = 0, len = states.length; i < len; i++) { const state = states[i]; let positionLineNumber = 1; let positionColumn = 1; // Avoid missing properties on the literal if (state.position && state.position.lineNumber) { positionLineNumber = state.position.lineNumber; } if (state.position && state.position.column) { positionColumn = state.position.column; } let selectionStartLineNumber = positionLineNumber; let selectionStartColumn = positionColumn; // Avoid missing properties on the literal if (state.selectionStart && state.selectionStart.lineNumber) { selectionStartLineNumber = state.selectionStart.lineNumber; } if (state.selectionStart && state.selectionStart.column) { selectionStartColumn = state.selectionStart.column; } desiredSelections.push({ selectionStartLineNumber: selectionStartLineNumber, selectionStartColumn: selectionStartColumn, positionLineNumber: positionLineNumber, positionColumn: positionColumn }); } this.setStates('restoreState', CursorChangeReason.NotSet, CursorState.fromModelSelections(desiredSelections)); this.reveal(true, RevealTarget.Primary, editorCommon.ScrollType.Immediate); } private _onModelContentChanged(hadFlushEvent: boolean): void { this._prevEditOperationType = EditOperationType.Other; if (hadFlushEvent) { // a model.setValue() was called this._cursors.dispose(); this._cursors = new CursorCollection(this.context); this._emitStateChangedIfNecessary('model', CursorChangeReason.ContentFlush, null); } else { const selectionsFromMarkers = this._cursors.readSelectionFromMarkers(); this.setStates('modelChange', CursorChangeReason.RecoverFromMarkers, CursorState.fromModelSelections(selectionsFromMarkers)); } } public getSelection(): Selection { return this._cursors.getPrimaryCursor().modelState.selection; } public getColumnSelectData(): IColumnSelectData { if (this._columnSelectData) { return this._columnSelectData; } const primaryCursor = this._cursors.getPrimaryCursor(); const primaryPos = primaryCursor.viewState.position; return { toViewLineNumber: primaryPos.lineNumber, toViewVisualColumn: CursorColumns.visibleColumnFromColumn2(this.context.config, this.context.viewModel, primaryPos) }; } public getSelections(): Selection[] { return this._cursors.getSelections(); } public getViewSelections(): Selection[] { return this._cursors.getViewSelections(); } public getPosition(): Position { return this._cursors.getPrimaryCursor().modelState.position; } public setSelections(source: string, selections: ISelection[]): void { this.setStates(source, CursorChangeReason.NotSet, CursorState.fromModelSelections(selections)); } public getPrevEditOperationType(): EditOperationType { return this._prevEditOperationType; } public setPrevEditOperationType(type: EditOperationType): void { this._prevEditOperationType = type; } // ------ auxiliary handling logic private _executeEditOperation(opResult: EditOperationResult): void { if (!opResult) { // Nothing to execute return; } if (opResult.shouldPushStackElementBefore) { this._model.pushStackElement(); } const result = CommandExecutor.executeCommands(this._model, this._cursors.getSelections(), opResult.commands); if (result) { // The commands were applied correctly this._interpretCommandResult(result); this._prevEditOperationType = opResult.type; } if (opResult.shouldPushStackElementAfter) { this._model.pushStackElement(); } } private _interpretCommandResult(cursorState: Selection[]): void { if (!cursorState || cursorState.length === 0) { cursorState = this._cursors.readSelectionFromMarkers(); } this._columnSelectData = null; this._cursors.setSelections(cursorState); this._cursors.normalize(); } // ----------------------------------------------------------------------------------------------------------- // ----- emitting events private _emitStateChangedIfNecessary(source: string, reason: CursorChangeReason, oldState: CursorModelState): boolean { const newState = new CursorModelState(this._model, this); if (newState.equals(oldState)) { return false; } const selections = this._cursors.getSelections(); const viewSelections = this._cursors.getViewSelections(); // Let the view get the event first. try { const eventsCollector = this._beginEmit(); eventsCollector.emit(new viewEvents.ViewCursorStateChangedEvent(viewSelections)); } finally { this._endEmit(); } // Only after the view has been notified, let the rest of the world know... if (!oldState || oldState.cursorState.length !== newState.cursorState.length || newState.cursorState.some((newCursorState, i) => !newCursorState.modelState.equals(oldState.cursorState[i].modelState)) ) { this._onDidChange.fire(new CursorStateChangedEvent(selections, source || 'keyboard', reason)); } return true; } private _revealRange(revealTarget: RevealTarget, verticalType: viewEvents.VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType): void { const viewPositions = this._cursors.getViewPositions(); let viewPosition = viewPositions[0]; if (revealTarget === RevealTarget.TopMost) { for (let i = 1; i < viewPositions.length; i++) { if (viewPositions[i].isBefore(viewPosition)) { viewPosition = viewPositions[i]; } } } else if (revealTarget === RevealTarget.BottomMost) { for (let i = 1; i < viewPositions.length; i++) { if (viewPosition.isBeforeOrEqual(viewPositions[i])) { viewPosition = viewPositions[i]; } } } else { if (viewPositions.length > 1) { // no revealing! return; } } const viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column); this.emitCursorRevealRange(viewRange, verticalType, revealHorizontal, scrollType); } public emitCursorRevealRange(viewRange: Range, verticalType: viewEvents.VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType) { try { const eventsCollector = this._beginEmit(); eventsCollector.emit(new viewEvents.ViewRevealRangeRequestEvent(viewRange, verticalType, revealHorizontal, scrollType)); } finally { this._endEmit(); } } // ----------------------------------------------------------------------------------------------------------- // ----- handlers beyond this point public trigger(source: string, handlerId: string, payload: any): void { const H = editorCommon.Handler; if (handlerId === H.CompositionStart) { this._isDoingComposition = true; return; } if (handlerId === H.CompositionEnd) { this._isDoingComposition = false; return; } if (this._configuration.editor.readOnly) { // All the remaining handlers will try to edit the model, // but we cannot edit when read only... return; } const oldState = new CursorModelState(this._model, this); let cursorChangeReason = CursorChangeReason.NotSet; // ensure valid state on all cursors this._cursors.ensureValidState(); this._isHandling = true; try { switch (handlerId) { case H.Type: this._type(source, <string>payload.text); break; case H.ReplacePreviousChar: this._replacePreviousChar(<string>payload.text, <number>payload.replaceCharCnt); break; case H.Paste: cursorChangeReason = CursorChangeReason.Paste; this._paste(<string>payload.text, <boolean>payload.pasteOnNewLine, <string[]>payload.multicursorText); break; case H.Cut: this._cut(); break; case H.Undo: cursorChangeReason = CursorChangeReason.Undo; this._interpretCommandResult(this._model.undo()); break; case H.Redo: cursorChangeReason = CursorChangeReason.Redo; this._interpretCommandResult(this._model.redo()); break; case H.ExecuteCommand: this._externalExecuteCommand(<editorCommon.ICommand>payload); break; case H.ExecuteCommands: this._externalExecuteCommands(<editorCommon.ICommand[]>payload); break; } } catch (err) { onUnexpectedError(err); } this._isHandling = false; if (this._emitStateChangedIfNecessary(source, cursorChangeReason, oldState)) { this._revealRange(RevealTarget.Primary, viewEvents.VerticalRevealType.Simple, true, editorCommon.ScrollType.Smooth); } } private _type(source: string, text: string): void { if (!this._isDoingComposition && source === 'keyboard') { // If this event is coming straight from the keyboard, look for electric characters and enter for (let i = 0, len = text.length; i < len; i++) { let charCode = text.charCodeAt(i); let chr: string; 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(TypeOperations.typeWithInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), chr)); } } else { this._executeEditOperation(TypeOperations.typeWithoutInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), text)); } } private _replacePreviousChar(text: string, replaceCharCnt: number): void { this._executeEditOperation(TypeOperations.replacePreviousChar(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), text, replaceCharCnt)); } private _paste(text: string, pasteOnNewLine: boolean, multicursorText: string[]): void { this._executeEditOperation(TypeOperations.paste(this.context.config, this.context.model, this.getSelections(), text, pasteOnNewLine, multicursorText)); } private _cut(): void { this._executeEditOperation(DeleteOperations.cut(this.context.config, this.context.model, this.getSelections())); } private _externalExecuteCommand(command: editorCommon.ICommand): void { this._cursors.killSecondaryCursors(); this._executeEditOperation(new EditOperationResult(EditOperationType.Other, [command], { shouldPushStackElementBefore: false, shouldPushStackElementAfter: false })); } private _externalExecuteCommands(commands: editorCommon.ICommand[]): void { this._executeEditOperation(new EditOperationResult(EditOperationType.Other, commands, { shouldPushStackElementBefore: false, shouldPushStackElementAfter: false })); } } interface IExecContext { readonly model: ITextModel; readonly selectionsBefore: Selection[]; readonly trackedRanges: string[]; readonly trackedRangesDirection: SelectionDirection[]; } interface ICommandData { operations: IIdentifiedSingleEditOperation[]; hadTrackedEditOperation: boolean; } interface ICommandsData { operations: IIdentifiedSingleEditOperation[]; hadTrackedEditOperation: boolean; } class CommandExecutor { public static executeCommands(model: ITextModel, selectionsBefore: Selection[], commands: editorCommon.ICommand[]): Selection[] { const ctx: IExecContext = { model: model, selectionsBefore: selectionsBefore, trackedRanges: [], trackedRangesDirection: [] }; const result = this._innerExecuteCommands(ctx, commands); for (let i = 0, len = ctx.trackedRanges.length; i < len; i++) { ctx.model._setTrackedRange(ctx.trackedRanges[i], null, TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges); } return result; } private static _innerExecuteCommands(ctx: IExecContext, commands: editorCommon.ICommand[]): Selection[] { if (this._arrayIsEmpty(commands)) { return null; } const commandsData = this._getEditOperations(ctx, commands); if (commandsData.operations.length === 0) { return null; } const rawOperations = commandsData.operations; const loserCursorsMap = this._getLoserCursorMap(rawOperations); if (loserCursorsMap.hasOwnProperty('0')) { // These commands are very messed up console.warn('Ignoring commands'); return null; } // Remove operations belonging to losing cursors let filteredOperations: IIdentifiedSingleEditOperation[] = []; for (let i = 0, len = rawOperations.length; i < len; i++) { if (!loserCursorsMap.hasOwnProperty(rawOperations[i].identifier.major.toString())) { filteredOperations.push(rawOperations[i]); } } // TODO@Alex: find a better way to do this. // give the hint that edit operations are tracked to the model if (commandsData.hadTrackedEditOperation && filteredOperations.length > 0) { filteredOperations[0]._isTracked = true; } const selectionsAfter = ctx.model.pushEditOperations(ctx.selectionsBefore, filteredOperations, (inverseEditOperations: IIdentifiedSingleEditOperation[]): Selection[] => { let groupedInverseEditOperations: IIdentifiedSingleEditOperation[][] = []; for (let i = 0; i < ctx.selectionsBefore.length; i++) { groupedInverseEditOperations[i] = []; } for (let i = 0; i < inverseEditOperations.length; i++) { const op = inverseEditOperations[i]; if (!op.identifier) { // perhaps auto whitespace trim edits continue; } groupedInverseEditOperations[op.identifier.major].push(op); } const minorBasedSorter = (a: IIdentifiedSingleEditOperation, b: IIdentifiedSingleEditOperation) => { return a.identifier.minor - b.identifier.minor; }; let cursorSelections: Selection[] = []; for (let i = 0; i < ctx.selectionsBefore.length; i++) { if (groupedInverseEditOperations[i].length > 0) { groupedInverseEditOperations[i].sort(minorBasedSorter); cursorSelections[i] = commands[i].computeCursorState(ctx.model, { getInverseEditOperations: () => { return groupedInverseEditOperations[i]; }, getTrackedSelection: (id: string) => { const idx = parseInt(id, 10); const range = ctx.model._getTrackedRange(ctx.trackedRanges[idx]); if (ctx.trackedRangesDirection[idx] === SelectionDirection.LTR) { return new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn); } return new Selection(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn); } }); } else { cursorSelections[i] = ctx.selectionsBefore[i]; } } return cursorSelections; }); // Extract losing cursors let losingCursors: number[] = []; for (let losingCursorIndex in loserCursorsMap) { if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) { losingCursors.push(parseInt(losingCursorIndex, 10)); } } // Sort losing cursors descending losingCursors.sort((a: number, b: number): number => { return b - a; }); // Remove losing cursors for (let i = 0; i < losingCursors.length; i++) { selectionsAfter.splice(losingCursors[i], 1); } return selectionsAfter; } private static _arrayIsEmpty(commands: editorCommon.ICommand[]): boolean { for (let i = 0, len = commands.length; i < len; i++) { if (commands[i]) { return false; } } return true; } private static _getEditOperations(ctx: IExecContext, commands: editorCommon.ICommand[]): ICommandsData { let operations: IIdentifiedSingleEditOperation[] = []; let hadTrackedEditOperation: boolean = false; for (let i = 0, len = commands.length; i < len; i++) { if (commands[i]) { const r = this._getEditOperationsFromCommand(ctx, i, commands[i]); operations = operations.concat(r.operations); hadTrackedEditOperation = hadTrackedEditOperation || r.hadTrackedEditOperation; } } return { operations: operations, hadTrackedEditOperation: hadTrackedEditOperation }; } private static _getEditOperationsFromCommand(ctx: IExecContext, majorIdentifier: number, command: editorCommon.ICommand): ICommandData { // This method acts as a transaction, if the command fails // everything it has done is ignored let operations: IIdentifiedSingleEditOperation[] = []; let operationMinor = 0; const addEditOperation = (selection: Range, text: string) => { 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 }); }; let hadTrackedEditOperation = false; const addTrackedEditOperation = (selection: Range, text: string) => { hadTrackedEditOperation = true; addEditOperation(selection, text); }; const trackSelection = (selection: Selection, trackPreviousOnEmpty?: boolean) => { let stickiness: TrackedRangeStickiness; if (selection.isEmpty()) { if (typeof trackPreviousOnEmpty === 'boolean') { if (trackPreviousOnEmpty) { stickiness = TrackedRangeStickiness.GrowsOnlyWhenTypingBefore; } else { stickiness = TrackedRangeStickiness.GrowsOnlyWhenTypingAfter; } } else { // Try to lock it with surrounding text const maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber); if (selection.startColumn === maxLineColumn) { stickiness = TrackedRangeStickiness.GrowsOnlyWhenTypingBefore; } else { stickiness = TrackedRangeStickiness.GrowsOnlyWhenTypingAfter; } } } else { stickiness = TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges; } const l = ctx.trackedRanges.length; const id = ctx.model._setTrackedRange(null, selection, stickiness); ctx.trackedRanges[l] = id; ctx.trackedRangesDirection[l] = selection.getDirection(); return l.toString(); }; const editOperationBuilder: editorCommon.IEditOperationBuilder = { addEditOperation: addEditOperation, addTrackedEditOperation: addTrackedEditOperation, trackSelection: trackSelection }; try { command.getEditOperations(ctx.model, editOperationBuilder); } catch (e) { e.friendlyMessage = nls.localize('corrupt.commands', "Unexpected exception while executing command."); onUnexpectedError(e); return { operations: [], hadTrackedEditOperation: false }; } return { operations: operations, hadTrackedEditOperation: hadTrackedEditOperation }; } private static _getLoserCursorMap(operations: IIdentifiedSingleEditOperation[]): { [index: string]: boolean; } { // This is destructive on the array operations = operations.slice(0); // Sort operations with last one first operations.sort((a: IIdentifiedSingleEditOperation, b: IIdentifiedSingleEditOperation): number => { // Note the minus! return -(Range.compareRangesUsingEnds(a.range, b.range)); }); // Operations can not overlap! let loserCursorsMap: { [index: string]: boolean; } = {}; for (let i = 1; i < operations.length; i++) { const previousOp = operations[i - 1]; const currentOp = operations[i]; if (previousOp.range.getStartPosition().isBefore(currentOp.range.getEndPosition())) { let loserMajor: number; if (previousOp.identifier.major > currentOp.identifier.major) { // previousOp loses the battle loserMajor = previousOp.identifier.major; } else { loserMajor = currentOp.identifier.major; } loserCursorsMap[loserMajor.toString()] = true; for (let j = 0; j < operations.length; j++) { if (operations[j].identifier.major === loserMajor) { operations.splice(j, 1); if (j < i) { i--; } j--; } } if (i > 0) { i--; } } } return loserCursorsMap; } }
src/vs/editor/common/controller/cursor.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0003044988843612373, 0.00017360664787702262, 0.0001648589241085574, 0.00017263655900023878, 0.000014477292097581085 ]
{ "id": 8, "code_window": [ "\n", "\tconstructor(\n", "\t\teditor: ICodeEditor,\n", "\t\t@IContextKeyService contextKeyService: IContextKeyService\n", "\t) {\n", "\t\tthis._editor = editor;\n", "\t\tthis._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\tsuper();\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 45 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "copyMarker": "Mรกsolรกs", "copyMarkerMessage": "รœzenet mรกsolรกsa" }
i18n/hun/src/vs/workbench/parts/markers/electron-browser/markersElectronContributions.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00018063221068587154, 0.00017873596516437829, 0.0001768397050909698, 0.00017873596516437829, 0.0000018962527974508703 ]
{ "id": 8, "code_window": [ "\n", "\tconstructor(\n", "\t\teditor: ICodeEditor,\n", "\t\t@IContextKeyService contextKeyService: IContextKeyService\n", "\t) {\n", "\t\tthis._editor = editor;\n", "\t\tthis._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\tsuper();\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 45 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "splitJoinTag": "Emmet: Etiketi Bรถl/BirleลŸtir" }
i18n/trk/src/vs/workbench/parts/emmet/electron-browser/actions/splitJoinTag.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017657298303674906, 0.00017657298303674906, 0.00017657298303674906, 0.00017657298303674906, 0 ]
{ "id": 8, "code_window": [ "\n", "\tconstructor(\n", "\t\teditor: ICodeEditor,\n", "\t\t@IContextKeyService contextKeyService: IContextKeyService\n", "\t) {\n", "\t\tthis._editor = editor;\n", "\t\tthis._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\tsuper();\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 45 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "openFolderFirst": "Aprire prima una cartella per creare le impostazioni dell'area di lavoro", "emptyKeybindingsHeader": "Inserire i tasti di scelta rapida in questo file per sovrascrivere i valori predefiniti", "defaultKeybindings": "Tasti di scelta rapida predefiniti", "folderSettingsName": "{0} (Impostazioni cartella)", "fail.createSettings": "Non รจ possibile creare '{0}' ({1})." }
i18n/ita/src/vs/workbench/parts/preferences/browser/preferencesService.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017383263912051916, 0.00017232907703146338, 0.00017082552949432284, 0.00017232907703146338, 0.0000015035548130981624 ]
{ "id": 9, "code_window": [ "\t\tthis._editor = editor;\n", "\t\tthis._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService);\n", "\t}\n", "\n", "\tdispose(): void {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(this._editor.onDidAttemptReadOnlyEdit(() => this._onDidAttemptReadOnlyEdit()));\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 47 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./messageController'; import { setDisposableTimeout } from 'vs/base/common/async'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { ICodeEditor, IContentWidget, IContentWidgetPosition, ContentWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IPosition } from 'vs/editor/common/core/position'; import { registerThemingParticipant, HIGH_CONTRAST } from 'vs/platform/theme/common/themeService'; import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry'; import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; export class MessageController implements editorCommon.IEditorContribution { private static readonly _id = 'editor.contrib.messageController'; static MESSAGE_VISIBLE = new RawContextKey<boolean>('messageVisible', false); static get(editor: ICodeEditor): MessageController { return editor.getContribution<MessageController>(MessageController._id); } getId(): string { return MessageController._id; } private _editor: ICodeEditor; private _visible: IContextKey<boolean>; private _messageWidget: MessageWidget; private _messageListeners: IDisposable[] = []; constructor( editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService ) { this._editor = editor; this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService); } dispose(): void { this._visible.reset(); } isVisible() { return this._visible.get(); } showMessage(message: string, position: IPosition): void { alert(message); this._visible.set(true); dispose(this._messageWidget); this._messageListeners = dispose(this._messageListeners); this._messageWidget = new MessageWidget(this._editor, position, message); // close on blur, cursor, model change, dispose this._messageListeners.push(this._editor.onDidBlurEditorText(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeCursorPosition(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidDispose(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeModel(() => this.closeMessage())); // close after 3s this._messageListeners.push(setDisposableTimeout(() => this.closeMessage(), 3000)); // close on mouse move let bounds: Range; this._messageListeners.push(this._editor.onMouseMove(e => { // outside the text area if (!e.target.position) { return; } if (!bounds) { // define bounding box around position and first mouse occurance bounds = new Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1); } else if (!bounds.containsPosition(e.target.position)) { // check if position is still in bounds this.closeMessage(); } })); } closeMessage(): void { this._visible.reset(); this._messageListeners = dispose(this._messageListeners); this._messageListeners.push(MessageWidget.fadeOut(this._messageWidget)); } } const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get); registerEditorCommand(new MessageCommand({ id: 'leaveEditorMessage', precondition: MessageController.MESSAGE_VISIBLE, handler: c => c.closeMessage(), kbOpts: { weight: KeybindingsRegistry.WEIGHT.editorContrib(30), primary: KeyCode.Escape } })); class MessageWidget implements IContentWidget { // Editor.IContentWidget.allowEditorOverflow readonly allowEditorOverflow = true; readonly suppressMouseDown = false; private _editor: ICodeEditor; private _position: IPosition; private _domNode: HTMLDivElement; static fadeOut(messageWidget: MessageWidget): IDisposable { let handle: number; const dispose = () => { messageWidget.dispose(); clearTimeout(handle); messageWidget.getDomNode().removeEventListener('animationend', dispose); }; handle = setTimeout(dispose, 110); messageWidget.getDomNode().addEventListener('animationend', dispose); messageWidget.getDomNode().classList.add('fadeOut'); return { dispose }; } constructor(editor: ICodeEditor, { lineNumber, column }: IPosition, text: string) { this._editor = editor; this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, editorCommon.ScrollType.Smooth); this._position = { lineNumber, column: column - 1 }; this._domNode = document.createElement('div'); this._domNode.classList.add('monaco-editor-overlaymessage'); const message = document.createElement('div'); message.classList.add('message'); message.textContent = text; this._domNode.appendChild(message); const anchor = document.createElement('div'); anchor.classList.add('anchor'); this._domNode.appendChild(anchor); this._editor.addContentWidget(this); this._domNode.classList.add('fadeIn'); } dispose() { this._editor.removeContentWidget(this); } getId(): string { return 'messageoverlay'; } getDomNode(): HTMLElement { return this._domNode; } getPosition(): IContentWidgetPosition { return { position: this._position, preference: [ContentWidgetPositionPreference.ABOVE] }; } } registerEditorContribution(MessageController); registerThemingParticipant((theme, collector) => { let border = theme.getColor(inputValidationInfoBorder); if (border) { let borderWidth = theme.type === 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}; }`); } let background = theme.getColor(inputValidationInfoBackground); if (background) { collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { background-color: ${background}; }`); } });
src/vs/editor/contrib/message/messageController.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.9974265694618225, 0.09446055442094803, 0.0001670294877840206, 0.0004110624431632459, 0.270315557718277 ]
{ "id": 9, "code_window": [ "\t\tthis._editor = editor;\n", "\t\tthis._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService);\n", "\t}\n", "\n", "\tdispose(): void {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(this._editor.onDidAttemptReadOnlyEdit(() => this._onDidAttemptReadOnlyEdit()));\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 47 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-action-bar .action-item .action-label.extension-action { padding: 0 5px; line-height: initial; } .monaco-action-bar .action-item .action-label.clear-extensions { background: url('clear.svg') center center no-repeat; } .vs-dark .monaco-action-bar .action-item .action-label.clear-extensions, .hc-black .monaco-action-bar .action-item .action-label.clear-extensions { background: url('clear-inverse.svg') center center no-repeat; } .monaco-action-bar .action-item .action-label.extension-action.enable:after, .monaco-action-bar .action-item .action-label.extension-action.disable:after { content: 'โ–ผ'; padding-left: 2px; font-size: 80%; } .monaco-action-bar .action-item.disabled .action-label.extension-action.install:not(.installing), .monaco-action-bar .action-item.disabled .action-label.extension-action.uninstall:not(.uninstalling), .monaco-action-bar .action-item.disabled .action-label.extension-action.update, .monaco-action-bar .action-item.disabled .action-label.extension-action.enable, .monaco-action-bar .action-item.disabled .action-label.extension-action.disable, .monaco-action-bar .action-item.disabled .action-label.extension-action.reload, .monaco-action-bar .action-item.disabled .action-label.disable-status.hide, .monaco-action-bar .action-item.disabled .action-label.malicious-status.not-malicious { display: none; } .monaco-action-bar .action-item .action-label.disable-status, .monaco-action-bar .action-item .action-label.malicious-status { border-radius: 4px; color: inherit; background-color: transparent; opacity: 0.9; font-style: italic; padding: 0 5px; line-height: initial; } .extension-editor>.header>.details>.actions>.monaco-action-bar .action-item .action-label.disable-status, .extension-editor>.header>.details>.actions>.monaco-action-bar .action-item .action-label.malicious-status { font-weight: normal; } .extensions-viewlet>.extensions .extension>.details>.footer>.monaco-action-bar .action-item .action-label.extension-action.manage.hide { display: none; } .extensions-viewlet>.extensions .extension>.details>.footer>.monaco-action-bar .action-item .action-label.extension-action.manage { height: 18px; width: 10px; border: none; background: url('manage.svg') center center no-repeat; } .hc-black .extensions-viewlet>.extensions .extension>.details>.footer>.monaco-action-bar .action-item .action-label.extension-action.manage, .vs-dark .extensions-viewlet>.extensions .extension>.details>.footer>.monaco-action-bar .action-item .action-label.extension-action.manage { background: url('manage-inverse.svg') center center no-repeat; }
src/vs/workbench/parts/extensions/browser/media/extensionActions.css
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017485450371168554, 0.00016937260807026178, 0.00016708300972823054, 0.00016917490574996918, 0.0000024483222205162747 ]
{ "id": 9, "code_window": [ "\t\tthis._editor = editor;\n", "\t\tthis._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService);\n", "\t}\n", "\n", "\tdispose(): void {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(this._editor.onDidAttemptReadOnlyEdit(() => this._onDidAttemptReadOnlyEdit()));\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 47 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "workbenchConfigurationTitle": "Banc d'essai", "workbench.startupEditor.none": "Dรฉmarrage sans รฉditeur.", "workbench.startupEditor.welcomePage": "Ouvre la page de bienvenue (par dรฉfaut).", "workbench.startupEditor.newUntitledFile": "Ouverture d'un nouveau fichier sans titre.", "workbench.startupEditor": "Dรฉfinit quel รฉditeur sโ€™affiche au dรฉmarrage, si aucun nโ€™est restaurรฉ ร  partir de la session prรฉcรฉdente. Sรฉlectionnez 'none' pour dรฉmarrer sans รฉditeur, 'welcomePage' pour ouvrir la page dโ€™accueil (par dรฉfaut), 'newUntitledFile' pour ouvrir un nouveau fichier sans titre (seulement lors de l'ouverture d'un espace de travail vide).", "help": "Aide" }
i18n/fra/src/vs/workbench/parts/welcome/page/electron-browser/welcomePage.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017353221483062953, 0.00017003031098283827, 0.0001665283925831318, 0.00017003031098283827, 0.0000035019111237488687 ]
{ "id": 9, "code_window": [ "\t\tthis._editor = editor;\n", "\t\tthis._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService);\n", "\t}\n", "\n", "\tdispose(): void {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(this._editor.onDidAttemptReadOnlyEdit(() => this._onDidAttemptReadOnlyEdit()));\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 47 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "disableOtherKeymapsConfirmation": "่ฆๅœ็”จๅ…ถไป–ๆŒ‰้ตๅฐๆ‡‰ ({0})๏ผŒไปฅ้ฟๅ…ๆŒ‰้ต็นซ็ต้—œไฟ‚้–“็š„่ก็ชๅ—Ž?", "yes": "ๆ˜ฏ", "no": "ๅฆ", "betterMergeDisabled": "็›ฎๅ‰ๅทฒๅ…งๅปบ Better Merge ๅปถไผธๆจก็ต„๏ผŒๅฎ‰่ฃ็š„ๅปถไผธๆจก็ต„ๅทฒๅœ็”จไธฆไธ”ๅฏไปฅ็งป้™คใ€‚", "uninstall": "่งฃ้™คๅฎ‰่ฃ" }
i18n/cht/src/vs/workbench/parts/extensions/electron-browser/extensionsUtils.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0001722798915579915, 0.00017065451538655907, 0.00016902913921512663, 0.00017065451538655907, 0.0000016253761714324355 ]
{ "id": 10, "code_window": [ "\t}\n", "\n", "\tdispose(): void {\n", "\t\tthis._visible.reset();\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tsuper.dispose();\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 50 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./messageController'; import { setDisposableTimeout } from 'vs/base/common/async'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { ICodeEditor, IContentWidget, IContentWidgetPosition, ContentWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IPosition } from 'vs/editor/common/core/position'; import { registerThemingParticipant, HIGH_CONTRAST } from 'vs/platform/theme/common/themeService'; import { inputValidationInfoBorder, inputValidationInfoBackground } from 'vs/platform/theme/common/colorRegistry'; import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; export class MessageController implements editorCommon.IEditorContribution { private static readonly _id = 'editor.contrib.messageController'; static MESSAGE_VISIBLE = new RawContextKey<boolean>('messageVisible', false); static get(editor: ICodeEditor): MessageController { return editor.getContribution<MessageController>(MessageController._id); } getId(): string { return MessageController._id; } private _editor: ICodeEditor; private _visible: IContextKey<boolean>; private _messageWidget: MessageWidget; private _messageListeners: IDisposable[] = []; constructor( editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService ) { this._editor = editor; this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService); } dispose(): void { this._visible.reset(); } isVisible() { return this._visible.get(); } showMessage(message: string, position: IPosition): void { alert(message); this._visible.set(true); dispose(this._messageWidget); this._messageListeners = dispose(this._messageListeners); this._messageWidget = new MessageWidget(this._editor, position, message); // close on blur, cursor, model change, dispose this._messageListeners.push(this._editor.onDidBlurEditorText(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeCursorPosition(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidDispose(() => this.closeMessage())); this._messageListeners.push(this._editor.onDidChangeModel(() => this.closeMessage())); // close after 3s this._messageListeners.push(setDisposableTimeout(() => this.closeMessage(), 3000)); // close on mouse move let bounds: Range; this._messageListeners.push(this._editor.onMouseMove(e => { // outside the text area if (!e.target.position) { return; } if (!bounds) { // define bounding box around position and first mouse occurance bounds = new Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1); } else if (!bounds.containsPosition(e.target.position)) { // check if position is still in bounds this.closeMessage(); } })); } closeMessage(): void { this._visible.reset(); this._messageListeners = dispose(this._messageListeners); this._messageListeners.push(MessageWidget.fadeOut(this._messageWidget)); } } const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get); registerEditorCommand(new MessageCommand({ id: 'leaveEditorMessage', precondition: MessageController.MESSAGE_VISIBLE, handler: c => c.closeMessage(), kbOpts: { weight: KeybindingsRegistry.WEIGHT.editorContrib(30), primary: KeyCode.Escape } })); class MessageWidget implements IContentWidget { // Editor.IContentWidget.allowEditorOverflow readonly allowEditorOverflow = true; readonly suppressMouseDown = false; private _editor: ICodeEditor; private _position: IPosition; private _domNode: HTMLDivElement; static fadeOut(messageWidget: MessageWidget): IDisposable { let handle: number; const dispose = () => { messageWidget.dispose(); clearTimeout(handle); messageWidget.getDomNode().removeEventListener('animationend', dispose); }; handle = setTimeout(dispose, 110); messageWidget.getDomNode().addEventListener('animationend', dispose); messageWidget.getDomNode().classList.add('fadeOut'); return { dispose }; } constructor(editor: ICodeEditor, { lineNumber, column }: IPosition, text: string) { this._editor = editor; this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, editorCommon.ScrollType.Smooth); this._position = { lineNumber, column: column - 1 }; this._domNode = document.createElement('div'); this._domNode.classList.add('monaco-editor-overlaymessage'); const message = document.createElement('div'); message.classList.add('message'); message.textContent = text; this._domNode.appendChild(message); const anchor = document.createElement('div'); anchor.classList.add('anchor'); this._domNode.appendChild(anchor); this._editor.addContentWidget(this); this._domNode.classList.add('fadeIn'); } dispose() { this._editor.removeContentWidget(this); } getId(): string { return 'messageoverlay'; } getDomNode(): HTMLElement { return this._domNode; } getPosition(): IContentWidgetPosition { return { position: this._position, preference: [ContentWidgetPositionPreference.ABOVE] }; } } registerEditorContribution(MessageController); registerThemingParticipant((theme, collector) => { let border = theme.getColor(inputValidationInfoBorder); if (border) { let borderWidth = theme.type === 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}; }`); } let background = theme.getColor(inputValidationInfoBackground); if (background) { collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { background-color: ${background}; }`); } });
src/vs/editor/contrib/message/messageController.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.13645529747009277, 0.015274377539753914, 0.00016576510097365826, 0.00018405640730634332, 0.032307155430316925 ]
{ "id": 10, "code_window": [ "\t}\n", "\n", "\tdispose(): void {\n", "\t\tthis._visible.reset();\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tsuper.dispose();\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 50 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import URI from 'vs/base/common/uri'; import { TPromise } from 'vs/base/common/winjs.base'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IEditor, Position, IEditorOptions } from 'vs/platform/editor/common/editor'; import { ITextModel } from 'vs/editor/common/model'; import { IRange } from 'vs/editor/common/core/range'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { join } from 'vs/base/common/paths'; import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { Event } from 'vs/base/common/event'; import { IStringDictionary } from 'vs/base/common/collections'; import { ILocalExtension } from 'vs/platform/extensionManagement/common/extensionManagement'; import { localize } from 'vs/nls'; export interface ISettingsGroup { id: string; range: IRange; title: string; titleRange: IRange; sections: ISettingsSection[]; } export interface ISettingsSection { titleRange?: IRange; title?: string; settings: ISetting[]; } export interface ISetting { range: IRange; key: string; keyRange: IRange; value: any; valueRange: IRange; description: string[]; descriptionRanges: IRange[]; overrides?: ISetting[]; overrideOf?: ISetting; } export interface IExtensionSetting extends ISetting { extensionName: string; extensionPublisher: string; } export interface ISearchResult { filterMatches: ISettingMatch[]; metadata?: IFilterMetadata; } export interface ISearchResultGroup { id: string; label: string; result: ISearchResult; order: number; } export interface IFilterResult { query?: string; filteredGroups: ISettingsGroup[]; allGroups: ISettingsGroup[]; matches: IRange[]; metadata?: IStringDictionary<IFilterMetadata>; } export interface ISettingMatch { setting: ISetting; matches: IRange[]; score: number; } export interface IScoredResults { [key: string]: IRemoteSetting; } export interface IRemoteSetting { score: number; key: string; id: string; defaultValue: string; description: string; packageId: string; extensionName?: string; extensionPublisher?: string; } export interface IFilterMetadata { requestUrl: string; requestBody: string; timestamp: number; duration: number; scoredResults: IScoredResults; extensions?: ILocalExtension[]; /** The number of requests made, since requests are split by number of filters */ requestCount?: number; /** The name of the server that actually served the request */ context: string; } export interface IPreferencesEditorModel<T> { uri: URI; getPreference(key: string): T; dispose(): void; } export type IGroupFilter = (group: ISettingsGroup) => boolean; export type ISettingMatcher = (setting: ISetting, group: ISettingsGroup) => { matches: IRange[], score: number }; export interface ISettingsEditorModel extends IPreferencesEditorModel<ISetting> { readonly onDidChangeGroups: Event<void>; settingsGroups: ISettingsGroup[]; filterSettings(filter: string, groupFilter: IGroupFilter, settingMatcher: ISettingMatcher): ISettingMatch[]; findValueMatches(filter: string, setting: ISetting): IRange[]; updateResultGroup(id: string, resultGroup: ISearchResultGroup): IFilterResult; } export interface IKeybindingsEditorModel<T> extends IPreferencesEditorModel<T> { } export const IPreferencesService = createDecorator<IPreferencesService>('preferencesService'); export interface IPreferencesService { _serviceBrand: any; userSettingsResource: URI; workspaceSettingsResource: URI; getFolderSettingsResource(resource: URI): URI; resolveModel(uri: URI): TPromise<ITextModel>; createPreferencesEditorModel<T>(uri: URI): TPromise<IPreferencesEditorModel<T>>; openRawDefaultSettings(): TPromise<void>; openSettings(): TPromise<IEditor>; openGlobalSettings(options?: IEditorOptions, position?: Position): TPromise<IEditor>; openWorkspaceSettings(options?: IEditorOptions, position?: Position): TPromise<IEditor>; openFolderSettings(folder: URI, options?: IEditorOptions, position?: Position): TPromise<IEditor>; switchSettings(target: ConfigurationTarget, resource: URI): TPromise<void>; openGlobalKeybindingSettings(textual: boolean): TPromise<void>; configureSettingsForLanguage(language: string): void; } export function getSettingsTargetName(target: ConfigurationTarget, resource: URI, workspaceContextService: IWorkspaceContextService): string { switch (target) { case ConfigurationTarget.USER: return localize('userSettingsTarget', "User Settings"); case ConfigurationTarget.WORKSPACE: return localize('workspaceSettingsTarget', "Workspace Settings"); case ConfigurationTarget.WORKSPACE_FOLDER: const folder = workspaceContextService.getWorkspaceFolder(resource); return folder ? folder.name : ''; } return ''; } export const FOLDER_SETTINGS_PATH = join('.vscode', 'settings.json'); export const DEFAULT_SETTINGS_EDITOR_SETTING = 'workbench.settings.openDefaultSettings';
src/vs/workbench/services/preferences/common/preferences.ts
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0007441593916155398, 0.00020497576042544097, 0.00016658572712913156, 0.00016938069893512875, 0.00013490307901520282 ]
{ "id": 10, "code_window": [ "\t}\n", "\n", "\tdispose(): void {\n", "\t\tthis._visible.reset();\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tsuper.dispose();\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 50 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "breakpointDisabledHover": "ํ•ด์ œ๋œ ์ค‘๋‹จ์ ", "breakpointUnverifieddHover": "ํ™•์ธ๋˜์ง€ ์•Š์€ ์ค‘๋‹จ์ ", "breakpointDirtydHover": "ํ™•์ธ๋˜์ง€ ์•Š์€ ์ค‘๋‹จ์ ์ž…๋‹ˆ๋‹ค. ํŒŒ์ผ์ด ์ˆ˜์ •๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๋””๋ฒ„๊ทธ ์„ธ์…˜์„ ๋‹ค์‹œ ์‹œ์ž‘ํ•˜์„ธ์š”.", "breakpointUnsupported": "์ด ๋””๋ฒ„๊ทธ ํ˜•์‹์—์„œ ์ง€์›๋˜์ง€ ์•Š๋Š” ์กฐ๊ฑด๋ถ€ ์ค‘๋‹จ์ " }
i18n/kor/src/vs/workbench/parts/debug/browser/debugEditorModelManager.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017291316180489957, 0.0001699755375739187, 0.00016703792789485306, 0.0001699755375739187, 0.000002937616955023259 ]
{ "id": 10, "code_window": [ "\t}\n", "\n", "\tdispose(): void {\n", "\t\tthis._visible.reset();\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tsuper.dispose();\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 50 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "debugExceptionWidgetBorder": "A kivรฉtelmodul keretszรญne.", "debugExceptionWidgetBackground": "A kivรฉtelmodul hรกttรฉrszรญne.", "exceptionThrownWithId": "Kivรฉtel kรถvetkezett be: {0}", "exceptionThrown": "Kivรฉtel kรถvetkezett be." }
i18n/hun/src/vs/workbench/parts/debug/browser/exceptionWidget.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017504584684502333, 0.0001722707092994824, 0.00016949557175394148, 0.0001722707092994824, 0.000002775137545540929 ]
{ "id": 11, "code_window": [ "\t\tthis._messageListeners = dispose(this._messageListeners);\n", "\t\tthis._messageListeners.push(MessageWidget.fadeOut(this._messageWidget));\n", "\t}\n", "}\n", "\n", "const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get);\n", "\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tprivate _onDidAttemptReadOnlyEdit(): void {\n", "\t\tthis.showMessage(nls.localize('editor.readonly', \"Cannot edit in read-only editor\"), this._editor.getPosition());\n", "\t}\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import * as strings from 'vs/base/common/strings'; import { onUnexpectedError } from 'vs/base/common/errors'; import { CursorCollection } from 'vs/editor/common/controller/cursorCollection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { Selection, SelectionDirection, ISelection } from 'vs/editor/common/core/selection'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { CursorColumns, CursorConfiguration, EditOperationResult, CursorContext, CursorState, RevealTarget, IColumnSelectData, ICursors, EditOperationType } from 'vs/editor/common/controller/cursorCommon'; import { DeleteOperations } from 'vs/editor/common/controller/cursorDeleteOperations'; import { TypeOperations } from 'vs/editor/common/controller/cursorTypeOperations'; import { RawContentChangedType } from 'vs/editor/common/model/textModelEvents'; import { CursorChangeReason } from 'vs/editor/common/controller/cursorEvents'; import { IViewModel } from 'vs/editor/common/viewModel/viewModel'; import * as viewEvents from 'vs/editor/common/view/viewEvents'; import { Event, Emitter } from 'vs/base/common/event'; import { ITextModel, IIdentifiedSingleEditOperation, TrackedRangeStickiness } from 'vs/editor/common/model'; function containsLineMappingChanged(events: viewEvents.ViewEvent[]): boolean { for (let i = 0, len = events.length; i < len; i++) { if (events[i].type === viewEvents.ViewEventType.ViewLineMappingChanged) { return true; } } return false; } export class CursorStateChangedEvent { /** * The new selections. * The primary selection is always at index 0. */ readonly selections: Selection[]; /** * Source of the call that caused the event. */ readonly source: string; /** * Reason. */ readonly reason: CursorChangeReason; constructor(selections: Selection[], source: string, reason: CursorChangeReason) { this.selections = selections; this.source = source; this.reason = reason; } } /** * A snapshot of the cursor and the model state */ export class CursorModelState { public readonly modelVersionId: number; public readonly cursorState: CursorState[]; constructor(model: ITextModel, cursor: Cursor) { this.modelVersionId = model.getVersionId(); this.cursorState = cursor.getAll(); } public equals(other: CursorModelState): boolean { if (!other) { return false; } if (this.modelVersionId !== other.modelVersionId) { return false; } if (this.cursorState.length !== other.cursorState.length) { return false; } for (let i = 0, len = this.cursorState.length; i < len; i++) { if (!this.cursorState[i].equals(other.cursorState[i])) { return false; } } return true; } } export class Cursor extends viewEvents.ViewEventEmitter implements ICursors { public static MAX_CURSOR_COUNT = 10000; private readonly _onDidReachMaxCursorCount: Emitter<void> = this._register(new Emitter<void>()); public readonly onDidReachMaxCursorCount: Event<void> = this._onDidReachMaxCursorCount.event; private readonly _onDidChange: Emitter<CursorStateChangedEvent> = this._register(new Emitter<CursorStateChangedEvent>()); public readonly onDidChange: Event<CursorStateChangedEvent> = this._onDidChange.event; private readonly _configuration: editorCommon.IConfiguration; private readonly _model: ITextModel; private _knownModelVersionId: number; private readonly _viewModel: IViewModel; public context: CursorContext; private _cursors: CursorCollection; private _isHandling: boolean; private _isDoingComposition: boolean; private _columnSelectData: IColumnSelectData; private _prevEditOperationType: EditOperationType; constructor(configuration: editorCommon.IConfiguration, model: ITextModel, viewModel: IViewModel) { super(); this._configuration = configuration; this._model = model; this._knownModelVersionId = this._model.getVersionId(); this._viewModel = viewModel; this.context = new CursorContext(this._configuration, this._model, this._viewModel); this._cursors = new CursorCollection(this.context); this._isHandling = false; this._isDoingComposition = false; this._columnSelectData = null; this._prevEditOperationType = EditOperationType.Other; this._register(this._model.onDidChangeRawContent((e) => { this._knownModelVersionId = e.versionId; if (this._isHandling) { return; } let hadFlushEvent = e.containsEvent(RawContentChangedType.Flush); this._onModelContentChanged(hadFlushEvent); })); this._register(viewModel.addEventListener((events: viewEvents.ViewEvent[]) => { if (!containsLineMappingChanged(events)) { return; } if (this._knownModelVersionId !== this._model.getVersionId()) { // There are model change events that I didn't yet receive. // // This can happen when editing the model, and the view model receives the change events first, // and the view model emits line mapping changed events, all before the cursor gets a chance to // recover from markers. // // The model change listener above will be called soon and we'll ensure a valid cursor state there. return; } // Ensure valid state this.setStates('viewModel', CursorChangeReason.NotSet, this.getAll()); })); const updateCursorContext = () => { this.context = new CursorContext(this._configuration, this._model, this._viewModel); this._cursors.updateContext(this.context); }; this._register(this._model.onDidChangeLanguage((e) => { updateCursorContext(); })); this._register(this._model.onDidChangeLanguageConfiguration(() => { updateCursorContext(); })); this._register(this._model.onDidChangeOptions(() => { updateCursorContext(); })); this._register(this._configuration.onDidChange((e) => { if (CursorConfiguration.shouldRecreate(e)) { updateCursorContext(); } })); } public dispose(): void { this._cursors.dispose(); super.dispose(); } // ------ some getters/setters public getPrimaryCursor(): CursorState { return this._cursors.getPrimaryCursor(); } public getLastAddedCursorIndex(): number { return this._cursors.getLastAddedCursorIndex(); } public getAll(): CursorState[] { return this._cursors.getAll(); } public setStates(source: string, reason: CursorChangeReason, states: CursorState[]): void { if (states.length > Cursor.MAX_CURSOR_COUNT) { states = states.slice(0, Cursor.MAX_CURSOR_COUNT); this._onDidReachMaxCursorCount.fire(void 0); } const oldState = new CursorModelState(this._model, this); this._cursors.setStates(states); this._cursors.normalize(); this._columnSelectData = null; this._emitStateChangedIfNecessary(source, reason, oldState); } public setColumnSelectData(columnSelectData: IColumnSelectData): void { this._columnSelectData = columnSelectData; } public reveal(horizontal: boolean, target: RevealTarget, scrollType: editorCommon.ScrollType): void { this._revealRange(target, viewEvents.VerticalRevealType.Simple, horizontal, scrollType); } public revealRange(revealHorizontal: boolean, viewRange: Range, verticalType: viewEvents.VerticalRevealType, scrollType: editorCommon.ScrollType) { this.emitCursorRevealRange(viewRange, verticalType, revealHorizontal, scrollType); } public scrollTo(desiredScrollTop: number): void { this._viewModel.viewLayout.setScrollPositionSmooth({ scrollTop: desiredScrollTop }); } public saveState(): editorCommon.ICursorState[] { let result: editorCommon.ICursorState[] = []; const selections = this._cursors.getSelections(); for (let i = 0, len = selections.length; i < len; i++) { const selection = selections[i]; result.push({ inSelectionMode: !selection.isEmpty(), selectionStart: { lineNumber: selection.selectionStartLineNumber, column: selection.selectionStartColumn, }, position: { lineNumber: selection.positionLineNumber, column: selection.positionColumn, } }); } return result; } public restoreState(states: editorCommon.ICursorState[]): void { let desiredSelections: ISelection[] = []; for (let i = 0, len = states.length; i < len; i++) { const state = states[i]; let positionLineNumber = 1; let positionColumn = 1; // Avoid missing properties on the literal if (state.position && state.position.lineNumber) { positionLineNumber = state.position.lineNumber; } if (state.position && state.position.column) { positionColumn = state.position.column; } let selectionStartLineNumber = positionLineNumber; let selectionStartColumn = positionColumn; // Avoid missing properties on the literal if (state.selectionStart && state.selectionStart.lineNumber) { selectionStartLineNumber = state.selectionStart.lineNumber; } if (state.selectionStart && state.selectionStart.column) { selectionStartColumn = state.selectionStart.column; } desiredSelections.push({ selectionStartLineNumber: selectionStartLineNumber, selectionStartColumn: selectionStartColumn, positionLineNumber: positionLineNumber, positionColumn: positionColumn }); } this.setStates('restoreState', CursorChangeReason.NotSet, CursorState.fromModelSelections(desiredSelections)); this.reveal(true, RevealTarget.Primary, editorCommon.ScrollType.Immediate); } private _onModelContentChanged(hadFlushEvent: boolean): void { this._prevEditOperationType = EditOperationType.Other; if (hadFlushEvent) { // a model.setValue() was called this._cursors.dispose(); this._cursors = new CursorCollection(this.context); this._emitStateChangedIfNecessary('model', CursorChangeReason.ContentFlush, null); } else { const selectionsFromMarkers = this._cursors.readSelectionFromMarkers(); this.setStates('modelChange', CursorChangeReason.RecoverFromMarkers, CursorState.fromModelSelections(selectionsFromMarkers)); } } public getSelection(): Selection { return this._cursors.getPrimaryCursor().modelState.selection; } public getColumnSelectData(): IColumnSelectData { if (this._columnSelectData) { return this._columnSelectData; } const primaryCursor = this._cursors.getPrimaryCursor(); const primaryPos = primaryCursor.viewState.position; return { toViewLineNumber: primaryPos.lineNumber, toViewVisualColumn: CursorColumns.visibleColumnFromColumn2(this.context.config, this.context.viewModel, primaryPos) }; } public getSelections(): Selection[] { return this._cursors.getSelections(); } public getViewSelections(): Selection[] { return this._cursors.getViewSelections(); } public getPosition(): Position { return this._cursors.getPrimaryCursor().modelState.position; } public setSelections(source: string, selections: ISelection[]): void { this.setStates(source, CursorChangeReason.NotSet, CursorState.fromModelSelections(selections)); } public getPrevEditOperationType(): EditOperationType { return this._prevEditOperationType; } public setPrevEditOperationType(type: EditOperationType): void { this._prevEditOperationType = type; } // ------ auxiliary handling logic private _executeEditOperation(opResult: EditOperationResult): void { if (!opResult) { // Nothing to execute return; } if (opResult.shouldPushStackElementBefore) { this._model.pushStackElement(); } const result = CommandExecutor.executeCommands(this._model, this._cursors.getSelections(), opResult.commands); if (result) { // The commands were applied correctly this._interpretCommandResult(result); this._prevEditOperationType = opResult.type; } if (opResult.shouldPushStackElementAfter) { this._model.pushStackElement(); } } private _interpretCommandResult(cursorState: Selection[]): void { if (!cursorState || cursorState.length === 0) { cursorState = this._cursors.readSelectionFromMarkers(); } this._columnSelectData = null; this._cursors.setSelections(cursorState); this._cursors.normalize(); } // ----------------------------------------------------------------------------------------------------------- // ----- emitting events private _emitStateChangedIfNecessary(source: string, reason: CursorChangeReason, oldState: CursorModelState): boolean { const newState = new CursorModelState(this._model, this); if (newState.equals(oldState)) { return false; } const selections = this._cursors.getSelections(); const viewSelections = this._cursors.getViewSelections(); // Let the view get the event first. try { const eventsCollector = this._beginEmit(); eventsCollector.emit(new viewEvents.ViewCursorStateChangedEvent(viewSelections)); } finally { this._endEmit(); } // Only after the view has been notified, let the rest of the world know... if (!oldState || oldState.cursorState.length !== newState.cursorState.length || newState.cursorState.some((newCursorState, i) => !newCursorState.modelState.equals(oldState.cursorState[i].modelState)) ) { this._onDidChange.fire(new CursorStateChangedEvent(selections, source || 'keyboard', reason)); } return true; } private _revealRange(revealTarget: RevealTarget, verticalType: viewEvents.VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType): void { const viewPositions = this._cursors.getViewPositions(); let viewPosition = viewPositions[0]; if (revealTarget === RevealTarget.TopMost) { for (let i = 1; i < viewPositions.length; i++) { if (viewPositions[i].isBefore(viewPosition)) { viewPosition = viewPositions[i]; } } } else if (revealTarget === RevealTarget.BottomMost) { for (let i = 1; i < viewPositions.length; i++) { if (viewPosition.isBeforeOrEqual(viewPositions[i])) { viewPosition = viewPositions[i]; } } } else { if (viewPositions.length > 1) { // no revealing! return; } } const viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column); this.emitCursorRevealRange(viewRange, verticalType, revealHorizontal, scrollType); } public emitCursorRevealRange(viewRange: Range, verticalType: viewEvents.VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType) { try { const eventsCollector = this._beginEmit(); eventsCollector.emit(new viewEvents.ViewRevealRangeRequestEvent(viewRange, verticalType, revealHorizontal, scrollType)); } finally { this._endEmit(); } } // ----------------------------------------------------------------------------------------------------------- // ----- handlers beyond this point public trigger(source: string, handlerId: string, payload: any): void { const H = editorCommon.Handler; if (handlerId === H.CompositionStart) { this._isDoingComposition = true; return; } if (handlerId === H.CompositionEnd) { this._isDoingComposition = false; return; } if (this._configuration.editor.readOnly) { // All the remaining handlers will try to edit the model, // but we cannot edit when read only... return; } const oldState = new CursorModelState(this._model, this); let cursorChangeReason = CursorChangeReason.NotSet; // ensure valid state on all cursors this._cursors.ensureValidState(); this._isHandling = true; try { switch (handlerId) { case H.Type: this._type(source, <string>payload.text); break; case H.ReplacePreviousChar: this._replacePreviousChar(<string>payload.text, <number>payload.replaceCharCnt); break; case H.Paste: cursorChangeReason = CursorChangeReason.Paste; this._paste(<string>payload.text, <boolean>payload.pasteOnNewLine, <string[]>payload.multicursorText); break; case H.Cut: this._cut(); break; case H.Undo: cursorChangeReason = CursorChangeReason.Undo; this._interpretCommandResult(this._model.undo()); break; case H.Redo: cursorChangeReason = CursorChangeReason.Redo; this._interpretCommandResult(this._model.redo()); break; case H.ExecuteCommand: this._externalExecuteCommand(<editorCommon.ICommand>payload); break; case H.ExecuteCommands: this._externalExecuteCommands(<editorCommon.ICommand[]>payload); break; } } catch (err) { onUnexpectedError(err); } this._isHandling = false; if (this._emitStateChangedIfNecessary(source, cursorChangeReason, oldState)) { this._revealRange(RevealTarget.Primary, viewEvents.VerticalRevealType.Simple, true, editorCommon.ScrollType.Smooth); } } private _type(source: string, text: string): void { if (!this._isDoingComposition && source === 'keyboard') { // If this event is coming straight from the keyboard, look for electric characters and enter for (let i = 0, len = text.length; i < len; i++) { let charCode = text.charCodeAt(i); let chr: string; 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(TypeOperations.typeWithInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), chr)); } } else { this._executeEditOperation(TypeOperations.typeWithoutInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), text)); } } private _replacePreviousChar(text: string, replaceCharCnt: number): void { this._executeEditOperation(TypeOperations.replacePreviousChar(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), text, replaceCharCnt)); } private _paste(text: string, pasteOnNewLine: boolean, multicursorText: string[]): void { this._executeEditOperation(TypeOperations.paste(this.context.config, this.context.model, this.getSelections(), text, pasteOnNewLine, multicursorText)); } private _cut(): void { this._executeEditOperation(DeleteOperations.cut(this.context.config, this.context.model, this.getSelections())); } private _externalExecuteCommand(command: editorCommon.ICommand): void { this._cursors.killSecondaryCursors(); this._executeEditOperation(new EditOperationResult(EditOperationType.Other, [command], { shouldPushStackElementBefore: false, shouldPushStackElementAfter: false })); } private _externalExecuteCommands(commands: editorCommon.ICommand[]): void { this._executeEditOperation(new EditOperationResult(EditOperationType.Other, commands, { shouldPushStackElementBefore: false, shouldPushStackElementAfter: false })); } } interface IExecContext { readonly model: ITextModel; readonly selectionsBefore: Selection[]; readonly trackedRanges: string[]; readonly trackedRangesDirection: SelectionDirection[]; } interface ICommandData { operations: IIdentifiedSingleEditOperation[]; hadTrackedEditOperation: boolean; } interface ICommandsData { operations: IIdentifiedSingleEditOperation[]; hadTrackedEditOperation: boolean; } class CommandExecutor { public static executeCommands(model: ITextModel, selectionsBefore: Selection[], commands: editorCommon.ICommand[]): Selection[] { const ctx: IExecContext = { model: model, selectionsBefore: selectionsBefore, trackedRanges: [], trackedRangesDirection: [] }; const result = this._innerExecuteCommands(ctx, commands); for (let i = 0, len = ctx.trackedRanges.length; i < len; i++) { ctx.model._setTrackedRange(ctx.trackedRanges[i], null, TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges); } return result; } private static _innerExecuteCommands(ctx: IExecContext, commands: editorCommon.ICommand[]): Selection[] { if (this._arrayIsEmpty(commands)) { return null; } const commandsData = this._getEditOperations(ctx, commands); if (commandsData.operations.length === 0) { return null; } const rawOperations = commandsData.operations; const loserCursorsMap = this._getLoserCursorMap(rawOperations); if (loserCursorsMap.hasOwnProperty('0')) { // These commands are very messed up console.warn('Ignoring commands'); return null; } // Remove operations belonging to losing cursors let filteredOperations: IIdentifiedSingleEditOperation[] = []; for (let i = 0, len = rawOperations.length; i < len; i++) { if (!loserCursorsMap.hasOwnProperty(rawOperations[i].identifier.major.toString())) { filteredOperations.push(rawOperations[i]); } } // TODO@Alex: find a better way to do this. // give the hint that edit operations are tracked to the model if (commandsData.hadTrackedEditOperation && filteredOperations.length > 0) { filteredOperations[0]._isTracked = true; } const selectionsAfter = ctx.model.pushEditOperations(ctx.selectionsBefore, filteredOperations, (inverseEditOperations: IIdentifiedSingleEditOperation[]): Selection[] => { let groupedInverseEditOperations: IIdentifiedSingleEditOperation[][] = []; for (let i = 0; i < ctx.selectionsBefore.length; i++) { groupedInverseEditOperations[i] = []; } for (let i = 0; i < inverseEditOperations.length; i++) { const op = inverseEditOperations[i]; if (!op.identifier) { // perhaps auto whitespace trim edits continue; } groupedInverseEditOperations[op.identifier.major].push(op); } const minorBasedSorter = (a: IIdentifiedSingleEditOperation, b: IIdentifiedSingleEditOperation) => { return a.identifier.minor - b.identifier.minor; }; let cursorSelections: Selection[] = []; for (let i = 0; i < ctx.selectionsBefore.length; i++) { if (groupedInverseEditOperations[i].length > 0) { groupedInverseEditOperations[i].sort(minorBasedSorter); cursorSelections[i] = commands[i].computeCursorState(ctx.model, { getInverseEditOperations: () => { return groupedInverseEditOperations[i]; }, getTrackedSelection: (id: string) => { const idx = parseInt(id, 10); const range = ctx.model._getTrackedRange(ctx.trackedRanges[idx]); if (ctx.trackedRangesDirection[idx] === SelectionDirection.LTR) { return new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn); } return new Selection(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn); } }); } else { cursorSelections[i] = ctx.selectionsBefore[i]; } } return cursorSelections; }); // Extract losing cursors let losingCursors: number[] = []; for (let losingCursorIndex in loserCursorsMap) { if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) { losingCursors.push(parseInt(losingCursorIndex, 10)); } } // Sort losing cursors descending losingCursors.sort((a: number, b: number): number => { return b - a; }); // Remove losing cursors for (let i = 0; i < losingCursors.length; i++) { selectionsAfter.splice(losingCursors[i], 1); } return selectionsAfter; } private static _arrayIsEmpty(commands: editorCommon.ICommand[]): boolean { for (let i = 0, len = commands.length; i < len; i++) { if (commands[i]) { return false; } } return true; } private static _getEditOperations(ctx: IExecContext, commands: editorCommon.ICommand[]): ICommandsData { let operations: IIdentifiedSingleEditOperation[] = []; let hadTrackedEditOperation: boolean = false; for (let i = 0, len = commands.length; i < len; i++) { if (commands[i]) { const r = this._getEditOperationsFromCommand(ctx, i, commands[i]); operations = operations.concat(r.operations); hadTrackedEditOperation = hadTrackedEditOperation || r.hadTrackedEditOperation; } } return { operations: operations, hadTrackedEditOperation: hadTrackedEditOperation }; } private static _getEditOperationsFromCommand(ctx: IExecContext, majorIdentifier: number, command: editorCommon.ICommand): ICommandData { // This method acts as a transaction, if the command fails // everything it has done is ignored let operations: IIdentifiedSingleEditOperation[] = []; let operationMinor = 0; const addEditOperation = (selection: Range, text: string) => { 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 }); }; let hadTrackedEditOperation = false; const addTrackedEditOperation = (selection: Range, text: string) => { hadTrackedEditOperation = true; addEditOperation(selection, text); }; const trackSelection = (selection: Selection, trackPreviousOnEmpty?: boolean) => { let stickiness: TrackedRangeStickiness; if (selection.isEmpty()) { if (typeof trackPreviousOnEmpty === 'boolean') { if (trackPreviousOnEmpty) { stickiness = TrackedRangeStickiness.GrowsOnlyWhenTypingBefore; } else { stickiness = TrackedRangeStickiness.GrowsOnlyWhenTypingAfter; } } else { // Try to lock it with surrounding text const maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber); if (selection.startColumn === maxLineColumn) { stickiness = TrackedRangeStickiness.GrowsOnlyWhenTypingBefore; } else { stickiness = TrackedRangeStickiness.GrowsOnlyWhenTypingAfter; } } } else { stickiness = TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges; } const l = ctx.trackedRanges.length; const id = ctx.model._setTrackedRange(null, selection, stickiness); ctx.trackedRanges[l] = id; ctx.trackedRangesDirection[l] = selection.getDirection(); return l.toString(); }; const editOperationBuilder: editorCommon.IEditOperationBuilder = { addEditOperation: addEditOperation, addTrackedEditOperation: addTrackedEditOperation, trackSelection: trackSelection }; try { command.getEditOperations(ctx.model, editOperationBuilder); } catch (e) { e.friendlyMessage = nls.localize('corrupt.commands', "Unexpected exception while executing command."); onUnexpectedError(e); return { operations: [], hadTrackedEditOperation: false }; } return { operations: operations, hadTrackedEditOperation: hadTrackedEditOperation }; } private static _getLoserCursorMap(operations: IIdentifiedSingleEditOperation[]): { [index: string]: boolean; } { // This is destructive on the array operations = operations.slice(0); // Sort operations with last one first operations.sort((a: IIdentifiedSingleEditOperation, b: IIdentifiedSingleEditOperation): number => { // Note the minus! return -(Range.compareRangesUsingEnds(a.range, b.range)); }); // Operations can not overlap! let loserCursorsMap: { [index: string]: boolean; } = {}; for (let i = 1; i < operations.length; i++) { const previousOp = operations[i - 1]; const currentOp = operations[i]; if (previousOp.range.getStartPosition().isBefore(currentOp.range.getEndPosition())) { let loserMajor: number; if (previousOp.identifier.major > currentOp.identifier.major) { // previousOp loses the battle loserMajor = previousOp.identifier.major; } else { loserMajor = currentOp.identifier.major; } loserCursorsMap[loserMajor.toString()] = true; for (let j = 0; j < operations.length; j++) { if (operations[j].identifier.major === loserMajor) { operations.splice(j, 1); if (j < i) { i--; } j--; } } if (i > 0) { i--; } } } return loserCursorsMap; } }
src/vs/editor/common/controller/cursor.ts
1
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0006478300201706588, 0.00017888136790134013, 0.0001653871440794319, 0.00017365338862873614, 0.00005063291246187873 ]
{ "id": 11, "code_window": [ "\t\tthis._messageListeners = dispose(this._messageListeners);\n", "\t\tthis._messageListeners.push(MessageWidget.fadeOut(this._messageWidget));\n", "\t}\n", "}\n", "\n", "const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get);\n", "\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tprivate _onDidAttemptReadOnlyEdit(): void {\n", "\t\tthis.showMessage(nls.localize('editor.readonly', \"Cannot edit in read-only editor\"), this._editor.getPosition());\n", "\t}\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 98 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "noWorkspace": "Aucun dossier ouvert", "explorerSection": "Section de l'Explorateur de fichiers", "noWorkspaceHelp": "Vous n'avez pas encore ajouter un dossier ร  l'espace de travail.", "addFolder": "Ajouter un dossier", "noFolderHelp": "Vous n'avez pas encore ouvert de dossier.", "openFolder": "Ouvrir le dossier" }
i18n/fra/src/vs/workbench/parts/files/electron-browser/views/emptyView.i18n.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017840682994574308, 0.00017601114814169705, 0.00017361546633765101, 0.00017601114814169705, 0.000002395681804046035 ]
{ "id": 11, "code_window": [ "\t\tthis._messageListeners = dispose(this._messageListeners);\n", "\t\tthis._messageListeners.push(MessageWidget.fadeOut(this._messageWidget));\n", "\t}\n", "}\n", "\n", "const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get);\n", "\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tprivate _onDidAttemptReadOnlyEdit(): void {\n", "\t\tthis.showMessage(nls.localize('editor.readonly', \"Cannot edit in read-only editor\"), this._editor.getPosition());\n", "\t}\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { KeybindingResolver } from 'vs/platform/keybinding/common/keybindingResolver'; import { IContextKey, IContext, IContextKeyServiceTarget, IContextKeyService, SET_CONTEXT_COMMAND_ID, ContextKeyExpr, IContextKeyChangeEvent } from 'vs/platform/contextkey/common/contextkey'; import { IConfigurationService, IConfigurationChangeEvent, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { Event, Emitter, debounceEvent } from 'vs/base/common/event'; const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context'; export class Context implements IContext { protected _parent: Context; protected _value: { [key: string]: any; }; protected _id: number; constructor(id: number, parent: Context) { this._id = id; this._parent = parent; this._value = Object.create(null); this._value['_contextId'] = id; } public setValue(key: string, value: any): boolean { // console.log('SET ' + key + ' = ' + value + ' ON ' + this._id); if (this._value[key] !== value) { this._value[key] = value; return true; } return false; } public removeValue(key: string): boolean { // console.log('REMOVE ' + key + ' FROM ' + this._id); if (key in this._value) { delete this._value[key]; return true; } return false; } public getValue<T>(key: string): T { const ret = this._value[key]; if (typeof ret === 'undefined' && this._parent) { return this._parent.getValue<T>(key); } return ret; } collectAllValues(): { [key: string]: any; } { let result = this._parent ? this._parent.collectAllValues() : Object.create(null); result = { ...result, ...this._value }; delete result['_contextId']; return result; } } class ConfigAwareContextValuesContainer extends Context { private readonly _emitter: Emitter<string | string[]>; private readonly _subscription: IDisposable; private readonly _configurationService: IConfigurationService; constructor(id: number, configurationService: IConfigurationService, emitter: Emitter<string | string[]>) { super(id, null); this._emitter = emitter; this._configurationService = configurationService; this._subscription = configurationService.onDidChangeConfiguration(this._onConfigurationUpdated, this); this._initFromConfiguration(); } public dispose() { this._subscription.dispose(); } private _onConfigurationUpdated(event: IConfigurationChangeEvent): void { if (event.source === ConfigurationTarget.DEFAULT) { // new setting, rebuild everything this._initFromConfiguration(); } else { // update those that we know for (const configKey of event.affectedKeys) { const contextKey = `config.${configKey}`; if (contextKey in this._value) { this._value[contextKey] = this._configurationService.getValue(configKey); this._emitter.fire(configKey); } } } } private _initFromConfiguration() { const prefix = 'config.'; const config = this._configurationService.getValue(); const configKeys: { [key: string]: boolean } = Object.create(null); const configKeysChanged: string[] = []; // add new value from config const walk = (obj: any, keys: string[]) => { for (let key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { keys.push(key); let value = obj[key]; if (typeof value === 'boolean') { const configKey = keys.join('.'); const oldValue = this._value[configKey]; this._value[configKey] = value; if (oldValue !== value) { configKeysChanged.push(configKey); configKeys[configKey] = true; } else { configKeys[configKey] = false; } } else if (typeof value === 'object') { walk(value, keys); } keys.pop(); } } }; walk(config, ['config']); // remove unused keys for (let key in this._value) { if (key.indexOf(prefix) === 0 && configKeys[key] === undefined) { delete this._value[key]; configKeys[key] = true; configKeysChanged.push(key); } } // send events this._emitter.fire(configKeysChanged); } } class ContextKey<T> implements IContextKey<T> { private _parent: AbstractContextKeyService; private _key: string; private _defaultValue: T; constructor(parent: AbstractContextKeyService, key: string, defaultValue: T) { this._parent = parent; this._key = key; this._defaultValue = defaultValue; this.reset(); } public set(value: T): void { this._parent.setContext(this._key, value); } public reset(): void { if (typeof this._defaultValue === 'undefined') { this._parent.removeContext(this._key); } else { this._parent.setContext(this._key, this._defaultValue); } } public get(): T { return this._parent.getContextKeyValue<T>(this._key); } } export class ContextKeyChangeEvent implements IContextKeyChangeEvent { private _keys: string[] = []; collect(oneOrManyKeys: string | string[]): void { this._keys = this._keys.concat(oneOrManyKeys); } affectsSome(keys: Set<string>): boolean { for (const key of this._keys) { if (keys.has(key)) { return true; } } return false; } } export abstract class AbstractContextKeyService implements IContextKeyService { public _serviceBrand: any; protected _onDidChangeContext: Event<IContextKeyChangeEvent>; protected _onDidChangeContextKey: Emitter<string | string[]>; protected _myContextId: number; constructor(myContextId: number) { this._myContextId = myContextId; this._onDidChangeContextKey = new Emitter<string>(); } abstract dispose(): void; public createKey<T>(key: string, defaultValue: T): IContextKey<T> { return new ContextKey(this, key, defaultValue); } public get onDidChangeContext(): Event<IContextKeyChangeEvent> { if (!this._onDidChangeContext) { this._onDidChangeContext = debounceEvent<string | string[], ContextKeyChangeEvent>(this._onDidChangeContextKey.event, (prev, cur) => { if (!prev) { prev = new ContextKeyChangeEvent(); } prev.collect(cur); return prev; }, 25); } return this._onDidChangeContext; } public createScoped(domNode: IContextKeyServiceTarget): IContextKeyService { return new ScopedContextKeyService(this, this._onDidChangeContextKey, domNode); } public contextMatchesRules(rules: ContextKeyExpr): boolean { const context = this.getContextValuesContainer(this._myContextId); const result = KeybindingResolver.contextMatchesRules(context, rules); // console.group(rules.serialize() + ' -> ' + result); // rules.keys().forEach(key => { console.log(key, ctx[key]); }); // console.groupEnd(); return result; } public getContextKeyValue<T>(key: string): T { return this.getContextValuesContainer(this._myContextId).getValue<T>(key); } public setContext(key: string, value: any): void { const myContext = this.getContextValuesContainer(this._myContextId); if (!myContext) { return; } if (myContext.setValue(key, value)) { this._onDidChangeContextKey.fire(key); } } public removeContext(key: string): void { if (this.getContextValuesContainer(this._myContextId).removeValue(key)) { this._onDidChangeContextKey.fire(key); } } public getContext(target: IContextKeyServiceTarget): IContext { return this.getContextValuesContainer(findContextAttr(target)); } public abstract getContextValuesContainer(contextId: number): Context; public abstract createChildContext(parentContextId?: number): number; public abstract disposeContext(contextId: number): void; } export class ContextKeyService extends AbstractContextKeyService implements IContextKeyService { private _lastContextId: number; private _contexts: { [contextId: string]: Context; }; private _toDispose: IDisposable[] = []; constructor(@IConfigurationService configurationService: IConfigurationService) { super(0); this._lastContextId = 0; this._contexts = Object.create(null); const myContext = new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContextKey); this._contexts[String(this._myContextId)] = myContext; this._toDispose.push(myContext); // 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); } public dispose(): void { this._toDispose = dispose(this._toDispose); } public getContextValuesContainer(contextId: number): Context { return this._contexts[String(contextId)]; } public createChildContext(parentContextId: number = this._myContextId): number { let id = (++this._lastContextId); this._contexts[String(id)] = new Context(id, this.getContextValuesContainer(parentContextId)); return id; } public disposeContext(contextId: number): void { delete this._contexts[String(contextId)]; } } class ScopedContextKeyService extends AbstractContextKeyService { private _parent: AbstractContextKeyService; private _domNode: IContextKeyServiceTarget; constructor(parent: AbstractContextKeyService, emitter: Emitter<string | string[]>, domNode?: IContextKeyServiceTarget) { super(parent.createChildContext()); this._parent = parent; this._onDidChangeContextKey = emitter; if (domNode) { this._domNode = domNode; this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId)); } } public dispose(): void { this._parent.disposeContext(this._myContextId); if (this._domNode) { this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR); } } public get onDidChangeContext(): Event<IContextKeyChangeEvent> { return this._parent.onDidChangeContext; } public getContextValuesContainer(contextId: number): Context { return this._parent.getContextValuesContainer(contextId); } public createChildContext(parentContextId: number = this._myContextId): number { return this._parent.createChildContext(parentContextId); } public disposeContext(contextId: number): void { this._parent.disposeContext(contextId); } } function findContextAttr(domNode: IContextKeyServiceTarget): number { while (domNode) { if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) { return parseInt(domNode.getAttribute(KEYBINDING_CONTEXT_ATTR), 10); } domNode = domNode.parentElement; } return 0; } CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, function (accessor, contextKey: any, contextValue: any) { accessor.get(IContextKeyService).createKey(String(contextKey), contextValue); });
src/vs/platform/contextkey/browser/contextKeyService.ts
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.0010356407146900892, 0.00023416284238919616, 0.00016328415949828923, 0.00017296939040534198, 0.00017470450256951153 ]
{ "id": 11, "code_window": [ "\t\tthis._messageListeners = dispose(this._messageListeners);\n", "\t\tthis._messageListeners.push(MessageWidget.fadeOut(this._messageWidget));\n", "\t}\n", "}\n", "\n", "const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get);\n", "\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tprivate _onDidAttemptReadOnlyEdit(): void {\n", "\t\tthis.showMessage(nls.localize('editor.readonly', \"Cannot edit in read-only editor\"), this._editor.getPosition());\n", "\t}\n" ], "file_path": "src/vs/editor/contrib/message/messageController.ts", "type": "add", "edit_start_line_idx": 98 }
// ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS: [{ "name": "Microsoft/TypeScript-TmLanguage", "version": "0.0.1", "license": "MIT", "repositoryURL": "https://github.com/Microsoft/TypeScript-TmLanguage", "description": "The file syntaxes/JavaScript.tmLanguage.json was derived from TypeScriptReact.tmLanguage in https://github.com/Microsoft/TypeScript-TmLanguage." }, { "name": "textmate/javascript.tmbundle", "version": "0.0.0", "license": "TextMate Bundle License", "repositoryURL": "https://github.com/textmate/javascript.tmbundle", "licenseDetail": [ "Copyright (c) textmate-javascript.tmbundle project authors", "", "If not otherwise specified (see below), files in this repository fall under the following license:", "", "Permission to copy, use, modify, sell and distribute this", "software is granted. This software is provided \"as is\" without", "express or implied warranty, and with no claim as to its", "suitability for any purpose.", "", "An exception is made for files in readable text which contain their own license information,", "or files where an accompanying file exists (in the same directory) with a \"-license\" suffix added", "to the base-name name of the original file, and an extension of txt, html, or similar. For example", "\"tidy\" is accompanied by \"tidy-license.txt\"." ] }]
extensions/javascript/OSSREADME.json
0
https://github.com/microsoft/vscode/commit/0349c7af1f44bf5d40f6dbaac02ae3b6bd07d98a
[ 0.00017965742154046893, 0.00017455437046010047, 0.00016800015873741359, 0.00017527994350530207, 0.000004282347163098166 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tthis._onDidChange.fire(event);\n", "\t}\n", "\n", "\tabstract setSelected(value: boolean): void;\n", "\tabstract executeCells(uri: URI, ranges: ICellRange[]): void;\n", "\tabstract cancelCells(uri: URI, ranges: ICellRange[]): void;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tabstract setSelected(uri: URI, value: boolean): void;\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 84 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter } from 'vs/base/common/event'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { ExtHostNotebookKernelsShape, IMainContext, INotebookKernelDto2, MainContext, MainThreadNotebookKernelsShape } from 'vs/workbench/api/common/extHost.protocol'; import * as vscode from 'vscode'; import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { URI, UriComponents } from 'vs/base/common/uri'; import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { NotebookCellRange } from 'vs/workbench/api/common/extHostTypeConverters'; import { isNonEmptyArray } from 'vs/base/common/arrays'; type ExecuteHandler = (executions: vscode.NotebookCellExecutionTask[]) => void; type InterruptHandler = (notebook: vscode.NotebookDocument) => void; export class ExtHostNotebookKernels implements ExtHostNotebookKernelsShape { private readonly _proxy: MainThreadNotebookKernelsShape; private readonly _kernelData = new Map<number, { id: string, executeHandler: ExecuteHandler, interruptHandler?: InterruptHandler, selected: boolean, onDidChangeSelection: Emitter<boolean> }>(); private _handlePool: number = 0; constructor( mainContext: IMainContext, private readonly _extHostNotebook: ExtHostNotebookController ) { this._proxy = mainContext.getProxy(MainContext.MainThreadNotebookKernels); } createKernel(extension: IExtensionDescription, options: vscode.NotebookKernelOptions): vscode.NotebookKernel2 { const handle = this._handlePool++; const that = this; let isDisposed = false; const commandDisposables = new DisposableStore(); const emitter = new Emitter<boolean>(); this._kernelData.set(handle, { id: options.id, executeHandler: options.executeHandler, selected: false, onDidChangeSelection: emitter }); const data: INotebookKernelDto2 = { id: options.id, selector: options.selector, extensionId: extension.identifier, extensionLocation: extension.extensionLocation, label: options.label, supportedLanguages: isNonEmptyArray(options.supportedLanguages) ? options.supportedLanguages : ['plaintext'], supportsInterrupt: Boolean(options.interruptHandler), hasExecutionOrder: options.hasExecutionOrder, }; this._proxy.$addKernel(handle, data); // update: all setters write directly into the dto object // and trigger an update. the actual update will only happen // once per event loop execution let tokenPool = 0; const _update = () => { if (isDisposed) { return; } const myToken = ++tokenPool; Promise.resolve().then(() => { if (myToken === tokenPool) { this._proxy.$updateKernel(handle, data); } }); }; return { get id() { return data.id; }, get selector() { return data.selector; }, // get selected() { return that._kernelData.get(handle)?.selected ?? false; }, // onDidChangeSelection: emitter.event, get label() { return data.label; }, set label(value) { data.label = value; _update(); }, get description() { return data.description ?? ''; }, set description(value) { data.description = value; _update(); }, get supportedLanguages() { return data.supportedLanguages; }, set supportedLanguages(value) { data.supportedLanguages = isNonEmptyArray(value) ? value : ['plaintext']; _update(); }, get hasExecutionOrder() { return data.hasExecutionOrder ?? false; }, set hasExecutionOrder(value) { data.hasExecutionOrder = value; _update(); }, get executeHandler() { return that._kernelData.get(handle)!.executeHandler; }, get interruptHandler() { return that._kernelData.get(handle)!.interruptHandler; }, set interruptHandler(value) { that._kernelData.get(handle)!.interruptHandler = value; data.supportsInterrupt = Boolean(value); _update(); }, createNotebookCellExecutionTask(cell) { //todo@jrieken return that._extHostNotebook.createNotebookCellExecution(cell.document.uri, cell.index, data.id)!; }, dispose: () => { isDisposed = true; this._kernelData.delete(handle); commandDisposables.dispose(); emitter.dispose(); this._proxy.$removeKernel(handle); } }; } $acceptSelection(handle: number, value: boolean): void { const obj = this._kernelData.get(handle); if (obj) { obj.selected = value; obj.onDidChangeSelection.fire(value); } } $executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void { const obj = this._kernelData.get(handle); if (!obj) { // extension can dispose kernels in the meantime return; } const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri)); if (!document) { throw new Error('MISSING notebook'); } const execs: vscode.NotebookCellExecutionTask[] = []; for (let range of ranges) { const cells = document.notebookDocument.getCells(NotebookCellRange.to(range)); for (let cell of cells) { const exec = this._extHostNotebook.createNotebookCellExecution(document.uri, cell.index, obj.id); if (exec) { execs.push(exec); } else { // todo@jrieken there should always be an exec-object console.warn('could NOT create notebook cell execution task for: ' + cell.document.uri); } } } try { obj.executeHandler(execs); } catch (err) { // console.error(err); } } $cancelCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void { const obj = this._kernelData.get(handle); if (!obj) { // extension can dispose kernels in the meantime return; } const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri)); if (!document) { throw new Error('MISSING notebook'); } if (obj.interruptHandler) { obj.interruptHandler(document.notebookDocument); } } }
src/vs/workbench/api/common/extHostNotebookKernels.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.9985211491584778, 0.10595670342445374, 0.00016613189654890448, 0.00017264942289330065, 0.3056980073451996 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tthis._onDidChange.fire(event);\n", "\t}\n", "\n", "\tabstract setSelected(value: boolean): void;\n", "\tabstract executeCells(uri: URI, ranges: ICellRange[]): void;\n", "\tabstract cancelCells(uri: URI, ranges: ICellRange[]): void;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tabstract setSelected(uri: URI, value: boolean): void;\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 84 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { SemanticTokenData, Range, TextDocument, LanguageModes, Position } from './languageModes'; import { beforeOrSame } from '../utils/positions'; interface LegendMapping { types: number[] | undefined; modifiers: number[] | undefined; } export interface SemanticTokenProvider { readonly legend: { types: string[]; modifiers: string[] }; getSemanticTokens(document: TextDocument, ranges?: Range[]): Promise<number[]>; } export function newSemanticTokenProvider(languageModes: LanguageModes): SemanticTokenProvider { // combined legend across modes const legend: { types: string[], modifiers: string[] } = { types: [], modifiers: [] }; const legendMappings: { [modeId: string]: LegendMapping } = {}; for (let mode of languageModes.getAllModes()) { if (mode.getSemanticTokenLegend && mode.getSemanticTokens) { const modeLegend = mode.getSemanticTokenLegend(); legendMappings[mode.getId()] = { types: createMapping(modeLegend.types, legend.types), modifiers: createMapping(modeLegend.modifiers, legend.modifiers) }; } } return { legend, async getSemanticTokens(document: TextDocument, ranges?: Range[]): Promise<number[]> { const allTokens: SemanticTokenData[] = []; for (let mode of languageModes.getAllModesInDocument(document)) { if (mode.getSemanticTokens) { const mapping = legendMappings[mode.getId()]; const tokens = await mode.getSemanticTokens(document); applyTypesMapping(tokens, mapping.types); applyModifiersMapping(tokens, mapping.modifiers); for (let token of tokens) { allTokens.push(token); } } } return encodeTokens(allTokens, ranges, document); } }; } function createMapping(origLegend: string[], newLegend: string[]): number[] | undefined { const mapping: number[] = []; let needsMapping = false; for (let origIndex = 0; origIndex < origLegend.length; origIndex++) { const entry = origLegend[origIndex]; let newIndex = newLegend.indexOf(entry); if (newIndex === -1) { newIndex = newLegend.length; newLegend.push(entry); } mapping.push(newIndex); needsMapping = needsMapping || (newIndex !== origIndex); } return needsMapping ? mapping : undefined; } function applyTypesMapping(tokens: SemanticTokenData[], typesMapping: number[] | undefined): void { if (typesMapping) { for (let token of tokens) { token.typeIdx = typesMapping[token.typeIdx]; } } } function applyModifiersMapping(tokens: SemanticTokenData[], modifiersMapping: number[] | undefined): void { if (modifiersMapping) { for (let token of tokens) { let modifierSet = token.modifierSet; if (modifierSet) { let index = 0; let result = 0; while (modifierSet > 0) { if ((modifierSet & 1) !== 0) { result = result + (1 << modifiersMapping[index]); } index++; modifierSet = modifierSet >> 1; } token.modifierSet = result; } } } } function encodeTokens(tokens: SemanticTokenData[], ranges: Range[] | undefined, document: TextDocument): number[] { const resultTokens = tokens.sort((d1, d2) => d1.start.line - d2.start.line || d1.start.character - d2.start.character); if (ranges) { ranges = ranges.sort((d1, d2) => d1.start.line - d2.start.line || d1.start.character - d2.start.character); } else { ranges = [Range.create(Position.create(0, 0), Position.create(document.lineCount, 0))]; } let rangeIndex = 0; let currRange = ranges[rangeIndex++]; let prefLine = 0; let prevChar = 0; let encodedResult: number[] = []; for (let k = 0; k < resultTokens.length && currRange; k++) { const curr = resultTokens[k]; const start = curr.start; while (currRange && beforeOrSame(currRange.end, start)) { currRange = ranges[rangeIndex++]; } if (currRange && beforeOrSame(currRange.start, start) && beforeOrSame({ line: start.line, character: start.character + curr.length }, currRange.end)) { // token inside a range if (prefLine !== start.line) { prevChar = 0; } encodedResult.push(start.line - prefLine); // line delta encodedResult.push(start.character - prevChar); // line delta encodedResult.push(curr.length); // length encodedResult.push(curr.typeIdx); // tokenType encodedResult.push(curr.modifierSet); // tokenModifier prefLine = start.line; prevChar = start.character; } } return encodedResult; }
extensions/html-language-features/server/src/modes/semanticTokens.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.0006061014719307423, 0.00021324687986634672, 0.00016423696069978178, 0.0001744942564982921, 0.00011396107584005222 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tthis._onDidChange.fire(event);\n", "\t}\n", "\n", "\tabstract setSelected(value: boolean): void;\n", "\tabstract executeCells(uri: URI, ranges: ICellRange[]): void;\n", "\tabstract cancelCells(uri: URI, ranges: ICellRange[]): void;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tabstract setSelected(uri: URI, value: boolean): void;\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 84 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ILineBreaksComputerFactory } from 'vs/editor/common/viewModel/splitLinesCollection'; import { WrappingIndent } from 'vs/editor/common/config/editorOptions'; import { FontInfo } from 'vs/editor/common/config/fontInfo'; import { createStringBuilder, IStringBuilder } from 'vs/editor/common/core/stringBuilder'; import { CharCode } from 'vs/base/common/charCode'; import * as strings from 'vs/base/common/strings'; import { Configuration } from 'vs/editor/browser/config/configuration'; import { ILineBreaksComputer, LineBreakData } from 'vs/editor/common/viewModel/viewModel'; const ttPolicy = window.trustedTypes?.createPolicy('domLineBreaksComputer', { createHTML: value => value }); export class DOMLineBreaksComputerFactory implements ILineBreaksComputerFactory { public static create(): DOMLineBreaksComputerFactory { return new DOMLineBreaksComputerFactory(); } constructor() { } public createLineBreaksComputer(fontInfo: FontInfo, tabSize: number, wrappingColumn: number, wrappingIndent: WrappingIndent): ILineBreaksComputer { tabSize = tabSize | 0; //@perf wrappingColumn = +wrappingColumn; //@perf let requests: string[] = []; return { addRequest: (lineText: string, previousLineBreakData: LineBreakData | null) => { requests.push(lineText); }, finalize: () => { return createLineBreaks(requests, fontInfo, tabSize, wrappingColumn, wrappingIndent); } }; } } function createLineBreaks(requests: string[], fontInfo: FontInfo, tabSize: number, firstLineBreakColumn: number, wrappingIndent: WrappingIndent): (LineBreakData | null)[] { if (firstLineBreakColumn === -1) { const result: null[] = []; for (let i = 0, len = requests.length; i < len; i++) { result[i] = null; } return result; } const overallWidth = Math.round(firstLineBreakColumn * fontInfo.typicalHalfwidthCharacterWidth); // Cannot respect WrappingIndent.Indent and WrappingIndent.DeepIndent because that would require // two dom layouts, in order to first set the width of the first line, and then set the width of the wrapped lines if (wrappingIndent === WrappingIndent.Indent || wrappingIndent === WrappingIndent.DeepIndent) { wrappingIndent = WrappingIndent.Same; } const containerDomNode = document.createElement('div'); Configuration.applyFontInfoSlow(containerDomNode, fontInfo); const sb = createStringBuilder(10000); const firstNonWhitespaceIndices: number[] = []; const wrappedTextIndentLengths: number[] = []; const renderLineContents: string[] = []; const allCharOffsets: number[][] = []; const allVisibleColumns: number[][] = []; for (let i = 0; i < requests.length; i++) { const lineContent = requests[i]; let firstNonWhitespaceIndex = 0; let wrappedTextIndentLength = 0; let width = overallWidth; if (wrappingIndent !== WrappingIndent.None) { firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent); if (firstNonWhitespaceIndex === -1) { // all whitespace line firstNonWhitespaceIndex = 0; } else { // Track existing indent for (let i = 0; i < firstNonWhitespaceIndex; i++) { const charWidth = ( lineContent.charCodeAt(i) === CharCode.Tab ? (tabSize - (wrappedTextIndentLength % tabSize)) : 1 ); wrappedTextIndentLength += charWidth; } const indentWidth = Math.ceil(fontInfo.spaceWidth * wrappedTextIndentLength); // Force sticking to beginning of line if no character would fit except for the indentation if (indentWidth + fontInfo.typicalFullwidthCharacterWidth > overallWidth) { firstNonWhitespaceIndex = 0; wrappedTextIndentLength = 0; } else { width = overallWidth - indentWidth; } } } const renderLineContent = lineContent.substr(firstNonWhitespaceIndex); const tmp = renderLine(renderLineContent, wrappedTextIndentLength, tabSize, width, sb); firstNonWhitespaceIndices[i] = firstNonWhitespaceIndex; wrappedTextIndentLengths[i] = wrappedTextIndentLength; renderLineContents[i] = renderLineContent; allCharOffsets[i] = tmp[0]; allVisibleColumns[i] = tmp[1]; } const html = sb.build(); const trustedhtml = ttPolicy?.createHTML(html) ?? html; containerDomNode.innerHTML = trustedhtml as string; containerDomNode.style.position = 'absolute'; containerDomNode.style.top = '10000'; containerDomNode.style.wordWrap = 'break-word'; document.body.appendChild(containerDomNode); let range = document.createRange(); const lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0); let result: (LineBreakData | null)[] = []; for (let i = 0; i < requests.length; i++) { const lineDomNode = lineDomNodes[i]; const breakOffsets: number[] | null = readLineBreaks(range, lineDomNode, renderLineContents[i], allCharOffsets[i]); if (breakOffsets === null) { result[i] = null; continue; } const firstNonWhitespaceIndex = firstNonWhitespaceIndices[i]; const wrappedTextIndentLength = wrappedTextIndentLengths[i]; const visibleColumns = allVisibleColumns[i]; const breakOffsetsVisibleColumn: number[] = []; for (let j = 0, len = breakOffsets.length; j < len; j++) { breakOffsetsVisibleColumn[j] = visibleColumns[breakOffsets[j]]; } if (firstNonWhitespaceIndex !== 0) { // All break offsets are relative to the renderLineContent, make them absolute again for (let j = 0, len = breakOffsets.length; j < len; j++) { breakOffsets[j] += firstNonWhitespaceIndex; } } result[i] = new LineBreakData(breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength); } document.body.removeChild(containerDomNode); return result; } const enum Constants { SPAN_MODULO_LIMIT = 16384 } function renderLine(lineContent: string, initialVisibleColumn: number, tabSize: number, width: number, sb: IStringBuilder): [number[], number[]] { sb.appendASCIIString('<div style="width:'); sb.appendASCIIString(String(width)); sb.appendASCIIString('px;">'); // if (containsRTL) { // sb.appendASCIIString('" dir="ltr'); // } const len = lineContent.length; let visibleColumn = initialVisibleColumn; let charOffset = 0; let charOffsets: number[] = []; let visibleColumns: number[] = []; let nextCharCode = (0 < len ? lineContent.charCodeAt(0) : CharCode.Null); sb.appendASCIIString('<span>'); for (let charIndex = 0; charIndex < len; charIndex++) { if (charIndex !== 0 && charIndex % Constants.SPAN_MODULO_LIMIT === 0) { sb.appendASCIIString('</span><span>'); } charOffsets[charIndex] = charOffset; visibleColumns[charIndex] = visibleColumn; const charCode = nextCharCode; nextCharCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : CharCode.Null); let producedCharacters = 1; let charWidth = 1; switch (charCode) { case CharCode.Tab: producedCharacters = (tabSize - (visibleColumn % tabSize)); charWidth = producedCharacters; for (let space = 1; space <= producedCharacters; space++) { if (space < producedCharacters) { sb.write1(0xA0); // &nbsp; } else { sb.appendASCII(CharCode.Space); } } break; case CharCode.Space: if (nextCharCode === CharCode.Space) { sb.write1(0xA0); // &nbsp; } else { sb.appendASCII(CharCode.Space); } break; case CharCode.LessThan: sb.appendASCIIString('&lt;'); break; case CharCode.GreaterThan: sb.appendASCIIString('&gt;'); break; case CharCode.Ampersand: sb.appendASCIIString('&amp;'); break; case CharCode.Null: sb.appendASCIIString('&#00;'); break; case CharCode.UTF8_BOM: case CharCode.LINE_SEPARATOR: case CharCode.PARAGRAPH_SEPARATOR: case CharCode.NEXT_LINE: sb.write1(0xFFFD); break; default: if (strings.isFullWidthCharacter(charCode)) { charWidth++; } if (charCode < 32) { sb.write1(9216 + charCode); } else { sb.write1(charCode); } } charOffset += producedCharacters; visibleColumn += charWidth; } sb.appendASCIIString('</span>'); charOffsets[lineContent.length] = charOffset; visibleColumns[lineContent.length] = visibleColumn; sb.appendASCIIString('</div>'); return [charOffsets, visibleColumns]; } function readLineBreaks(range: Range, lineDomNode: HTMLDivElement, lineContent: string, charOffsets: number[]): number[] | null { if (lineContent.length <= 1) { return null; } const spans = <HTMLSpanElement[]>Array.prototype.slice.call(lineDomNode.children, 0); const breakOffsets: number[] = []; try { discoverBreaks(range, spans, charOffsets, 0, null, lineContent.length - 1, null, breakOffsets); } catch (err) { console.log(err); return null; } if (breakOffsets.length === 0) { return null; } breakOffsets.push(lineContent.length); return breakOffsets; } type MaybeRects = ClientRectList | DOMRectList | null; function discoverBreaks(range: Range, spans: HTMLSpanElement[], charOffsets: number[], low: number, lowRects: MaybeRects, high: number, highRects: MaybeRects, result: number[]): void { if (low === high) { return; } lowRects = lowRects || readClientRect(range, spans, charOffsets[low], charOffsets[low + 1]); highRects = highRects || readClientRect(range, spans, charOffsets[high], charOffsets[high + 1]); if (Math.abs(lowRects[0].top - highRects[0].top) <= 0.1) { // same line return; } // there is at least one line break between these two offsets if (low + 1 === high) { // the two characters are adjacent, so the line break must be exactly between them result.push(high); return; } const mid = low + ((high - low) / 2) | 0; const midRects = readClientRect(range, spans, charOffsets[mid], charOffsets[mid + 1]); discoverBreaks(range, spans, charOffsets, low, lowRects, mid, midRects, result); discoverBreaks(range, spans, charOffsets, mid, midRects, high, highRects, result); } function readClientRect(range: Range, spans: HTMLSpanElement[], startOffset: number, endOffset: number): ClientRectList | DOMRectList { range.setStart(spans[(startOffset / Constants.SPAN_MODULO_LIMIT) | 0].firstChild!, startOffset % Constants.SPAN_MODULO_LIMIT); range.setEnd(spans[(endOffset / Constants.SPAN_MODULO_LIMIT) | 0].firstChild!, endOffset % Constants.SPAN_MODULO_LIMIT); return range.getClientRects(); }
src/vs/editor/browser/view/domLineBreaksComputer.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017690363165456802, 0.00017193735402543098, 0.00016770820366218686, 0.00017214196850545704, 0.0000023853042421251303 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tthis._onDidChange.fire(event);\n", "\t}\n", "\n", "\tabstract setSelected(value: boolean): void;\n", "\tabstract executeCells(uri: URI, ranges: ICellRange[]): void;\n", "\tabstract cancelCells(uri: URI, ranges: ICellRange[]): void;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tabstract setSelected(uri: URI, value: boolean): void;\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 84 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./iconlabel'; import * as dom from 'vs/base/browser/dom'; import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel'; import { IMatch } from 'vs/base/common/filters'; import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; import { Range } from 'vs/base/common/range'; import { equals } from 'vs/base/common/objects'; import { IHoverDelegate, IHoverDelegateOptions, IHoverDelegateTarget } from 'vs/base/browser/ui/iconLabel/iconHoverDelegate'; import { AnchorPosition } from 'vs/base/browser/ui/contextview/contextview'; import { IMarkdownString } from 'vs/base/common/htmlContent'; import { isFunction, isString } from 'vs/base/common/types'; import { domEvent } from 'vs/base/browser/event'; import { localize } from 'vs/nls'; import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation'; export interface IIconLabelCreationOptions { supportHighlights?: boolean; supportDescriptionHighlights?: boolean; supportIcons?: boolean; hoverDelegate?: IHoverDelegate; } export interface IIconLabelMarkdownString { markdown: IMarkdownString | string | undefined | ((token: CancellationToken) => Promise<IMarkdownString | string | undefined>); markdownNotSupportedFallback: string | undefined; } export interface IIconLabelValueOptions { title?: string | IIconLabelMarkdownString; descriptionTitle?: string; hideIcon?: boolean; extraClasses?: string[]; italic?: boolean; strikethrough?: boolean; matches?: IMatch[]; labelEscapeNewLines?: boolean; descriptionMatches?: IMatch[]; readonly separator?: string; readonly domId?: string; } class FastLabelNode { private disposed: boolean | undefined; private _textContent: string | undefined; private _className: string | undefined; private _empty: boolean | undefined; constructor(private _element: HTMLElement) { } get element(): HTMLElement { return this._element; } set textContent(content: string) { if (this.disposed || content === this._textContent) { return; } this._textContent = content; this._element.textContent = content; } set className(className: string) { if (this.disposed || className === this._className) { return; } this._className = className; this._element.className = className; } set empty(empty: boolean) { if (this.disposed || empty === this._empty) { return; } this._empty = empty; this._element.style.marginLeft = empty ? '0' : ''; } dispose(): void { this.disposed = true; } } export class IconLabel extends Disposable { private domNode: FastLabelNode; private nameNode: Label | LabelWithHighlights; private descriptionContainer: FastLabelNode; private descriptionNode: FastLabelNode | HighlightedLabel | undefined; private descriptionNodeFactory: () => FastLabelNode | HighlightedLabel; private labelContainer: HTMLElement; private hoverDelegate: IHoverDelegate | undefined = undefined; private readonly customHovers: Map<HTMLElement, IDisposable> = new Map(); constructor(container: HTMLElement, options?: IIconLabelCreationOptions) { super(); this.domNode = this._register(new FastLabelNode(dom.append(container, dom.$('.monaco-icon-label')))); this.labelContainer = dom.append(this.domNode.element, dom.$('.monaco-icon-label-container')); const nameContainer = dom.append(this.labelContainer, dom.$('span.monaco-icon-name-container')); this.descriptionContainer = this._register(new FastLabelNode(dom.append(this.labelContainer, dom.$('span.monaco-icon-description-container')))); if (options?.supportHighlights) { this.nameNode = new LabelWithHighlights(nameContainer, !!options.supportIcons); } else { this.nameNode = new Label(nameContainer); } if (options?.supportDescriptionHighlights) { this.descriptionNodeFactory = () => new HighlightedLabel(dom.append(this.descriptionContainer.element, dom.$('span.label-description')), !!options.supportIcons); } else { this.descriptionNodeFactory = () => this._register(new FastLabelNode(dom.append(this.descriptionContainer.element, dom.$('span.label-description')))); } if (options?.hoverDelegate) { this.hoverDelegate = options.hoverDelegate; } } get element(): HTMLElement { return this.domNode.element; } setLabel(label: string | string[], description?: string, options?: IIconLabelValueOptions): void { const classes = ['monaco-icon-label']; if (options) { if (options.extraClasses) { classes.push(...options.extraClasses); } if (options.italic) { classes.push('italic'); } if (options.strikethrough) { classes.push('strikethrough'); } } this.domNode.className = classes.join(' '); this.setupHover(this.labelContainer, options?.title); this.nameNode.setLabel(label, options); if (description || this.descriptionNode) { if (!this.descriptionNode) { this.descriptionNode = this.descriptionNodeFactory(); // description node is created lazily on demand } if (this.descriptionNode instanceof HighlightedLabel) { this.descriptionNode.set(description || '', options ? options.descriptionMatches : undefined); this.setupHover(this.descriptionNode.element, options?.descriptionTitle); } else { this.descriptionNode.textContent = description || ''; this.setupHover(this.descriptionNode.element, options?.descriptionTitle || ''); this.descriptionNode.empty = !description; } } } private setupHover(htmlElement: HTMLElement, tooltip: string | IIconLabelMarkdownString | undefined): void { const previousCustomHover = this.customHovers.get(htmlElement); if (previousCustomHover) { previousCustomHover.dispose(); this.customHovers.delete(htmlElement); } if (!tooltip) { htmlElement.removeAttribute('title'); return; } if (!this.hoverDelegate) { return this.setupNativeHover(htmlElement, tooltip); } else { return this.setupCustomHover(this.hoverDelegate, htmlElement, tooltip); } } private static adjustXAndShowCustomHover(hoverOptions: IHoverDelegateOptions | undefined, mouseX: number | undefined, hoverDelegate: IHoverDelegate, isHovering: boolean): IDisposable | undefined { if (hoverOptions && isHovering) { if (mouseX !== undefined) { (<IHoverDelegateTarget>hoverOptions.target).x = mouseX + 10; } return hoverDelegate.showHover(hoverOptions); } return undefined; } private getTooltipForCustom(markdownTooltip: string | IIconLabelMarkdownString): (token: CancellationToken) => Promise<string | IMarkdownString | undefined> { if (isString(markdownTooltip)) { return async () => markdownTooltip; } else if (isFunction(markdownTooltip.markdown)) { return markdownTooltip.markdown; } else { const markdown = markdownTooltip.markdown; return async () => markdown; } } private setupCustomHover(hoverDelegate: IHoverDelegate, htmlElement: HTMLElement, markdownTooltip: string | IIconLabelMarkdownString): void { htmlElement.setAttribute('title', ''); htmlElement.removeAttribute('title'); let tooltip = this.getTooltipForCustom(markdownTooltip); let hoverOptions: IHoverDelegateOptions | undefined; let mouseX: number | undefined; let isHovering = false; let tokenSource: CancellationTokenSource; let hoverDisposable: IDisposable | undefined; function mouseOver(this: HTMLElement, e: MouseEvent): void { if (isHovering) { return; } tokenSource = new CancellationTokenSource(); function mouseLeaveOrDown(this: HTMLElement, e: MouseEvent): void { const isMouseDown = e.type === dom.EventType.MOUSE_DOWN; if (isMouseDown) { hoverDisposable?.dispose(); hoverDisposable = undefined; } if (isMouseDown || (<any>e).fromElement === htmlElement) { isHovering = false; hoverOptions = undefined; tokenSource.dispose(true); mouseLeaveDisposable.dispose(); mouseDownDisposable.dispose(); } } const mouseLeaveDisposable = domEvent(htmlElement, dom.EventType.MOUSE_LEAVE, true)(mouseLeaveOrDown.bind(htmlElement)); const mouseDownDisposable = domEvent(htmlElement, dom.EventType.MOUSE_DOWN, true)(mouseLeaveOrDown.bind(htmlElement)); isHovering = true; function mouseMove(this: HTMLElement, e: MouseEvent): void { mouseX = e.x; } const mouseMoveDisposable = domEvent(htmlElement, dom.EventType.MOUSE_MOVE, true)(mouseMove.bind(htmlElement)); setTimeout(async () => { if (isHovering && tooltip) { // Re-use the already computed hover options if they exist. if (!hoverOptions) { const target: IHoverDelegateTarget = { targetElements: [this], dispose: () => { } }; hoverOptions = { text: localize('iconLabel.loading', "Loading..."), target, anchorPosition: AnchorPosition.BELOW }; hoverDisposable = IconLabel.adjustXAndShowCustomHover(hoverOptions, mouseX, hoverDelegate, isHovering); const resolvedTooltip = (await tooltip(tokenSource.token)) ?? (!isString(markdownTooltip) ? markdownTooltip.markdownNotSupportedFallback : undefined); if (resolvedTooltip) { hoverOptions = { text: resolvedTooltip, target, anchorPosition: AnchorPosition.BELOW }; // awaiting the tooltip could take a while. Make sure we're still hovering. hoverDisposable = IconLabel.adjustXAndShowCustomHover(hoverOptions, mouseX, hoverDelegate, isHovering); } else if (hoverDisposable) { hoverDisposable.dispose(); hoverDisposable = undefined; } } } mouseMoveDisposable.dispose(); }, hoverDelegate.delay); } const mouseOverDisposable = this._register(domEvent(htmlElement, dom.EventType.MOUSE_OVER, true)(mouseOver.bind(htmlElement))); this.customHovers.set(htmlElement, mouseOverDisposable); } private setupNativeHover(htmlElement: HTMLElement, tooltip: string | IIconLabelMarkdownString | undefined): void { let stringTooltip: string = ''; if (isString(tooltip)) { stringTooltip = tooltip; } else if (tooltip?.markdownNotSupportedFallback) { stringTooltip = tooltip.markdownNotSupportedFallback; } htmlElement.title = stringTooltip; } } class Label { private label: string | string[] | undefined = undefined; private singleLabel: HTMLElement | undefined = undefined; private options: IIconLabelValueOptions | undefined; constructor(private container: HTMLElement) { } setLabel(label: string | string[], options?: IIconLabelValueOptions): void { if (this.label === label && equals(this.options, options)) { return; } this.label = label; this.options = options; if (typeof label === 'string') { if (!this.singleLabel) { this.container.innerText = ''; this.container.classList.remove('multiple'); this.singleLabel = dom.append(this.container, dom.$('a.label-name', { id: options?.domId })); } this.singleLabel.textContent = label; } else { this.container.innerText = ''; this.container.classList.add('multiple'); this.singleLabel = undefined; for (let i = 0; i < label.length; i++) { const l = label[i]; const id = options?.domId && `${options?.domId}_${i}`; dom.append(this.container, dom.$('a.label-name', { id, 'data-icon-label-count': label.length, 'data-icon-label-index': i, 'role': 'treeitem' }, l)); if (i < label.length - 1) { dom.append(this.container, dom.$('span.label-separator', undefined, options?.separator || '/')); } } } } } function splitMatches(labels: string[], separator: string, matches: IMatch[] | undefined): IMatch[][] | undefined { if (!matches) { return undefined; } let labelStart = 0; return labels.map(label => { const labelRange = { start: labelStart, end: labelStart + label.length }; const result = matches .map(match => Range.intersect(labelRange, match)) .filter(range => !Range.isEmpty(range)) .map(({ start, end }) => ({ start: start - labelStart, end: end - labelStart })); labelStart = labelRange.end + separator.length; return result; }); } class LabelWithHighlights { private label: string | string[] | undefined = undefined; private singleLabel: HighlightedLabel | undefined = undefined; private options: IIconLabelValueOptions | undefined; constructor(private container: HTMLElement, private supportIcons: boolean) { } setLabel(label: string | string[], options?: IIconLabelValueOptions): void { if (this.label === label && equals(this.options, options)) { return; } this.label = label; this.options = options; if (typeof label === 'string') { if (!this.singleLabel) { this.container.innerText = ''; this.container.classList.remove('multiple'); this.singleLabel = new HighlightedLabel(dom.append(this.container, dom.$('a.label-name', { id: options?.domId })), this.supportIcons); } this.singleLabel.set(label, options?.matches, undefined, options?.labelEscapeNewLines); } else { this.container.innerText = ''; this.container.classList.add('multiple'); this.singleLabel = undefined; const separator = options?.separator || '/'; const matches = splitMatches(label, separator, options?.matches); for (let i = 0; i < label.length; i++) { const l = label[i]; const m = matches ? matches[i] : undefined; const id = options?.domId && `${options?.domId}_${i}`; const name = dom.$('a.label-name', { id, 'data-icon-label-count': label.length, 'data-icon-label-index': i, 'role': 'treeitem' }); const highlightedLabel = new HighlightedLabel(dom.append(this.container, name), this.supportIcons); highlightedLabel.set(l, m, undefined, options?.labelEscapeNewLines); if (i < label.length - 1) { dom.append(name, dom.$('span.label-separator', undefined, separator)); } } } } }
src/vs/base/browser/ui/iconLabel/iconLabel.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00022899566101841629, 0.00017314798606093973, 0.00016247315215878189, 0.0001722154556773603, 0.000009421226423000917 ]
{ "id": 1, "code_window": [ "\t$addKernel(handle: number, data: INotebookKernelDto2): void {\n", "\t\tconst that = this;\n", "\t\tconst kernel = new class extends MainThreadKernel {\n", "\t\t\tsetSelected(value: boolean): void {\n", "\t\t\t\tthat._proxy.$acceptSelection(handle, value);\n", "\t\t\t}\n", "\t\t\texecuteCells(uri: URI, ranges: ICellRange[]): void {\n", "\t\t\t\tthat._proxy.$executeCells(handle, uri, ranges);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tsetSelected(uri: URI, value: boolean): void {\n", "\t\t\t\tthat._proxy.$acceptSelection(handle, uri, value);\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 111 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ICellRange, INotebookTextModel } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { NotebookSelector } from 'vs/workbench/contrib/notebook/common/notebookSelector'; export interface INotebookKernel2ChangeEvent { label?: true; description?: true; detail?: true; isPreferred?: true; supportedLanguages?: true; hasExecutionOrder?: true; } export interface INotebookKernel2 { readonly id: string; readonly selector: NotebookSelector readonly extensionId: ExtensionIdentifier; readonly onDidChange: Event<INotebookKernel2ChangeEvent>; label: string; description?: string; detail?: string; isPreferred?: boolean; supportedLanguages: string[]; implementsExecutionOrder: boolean; implementsInterrupt: boolean; localResourceRoot: URI; preloadUris: URI[]; preloadProvides: string[]; setSelected(value: boolean): void; executeCells(uri: URI, ranges: ICellRange[]): void; cancelCells(uri: URI, ranges: ICellRange[]): void } export const INotebookKernelService = createDecorator<INotebookKernelService>('INotebookKernelService'); export interface INotebookKernelService { _serviceBrand: undefined; onDidAddKernel: Event<INotebookKernel2>; onDidRemoveKernel: Event<INotebookKernel2>; addKernel(kernel: INotebookKernel2): IDisposable; selectKernels(notebook: INotebookTextModel): INotebookKernel2[]; }
src/vs/workbench/contrib/notebook/common/notebookKernelService.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.008207188919186592, 0.0033979665022343397, 0.00016978461644612253, 0.003420919179916382, 0.0028663603588938713 ]
{ "id": 1, "code_window": [ "\t$addKernel(handle: number, data: INotebookKernelDto2): void {\n", "\t\tconst that = this;\n", "\t\tconst kernel = new class extends MainThreadKernel {\n", "\t\t\tsetSelected(value: boolean): void {\n", "\t\t\t\tthat._proxy.$acceptSelection(handle, value);\n", "\t\t\t}\n", "\t\t\texecuteCells(uri: URI, ranges: ICellRange[]): void {\n", "\t\t\t\tthat._proxy.$executeCells(handle, uri, ranges);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tsetSelected(uri: URI, value: boolean): void {\n", "\t\t\t\tthat._proxy.$acceptSelection(handle, uri, value);\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 111 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CharCode } from 'vs/base/common/charCode'; export const enum TokenType { Dollar, Colon, Comma, CurlyOpen, CurlyClose, Backslash, Forwardslash, Pipe, Int, VariableName, Format, Plus, Dash, QuestionMark, EOF } export interface Token { type: TokenType; pos: number; len: number; } export class Scanner { private static _table: { [ch: number]: TokenType } = { [CharCode.DollarSign]: TokenType.Dollar, [CharCode.Colon]: TokenType.Colon, [CharCode.Comma]: TokenType.Comma, [CharCode.OpenCurlyBrace]: TokenType.CurlyOpen, [CharCode.CloseCurlyBrace]: TokenType.CurlyClose, [CharCode.Backslash]: TokenType.Backslash, [CharCode.Slash]: TokenType.Forwardslash, [CharCode.Pipe]: TokenType.Pipe, [CharCode.Plus]: TokenType.Plus, [CharCode.Dash]: TokenType.Dash, [CharCode.QuestionMark]: TokenType.QuestionMark, }; static isDigitCharacter(ch: number): boolean { return ch >= CharCode.Digit0 && ch <= CharCode.Digit9; } static isVariableCharacter(ch: number): boolean { return ch === CharCode.Underline || (ch >= CharCode.a && ch <= CharCode.z) || (ch >= CharCode.A && ch <= CharCode.Z); } value: string = ''; pos: number = 0; text(value: string) { this.value = value; this.pos = 0; } tokenText(token: Token): string { return this.value.substr(token.pos, token.len); } next(): Token { if (this.pos >= this.value.length) { return { type: TokenType.EOF, pos: this.pos, len: 0 }; } let pos = this.pos; let len = 0; let ch = this.value.charCodeAt(pos); let type: TokenType; // static types type = Scanner._table[ch]; if (typeof type === 'number') { this.pos += 1; return { type, 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, pos, 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, pos, 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, pos, len }; } } export abstract class Marker { readonly _markerBrand: any; public parent!: Marker; protected _children: Marker[] = []; appendChild(child: Marker): this { if (child instanceof Text && this._children[this._children.length - 1] instanceof Text) { // this and previous child are text -> merge them (<Text>this._children[this._children.length - 1]).value += child.value; } else { // normal adoption of child child.parent = this; this._children.push(child); } return this; } replace(child: Marker, others: Marker[]): void { const { parent } = child; const idx = parent.children.indexOf(child); const newChildren = parent.children.slice(0); newChildren.splice(idx, 1, ...others); parent._children = newChildren; (function _fixParent(children: Marker[], parent: Marker) { for (const child of children) { child.parent = parent; _fixParent(child.children, child); } })(others, parent); } get children(): Marker[] { return this._children; } get snippet(): TextmateSnippet | undefined { let candidate: Marker = this; while (true) { if (!candidate) { return undefined; } if (candidate instanceof TextmateSnippet) { return candidate; } candidate = candidate.parent; } } toString(): string { return this.children.reduce((prev, cur) => prev + cur.toString(), ''); } abstract toTextmateString(): string; len(): number { return 0; } abstract clone(): Marker; } export class Text extends Marker { static escape(value: string): string { return value.replace(/\$|}|\\/g, '\\$&'); } constructor(public value: string) { super(); } override toString() { return this.value; } toTextmateString(): string { return Text.escape(this.value); } override len(): number { return this.value.length; } clone(): Text { return new Text(this.value); } } export abstract class TransformableMarker extends Marker { public transform?: Transform; } export class Placeholder extends TransformableMarker { static compareByIndex(a: Placeholder, b: Placeholder): number { 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; } } constructor(public index: number) { super(); } get isFinalTabstop() { return this.index === 0; } get choice(): Choice | undefined { return this._children.length === 1 && this._children[0] instanceof Choice ? this._children[0] as Choice : undefined; } toTextmateString(): string { let transformString = ''; if (this.transform) { transformString = this.transform.toTextmateString(); } if (this.children.length === 0 && !this.transform) { return `\$${this.index}`; } else if (this.children.length === 0) { return `\${${this.index}${transformString}}`; } else if (this.choice) { return `\${${this.index}|${this.choice.toTextmateString()}|${transformString}}`; } else { return `\${${this.index}:${this.children.map(child => child.toTextmateString()).join('')}${transformString}}`; } } clone(): Placeholder { let ret = new Placeholder(this.index); if (this.transform) { ret.transform = this.transform.clone(); } ret._children = this.children.map(child => child.clone()); return ret; } } export class Choice extends Marker { readonly options: Text[] = []; override appendChild(marker: Marker): this { if (marker instanceof Text) { marker.parent = this; this.options.push(marker); } return this; } override toString() { return this.options[0].value; } toTextmateString(): string { return this.options .map(option => option.value.replace(/\||,/g, '\\$&')) .join(','); } override len(): number { return this.options[0].len(); } clone(): Choice { let ret = new Choice(); this.options.forEach(ret.appendChild, ret); return ret; } } export class Transform extends Marker { regexp: RegExp = new RegExp(''); resolve(value: string): string { const _this = this; let didMatch = false; let ret = value.replace(this.regexp, function () { didMatch = true; return _this._replace(Array.prototype.slice.call(arguments, 0, -2)); }); // when the regex didn't match and when the transform has // else branches, then run those if (!didMatch && this._children.some(child => child instanceof FormatString && Boolean(child.elseValue))) { ret = this._replace([]); } return ret; } private _replace(groups: string[]): string { let ret = ''; for (const marker of this._children) { if (marker instanceof FormatString) { let value = groups[marker.index] || ''; value = marker.resolve(value); ret += value; } else { ret += marker.toString(); } } return ret; } override toString(): string { return ''; } toTextmateString(): string { return `/${this.regexp.source}/${this.children.map(c => c.toTextmateString())}/${(this.regexp.ignoreCase ? 'i' : '') + (this.regexp.global ? 'g' : '')}`; } clone(): Transform { let ret = new Transform(); ret.regexp = new RegExp(this.regexp.source, '' + (this.regexp.ignoreCase ? 'i' : '') + (this.regexp.global ? 'g' : '')); ret._children = this.children.map(child => child.clone()); return ret; } } export class FormatString extends Marker { constructor( readonly index: number, readonly shorthandName?: string, readonly ifValue?: string, readonly elseValue?: string, ) { super(); } resolve(value?: string): string { if (this.shorthandName === 'upcase') { return !value ? '' : value.toLocaleUpperCase(); } else if (this.shorthandName === 'downcase') { return !value ? '' : value.toLocaleLowerCase(); } else if (this.shorthandName === 'capitalize') { return !value ? '' : (value[0].toLocaleUpperCase() + value.substr(1)); } else if (this.shorthandName === 'pascalcase') { return !value ? '' : this._toPascalCase(value); } else if (Boolean(value) && typeof this.ifValue === 'string') { return this.ifValue; } else if (!Boolean(value) && typeof this.elseValue === 'string') { return this.elseValue; } else { return value || ''; } } private _toPascalCase(value: string): string { const match = value.match(/[a-z]+/gi); if (!match) { return value; } return match.map(function (word) { return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase(); }) .join(''); } toTextmateString(): string { let value = '${'; value += this.index; if (this.shorthandName) { value += `:/${this.shorthandName}`; } else if (this.ifValue && this.elseValue) { value += `:?${this.ifValue}:${this.elseValue}`; } else if (this.ifValue) { value += `:+${this.ifValue}`; } else if (this.elseValue) { value += `:-${this.elseValue}`; } value += '}'; return value; } clone(): FormatString { let ret = new FormatString(this.index, this.shorthandName, this.ifValue, this.elseValue); return ret; } } export class Variable extends TransformableMarker { constructor(public name: string) { super(); } resolve(resolver: VariableResolver): boolean { let value = resolver.resolve(this); if (this.transform) { value = this.transform.resolve(value || ''); } if (value !== undefined) { this._children = [new Text(value)]; return true; } return false; } toTextmateString(): string { let transformString = ''; if (this.transform) { transformString = this.transform.toTextmateString(); } if (this.children.length === 0) { return `\${${this.name}${transformString}}`; } else { return `\${${this.name}:${this.children.map(child => child.toTextmateString()).join('')}${transformString}}`; } } clone(): Variable { const ret = new Variable(this.name); if (this.transform) { ret.transform = this.transform.clone(); } ret._children = this.children.map(child => child.clone()); return ret; } } export interface VariableResolver { resolve(variable: Variable): string | undefined; } function walk(marker: Marker[], visitor: (marker: Marker) => boolean): void { const stack = [...marker]; while (stack.length > 0) { const marker = stack.shift()!; const recurse = visitor(marker); if (!recurse) { break; } stack.unshift(...marker.children); } } export class TextmateSnippet extends Marker { private _placeholders?: { all: Placeholder[], last?: Placeholder }; get placeholderInfo() { if (!this._placeholders) { // fill in placeholders let all: Placeholder[] = []; let last: Placeholder | undefined; this.walk(function (candidate) { if (candidate instanceof Placeholder) { all.push(candidate); last = !last || last.index < candidate.index ? candidate : last; } return true; }); this._placeholders = { all, last }; } return this._placeholders; } get placeholders(): Placeholder[] { const { all } = this.placeholderInfo; return all; } offset(marker: Marker): number { let pos = 0; let found = false; this.walk(candidate => { if (candidate === marker) { found = true; return false; } pos += candidate.len(); return true; }); if (!found) { return -1; } return pos; } fullLen(marker: Marker): number { let ret = 0; walk([marker], marker => { ret += marker.len(); return true; }); return ret; } enclosingPlaceholders(placeholder: Placeholder): Placeholder[] { let ret: Placeholder[] = []; let { parent } = placeholder; while (parent) { if (parent instanceof Placeholder) { ret.push(parent); } parent = parent.parent; } return ret; } resolveVariables(resolver: VariableResolver): this { this.walk(candidate => { if (candidate instanceof Variable) { if (candidate.resolve(resolver)) { this._placeholders = undefined; } } return true; }); return this; } override appendChild(child: Marker) { this._placeholders = undefined; return super.appendChild(child); } override replace(child: Marker, others: Marker[]): void { this._placeholders = undefined; return super.replace(child, others); } toTextmateString(): string { return this.children.reduce((prev, cur) => prev + cur.toTextmateString(), ''); } clone(): TextmateSnippet { let ret = new TextmateSnippet(); this._children = this.children.map(child => child.clone()); return ret; } walk(visitor: (marker: Marker) => boolean): void { walk(this.children, visitor); } } export class SnippetParser { static escape(value: string): string { return value.replace(/\$|}|\\/g, '\\$&'); } static guessNeedsClipboard(template: string): boolean { return /\${?CLIPBOARD/.test(template); } private _scanner: Scanner = new Scanner(); private _token: Token = { type: TokenType.EOF, pos: 0, len: 0 }; text(value: string): string { return this.parse(value).toString(); } parse(value: string, insertFinalTabstop?: boolean, enforceFinalTabstop?: boolean): TextmateSnippet { this._scanner.text(value); this._token = this._scanner.next(); const snippet = new TextmateSnippet(); while (this._parse(snippet)) { // nothing } // fill in values for placeholders. the first placeholder of an index // that has a value defines the value for all placeholders with that index const placeholderDefaultValues = new Map<number, Marker[] | undefined>(); const incompletePlaceholders: Placeholder[] = []; let placeholderCount = 0; snippet.walk(marker => { if (marker instanceof Placeholder) { placeholderCount += 1; if (marker.isFinalTabstop) { placeholderDefaultValues.set(0, undefined); } else if (!placeholderDefaultValues.has(marker.index) && marker.children.length > 0) { placeholderDefaultValues.set(marker.index, marker.children); } else { incompletePlaceholders.push(marker); } } return true; }); for (const placeholder of incompletePlaceholders) { const defaultValues = placeholderDefaultValues.get(placeholder.index); if (defaultValues) { const clone = new Placeholder(placeholder.index); clone.transform = placeholder.transform; for (const child of defaultValues) { clone.appendChild(child.clone()); } snippet.replace(placeholder, [clone]); } } if (!enforceFinalTabstop) { enforceFinalTabstop = placeholderCount > 0 && insertFinalTabstop; } if (!placeholderDefaultValues.has(0) && enforceFinalTabstop) { // the snippet uses placeholders but has no // final tabstop defined -> insert at the end snippet.appendChild(new Placeholder(0)); } return snippet; } private _accept(type?: TokenType): boolean; private _accept(type: TokenType | undefined, value: true): string; private _accept(type: TokenType, value?: boolean): boolean | string { if (type === undefined || this._token.type === type) { let ret = !value ? true : this._scanner.tokenText(this._token); this._token = this._scanner.next(); return ret; } return false; } private _backTo(token: Token): false { this._scanner.pos = token.pos + token.len; this._token = token; return false; } private _until(type: TokenType): false | string { const start = this._token; while (this._token.type !== type) { if (this._token.type === TokenType.EOF) { return false; } else if (this._token.type === TokenType.Backslash) { const nextToken = this._scanner.next(); if (nextToken.type !== TokenType.Dollar && nextToken.type !== TokenType.CurlyClose && nextToken.type !== TokenType.Backslash) { return false; } } this._token = this._scanner.next(); } const value = this._scanner.value.substring(start.pos, this._token.pos).replace(/\\(\$|}|\\)/g, '$1'); this._token = this._scanner.next(); return value; } private _parse(marker: Marker): boolean { return this._parseEscaped(marker) || this._parseTabstopOrVariableName(marker) || this._parseComplexPlaceholder(marker) || this._parseComplexVariable(marker) || this._parseAnything(marker); } // \$, \\, \} -> just text private _parseEscaped(marker: Marker): boolean { let value: string; 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 private _parseTabstopOrVariableName(parent: Marker): boolean { let value: string; const token = this._token; const 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 private _parseComplexPlaceholder(parent: Marker): boolean { let index: string; const token = this._token; const match = this._accept(TokenType.Dollar) && this._accept(TokenType.CurlyOpen) && (index = this._accept(TokenType.Int, true)); if (!match) { return this._backTo(token); } const 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 (placeholder.index > 0 && this._accept(TokenType.Pipe)) { // ${1|one,two,three|} const choice = new Choice(); while (true) { if (this._parseChoiceElement(choice)) { if (this._accept(TokenType.Comma)) { // opt, -> more continue; } if (this._accept(TokenType.Pipe)) { placeholder.appendChild(choice); if (this._accept(TokenType.CurlyClose)) { // ..|} -> done parent.appendChild(placeholder); return true; } } } this._backTo(token); return false; } } else if (this._accept(TokenType.Forwardslash)) { // ${1/<regex>/<format>/<options>} if (this._parseTransform(placeholder)) { 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); } } private _parseChoiceElement(parent: Choice): boolean { const token = this._token; const values: string[] = []; while (true) { if (this._token.type === TokenType.Comma || this._token.type === TokenType.Pipe) { break; } let value: string; if (value = this._accept(TokenType.Backslash, true)) { // \, \|, or \\ value = this._accept(TokenType.Comma, true) || this._accept(TokenType.Pipe, true) || this._accept(TokenType.Backslash, true) || value; } else { value = this._accept(undefined, true); } if (!value) { // EOF this._backTo(token); return false; } values.push(value); } if (values.length === 0) { this._backTo(token); return false; } parent.appendChild(new Text(values.join(''))); return true; } // ${foo:<children>}, ${foo} -> variable private _parseComplexVariable(parent: Marker): boolean { let name: string; const token = this._token; const match = this._accept(TokenType.Dollar) && this._accept(TokenType.CurlyOpen) && (name = this._accept(TokenType.VariableName, true)); if (!match) { return this._backTo(token); } const 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.Forwardslash)) { // ${foo/<regex>/<format>/<options>} if (this._parseTransform(variable)) { parent.appendChild(variable); return true; } this._backTo(token); return false; } else if (this._accept(TokenType.CurlyClose)) { // ${foo} parent.appendChild(variable); return true; } else { // ${foo <- missing curly or colon return this._backTo(token); } } private _parseTransform(parent: TransformableMarker): boolean { // ...<regex>/<format>/<options>} let transform = new Transform(); let regexValue = ''; let regexOptions = ''; // (1) /regex while (true) { if (this._accept(TokenType.Forwardslash)) { break; } let escaped: string; if (escaped = this._accept(TokenType.Backslash, true)) { escaped = this._accept(TokenType.Forwardslash, true) || escaped; regexValue += escaped; continue; } if (this._token.type !== TokenType.EOF) { regexValue += this._accept(undefined, true); continue; } return false; } // (2) /format while (true) { if (this._accept(TokenType.Forwardslash)) { break; } let escaped: string; if (escaped = this._accept(TokenType.Backslash, true)) { escaped = this._accept(TokenType.Backslash, true) || this._accept(TokenType.Forwardslash, true) || escaped; transform.appendChild(new Text(escaped)); continue; } if (this._parseFormatString(transform) || this._parseAnything(transform)) { continue; } return false; } // (3) /option while (true) { if (this._accept(TokenType.CurlyClose)) { break; } if (this._token.type !== TokenType.EOF) { regexOptions += this._accept(undefined, true); continue; } return false; } try { transform.regexp = new RegExp(regexValue, regexOptions); } catch (e) { // invalid regexp return false; } parent.transform = transform; return true; } private _parseFormatString(parent: Transform): boolean { const token = this._token; if (!this._accept(TokenType.Dollar)) { return false; } let complex = false; if (this._accept(TokenType.CurlyOpen)) { complex = true; } let index = this._accept(TokenType.Int, true); if (!index) { this._backTo(token); return false; } else if (!complex) { // $1 parent.appendChild(new FormatString(Number(index))); return true; } else if (this._accept(TokenType.CurlyClose)) { // ${1} parent.appendChild(new FormatString(Number(index))); return true; } else if (!this._accept(TokenType.Colon)) { this._backTo(token); return false; } if (this._accept(TokenType.Forwardslash)) { // ${1:/upcase} let shorthand = this._accept(TokenType.VariableName, true); if (!shorthand || !this._accept(TokenType.CurlyClose)) { this._backTo(token); return false; } else { parent.appendChild(new FormatString(Number(index), shorthand)); return true; } } else if (this._accept(TokenType.Plus)) { // ${1:+<if>} let ifValue = this._until(TokenType.CurlyClose); if (ifValue) { parent.appendChild(new FormatString(Number(index), undefined, ifValue, undefined)); return true; } } else if (this._accept(TokenType.Dash)) { // ${2:-<else>} let elseValue = this._until(TokenType.CurlyClose); if (elseValue) { parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue)); return true; } } else if (this._accept(TokenType.QuestionMark)) { // ${2:?<if>:<else>} let ifValue = this._until(TokenType.Colon); if (ifValue) { let elseValue = this._until(TokenType.CurlyClose); if (elseValue) { parent.appendChild(new FormatString(Number(index), undefined, ifValue, elseValue)); return true; } } } else { // ${1:<else>} let elseValue = this._until(TokenType.CurlyClose); if (elseValue) { parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue)); return true; } } this._backTo(token); return false; } private _parseAnything(marker: Marker): boolean { if (this._token.type !== TokenType.EOF) { marker.appendChild(new Text(this._scanner.tokenText(this._token))); this._accept(undefined); return true; } return false; } }
src/vs/editor/contrib/snippet/snippetParser.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00036052713403478265, 0.00017493685299996287, 0.00016093419981189072, 0.0001718949351925403, 0.00002186151505156886 ]
{ "id": 1, "code_window": [ "\t$addKernel(handle: number, data: INotebookKernelDto2): void {\n", "\t\tconst that = this;\n", "\t\tconst kernel = new class extends MainThreadKernel {\n", "\t\t\tsetSelected(value: boolean): void {\n", "\t\t\t\tthat._proxy.$acceptSelection(handle, value);\n", "\t\t\t}\n", "\t\t\texecuteCells(uri: URI, ranges: ICellRange[]): void {\n", "\t\t\t\tthat._proxy.$executeCells(handle, uri, ranges);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tsetSelected(uri: URI, value: boolean): void {\n", "\t\t\t\tthat._proxy.$acceptSelection(handle, uri, value);\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 111 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as fs from 'fs'; import { getTempFile } from '../utils/temp.electron'; import Tracer from '../utils/tracer'; import { OngoingRequestCanceller, OngoingRequestCancellerFactory } from './cancellation'; export class NodeRequestCanceller implements OngoingRequestCanceller { public readonly cancellationPipeName: string; public constructor( private readonly _serverId: string, private readonly _tracer: Tracer, ) { this.cancellationPipeName = getTempFile('tscancellation'); } public tryCancelOngoingRequest(seq: number): boolean { if (!this.cancellationPipeName) { return false; } this._tracer.logTrace(this._serverId, `TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`); try { fs.writeFileSync(this.cancellationPipeName + seq, ''); } catch { // noop } return true; } } export const nodeRequestCancellerFactory = new class implements OngoingRequestCancellerFactory { create(serverId: string, tracer: Tracer): OngoingRequestCanceller { return new NodeRequestCanceller(serverId, tracer); } };
extensions/typescript-language-features/src/tsServer/cancellation.electron.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017759994079824537, 0.00016991395386867225, 0.00016486740787513554, 0.00016887868696358055, 0.000004787160833075177 ]
{ "id": 1, "code_window": [ "\t$addKernel(handle: number, data: INotebookKernelDto2): void {\n", "\t\tconst that = this;\n", "\t\tconst kernel = new class extends MainThreadKernel {\n", "\t\t\tsetSelected(value: boolean): void {\n", "\t\t\t\tthat._proxy.$acceptSelection(handle, value);\n", "\t\t\t}\n", "\t\t\texecuteCells(uri: URI, ranges: ICellRange[]): void {\n", "\t\t\t\tthat._proxy.$executeCells(handle, uri, ranges);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tsetSelected(uri: URI, value: boolean): void {\n", "\t\t\t\tthat._proxy.$acceptSelection(handle, uri, value);\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 111 }
{ "allowTrailingCommas": true, "title": "JSON schema for the JavaScript configuration file", "type": "object", "default": { "compilerOptions": { "target": "es6" } } }
extensions/typescript-language-features/schemas/jsconfig.schema.json
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.0001742093008942902, 0.00017352084978483617, 0.00017283239867538214, 0.00017352084978483617, 6.884511094540358e-7 ]
{ "id": 3, "code_window": [ "\t$acceptEditorPropertiesChanged(id: string, data: INotebookEditorPropertiesChangeData): void;\n", "\t$acceptEditorViewColumns(data: INotebookEditorViewColumnInfo): void;\n", "}\n", "\n", "export interface ExtHostNotebookKernelsShape {\n", "\t$acceptSelection(handle: number, value: boolean): void;\n", "\t$executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void;\n", "\t$cancelCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void;\n", "}\n", "\n", "export interface ExtHostStorageShape {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t$acceptSelection(handle: number, uri: UriComponents, value: boolean): void;\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { flatten } from 'vs/base/common/arrays'; import { Emitter, Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers'; import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookKernel2, INotebookKernel2ChangeEvent, INotebookKernelService } from 'vs/workbench/contrib/notebook/common/notebookKernelService'; import { NotebookSelector } from 'vs/workbench/contrib/notebook/common/notebookSelector'; import { ExtHostContext, ExtHostNotebookKernelsShape, IExtHostContext, INotebookKernelDto2, MainContext, MainThreadNotebookKernelsShape } from '../common/extHost.protocol'; abstract class MainThreadKernel implements INotebookKernel2 { private readonly _onDidChange = new Emitter<INotebookKernel2ChangeEvent>(); private readonly preloads: { uri: URI, provides: string[] }[]; readonly onDidChange: Event<INotebookKernel2ChangeEvent> = this._onDidChange.event; readonly id: string; readonly selector: NotebookSelector; readonly extensionId: ExtensionIdentifier; implementsInterrupt: boolean; label: string; description?: string; detail?: string; isPreferred?: boolean; supportedLanguages: string[]; implementsExecutionOrder: boolean; localResourceRoot: URI; public get preloadUris() { return this.preloads.map(p => p.uri); } public get preloadProvides() { return flatten(this.preloads.map(p => p.provides)); } constructor(data: INotebookKernelDto2) { this.id = data.id; this.selector = data.selector; this.extensionId = data.extensionId; this.implementsInterrupt = data.supportsInterrupt ?? false; this.label = data.label; this.description = data.description; this.isPreferred = data.isPreferred; this.supportedLanguages = data.supportedLanguages; this.implementsExecutionOrder = data.hasExecutionOrder ?? false; this.localResourceRoot = URI.revive(data.extensionLocation); this.preloads = data.preloads?.map(u => ({ uri: URI.revive(u.uri), provides: u.provides })) ?? []; } update(data: Partial<INotebookKernelDto2>) { const event: INotebookKernel2ChangeEvent = Object.create(null); if (data.label !== undefined) { this.label = data.label; event.label = true; } if (data.description !== undefined) { this.description = data.description; event.description = true; } if (data.isPreferred !== undefined) { this.isPreferred = data.isPreferred; event.isPreferred = true; } if (data.supportedLanguages !== undefined) { this.supportedLanguages = data.supportedLanguages; event.supportedLanguages = true; } if (data.hasExecutionOrder !== undefined) { this.implementsExecutionOrder = data.hasExecutionOrder; event.hasExecutionOrder = true; } this._onDidChange.fire(event); } abstract setSelected(value: boolean): void; abstract executeCells(uri: URI, ranges: ICellRange[]): void; abstract cancelCells(uri: URI, ranges: ICellRange[]): void; } @extHostNamedCustomer(MainContext.MainThreadNotebookKernels) export class MainThreadNotebookKernels implements MainThreadNotebookKernelsShape { private readonly _kernels = new Map<number, [kernel: MainThreadKernel, registraion: IDisposable]>(); private readonly _proxy: ExtHostNotebookKernelsShape; constructor( extHostContext: IExtHostContext, @INotebookKernelService private readonly _notebookKernelService: INotebookKernelService, ) { this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostNotebookKernels); } dispose(): void { for (let [, registration] of this._kernels.values()) { registration.dispose(); } } $addKernel(handle: number, data: INotebookKernelDto2): void { const that = this; const kernel = new class extends MainThreadKernel { setSelected(value: boolean): void { that._proxy.$acceptSelection(handle, value); } executeCells(uri: URI, ranges: ICellRange[]): void { that._proxy.$executeCells(handle, uri, ranges); } cancelCells(uri: URI, ranges: ICellRange[]): void { that._proxy.$cancelCells(handle, uri, ranges); } }(data); const disposable = this._notebookKernelService.addKernel(kernel); this._kernels.set(handle, [kernel, disposable]); } $updateKernel(handle: number, data: Partial<INotebookKernelDto2>): void { const tuple = this._kernels.get(handle); if (tuple) { tuple[0].update(data); } } $removeKernel(handle: number): void { const tuple = this._kernels.get(handle); if (tuple) { tuple[1].dispose(); this._kernels.delete(handle); } } }
src/vs/workbench/api/browser/mainThreadNotebookKernels.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.9992141723632812, 0.13427576422691345, 0.00016818511357996613, 0.0010208061430603266, 0.339256227016449 ]
{ "id": 3, "code_window": [ "\t$acceptEditorPropertiesChanged(id: string, data: INotebookEditorPropertiesChangeData): void;\n", "\t$acceptEditorViewColumns(data: INotebookEditorViewColumnInfo): void;\n", "}\n", "\n", "export interface ExtHostNotebookKernelsShape {\n", "\t$acceptSelection(handle: number, value: boolean): void;\n", "\t$executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void;\n", "\t$cancelCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void;\n", "}\n", "\n", "export interface ExtHostStorageShape {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t$acceptSelection(handle: number, uri: UriComponents, value: boolean): void;\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 1000 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M5.56253 2.51577C3.46348 3.4501 2 5.55414 2 7.99999C2 11.3137 4.68629 14 8 14C11.3137 14 14 11.3137 14 7.99999C14 5.32519 12.2497 3.05919 9.83199 2.28482L9.52968 3.23832C11.5429 3.88454 13 5.7721 13 7.99999C13 10.7614 10.7614 13 8 13C5.23858 13 3 10.7614 3 7.99999C3 6.31104 3.83742 4.81767 5.11969 3.91245L5.56253 2.51577Z" fill="#424242"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M5 3H2V2H5.5L6 2.5V6H5V3Z" fill="#424242"/> </svg>
extensions/search-result/src/media/refresh-light.svg
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00016769238573033363, 0.00016769238573033363, 0.00016769238573033363, 0.00016769238573033363, 0 ]
{ "id": 3, "code_window": [ "\t$acceptEditorPropertiesChanged(id: string, data: INotebookEditorPropertiesChangeData): void;\n", "\t$acceptEditorViewColumns(data: INotebookEditorViewColumnInfo): void;\n", "}\n", "\n", "export interface ExtHostNotebookKernelsShape {\n", "\t$acceptSelection(handle: number, value: boolean): void;\n", "\t$executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void;\n", "\t$cancelCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void;\n", "}\n", "\n", "export interface ExtHostStorageShape {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t$acceptSelection(handle: number, uri: UriComponents, value: boolean): void;\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle'; import { Event, Emitter } from 'vs/base/common/event'; import { isPromiseCanceledError, getErrorMessage, createErrorWithActions } from 'vs/base/common/errors'; import { PagedModel, IPagedModel, IPager, DelayedPagedModel } from 'vs/base/common/paging'; import { SortBy, SortOrder, IQueryOptions } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IExtensionManagementServer, IExtensionManagementServerService, EnablementState, IWorkbenchExtensionManagementService } from 'vs/workbench/services/extensionManagement/common/extensionManagement'; import { IExtensionRecommendationsService } from 'vs/workbench/services/extensionRecommendations/common/extensionRecommendations'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { append, $ } from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { Delegate, Renderer, IExtensionsViewState, EXTENSION_LIST_ELEMENT_HEIGHT } from 'vs/workbench/contrib/extensions/browser/extensionsList'; import { ExtensionState, IExtension, IExtensionsWorkbenchService, IWorkspaceRecommendedExtensionsView } from 'vs/workbench/contrib/extensions/common/extensions'; import { Query } from 'vs/workbench/contrib/extensions/common/extensionQuery'; import { IExtensionService, toExtension } from 'vs/workbench/services/extensions/common/extensions'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { attachBadgeStyler } from 'vs/platform/theme/common/styler'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { ManageExtensionAction, getContextMenuActions, ExtensionAction } from 'vs/workbench/contrib/extensions/browser/extensionsActions'; import { WorkbenchPagedList } from 'vs/platform/list/browser/listService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { INotificationService, Severity } from 'vs/platform/notification/common/notification'; import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPane'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { coalesce, distinct, flatten } from 'vs/base/common/arrays'; import { IExperimentService, IExperiment, ExperimentActionType } from 'vs/workbench/contrib/experiments/common/experimentService'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { IListContextMenuEvent } from 'vs/base/browser/ui/list/list'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IAction, Action, Separator, ActionRunner } from 'vs/base/common/actions'; import { ExtensionIdentifier, IExtensionDescription, isLanguagePackExtension } from 'vs/platform/extensions/common/extensions'; import { CancelablePromise, createCancelablePromise } from 'vs/base/common/async'; import { IProductService } from 'vs/platform/product/common/productService'; import { SeverityIcon } from 'vs/platform/severityIcon/common/severityIcon'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { IExtensionWorkspaceTrustRequestService } from 'vs/workbench/services/extensions/common/extensionWorkspaceTrustRequest'; // Extensions that are automatically classified as Programming Language extensions, but should be Feature extensions const FORCE_FEATURE_EXTENSIONS = ['vscode.git', 'vscode.search-result']; type WorkspaceRecommendationsClassification = { count: { classification: 'SystemMetaData', purpose: 'FeatureInsight', 'isMeasurement': true }; }; class ExtensionsViewState extends Disposable implements IExtensionsViewState { private readonly _onFocus: Emitter<IExtension> = this._register(new Emitter<IExtension>()); readonly onFocus: Event<IExtension> = this._onFocus.event; private readonly _onBlur: Emitter<IExtension> = this._register(new Emitter<IExtension>()); readonly onBlur: Event<IExtension> = this._onBlur.event; private currentlyFocusedItems: IExtension[] = []; onFocusChange(extensions: IExtension[]): void { this.currentlyFocusedItems.forEach(extension => this._onBlur.fire(extension)); this.currentlyFocusedItems = extensions; this.currentlyFocusedItems.forEach(extension => this._onFocus.fire(extension)); } } export interface ExtensionsListViewOptions { server?: IExtensionManagementServer; fixedHeight?: boolean; onDidChangeTitle?: Event<string>; } class ExtensionListViewWarning extends Error { } interface IQueryResult { readonly model: IPagedModel<IExtension>; readonly onDidChangeModel?: Event<IPagedModel<IExtension>>; readonly disposables: DisposableStore; } export class ExtensionsListView extends ViewPane { private bodyTemplate: { messageContainer: HTMLElement; messageSeverityIcon: HTMLElement; messageBox: HTMLElement; extensionsList: HTMLElement; } | undefined; private badge: CountBadge | undefined; private list: WorkbenchPagedList<IExtension> | null = null; private queryRequest: { query: string, request: CancelablePromise<IPagedModel<IExtension>> } | null = null; private queryResult: IQueryResult | undefined; private readonly contextMenuActionRunner = this._register(new ActionRunner()); constructor( protected readonly options: ExtensionsListViewOptions, viewletViewOptions: IViewletViewOptions, @INotificationService protected notificationService: INotificationService, @IKeybindingService keybindingService: IKeybindingService, @IContextMenuService contextMenuService: IContextMenuService, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @IExtensionService private readonly extensionService: IExtensionService, @IExtensionsWorkbenchService protected extensionsWorkbenchService: IExtensionsWorkbenchService, @IExtensionRecommendationsService protected extensionRecommendationsService: IExtensionRecommendationsService, @ITelemetryService telemetryService: ITelemetryService, @IConfigurationService configurationService: IConfigurationService, @IWorkspaceContextService protected contextService: IWorkspaceContextService, @IExperimentService private readonly experimentService: IExperimentService, @IExtensionManagementServerService protected readonly extensionManagementServerService: IExtensionManagementServerService, @IExtensionWorkspaceTrustRequestService private readonly extensionWorkspaceTrustRequestService: IExtensionWorkspaceTrustRequestService, @IWorkbenchExtensionManagementService protected readonly extensionManagementService: IWorkbenchExtensionManagementService, @IProductService protected readonly productService: IProductService, @IContextKeyService contextKeyService: IContextKeyService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IOpenerService openerService: IOpenerService, @IPreferencesService private readonly preferencesService: IPreferencesService, @IStorageService private readonly storageService: IStorageService, ) { super({ ...(viewletViewOptions as IViewPaneOptions), showActionsAlways: true, maximumBodySize: options.fixedHeight ? storageService.getNumber(viewletViewOptions.id, StorageScope.GLOBAL, 0) : undefined }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); if (this.options.onDidChangeTitle) { this._register(this.options.onDidChangeTitle(title => this.updateTitle(title))); } this._register(this.contextMenuActionRunner.onDidRun(({ error }) => error && this.notificationService.error(error))); this.registerActions(); } protected registerActions(): void { } protected override renderHeader(container: HTMLElement): void { container.classList.add('extension-view-header'); super.renderHeader(container); this.badge = new CountBadge(append(container, $('.count-badge-wrapper'))); this._register(attachBadgeStyler(this.badge, this.themeService)); } override renderBody(container: HTMLElement): void { super.renderBody(container); const extensionsList = append(container, $('.extensions-list')); const messageContainer = append(container, $('.message-container')); const messageSeverityIcon = append(messageContainer, $('')); const messageBox = append(messageContainer, $('.message')); const delegate = new Delegate(); const extensionsViewState = new ExtensionsViewState(); const renderer = this.instantiationService.createInstance(Renderer, extensionsViewState); this.list = this.instantiationService.createInstance(WorkbenchPagedList, 'Extensions', extensionsList, delegate, [renderer], { multipleSelectionSupport: false, setRowLineHeight: false, horizontalScrolling: false, accessibilityProvider: <IListAccessibilityProvider<IExtension | null>>{ getAriaLabel(extension: IExtension | null): string { return extension ? localize('extension.arialabel', "{0}, {1}, {2}, {3}", extension.displayName, extension.version, extension.publisherDisplayName, extension.description) : ''; }, getWidgetAriaLabel(): string { return localize('extensions', "Extensions"); } }, overrideStyles: { listBackground: SIDE_BAR_BACKGROUND }, openOnSingleClick: true }) as WorkbenchPagedList<IExtension>; this._register(this.list.onContextMenu(e => this.onContextMenu(e), this)); this._register(this.list.onDidChangeFocus(e => extensionsViewState.onFocusChange(coalesce(e.elements)), this)); this._register(this.list); this._register(extensionsViewState); this._register(Event.debounce(Event.filter(this.list.onDidOpen, e => e.element !== null), (_, event) => event, 75, true)(options => { this.openExtension(options.element!, { sideByside: options.sideBySide, ...options.editorOptions }); })); this.bodyTemplate = { extensionsList, messageBox, messageContainer, messageSeverityIcon }; } protected override layoutBody(height: number, width: number): void { super.layoutBody(height, width); if (this.bodyTemplate) { this.bodyTemplate.extensionsList.style.height = height + 'px'; } if (this.list) { this.list.layout(height, width); } } async show(query: string, refresh?: boolean): Promise<IPagedModel<IExtension>> { if (this.queryRequest) { if (!refresh && this.queryRequest.query === query) { return this.queryRequest.request; } this.queryRequest.request.cancel(); this.queryRequest = null; } if (this.queryResult) { this.queryResult.disposables.dispose(); this.queryResult = undefined; } const parsedQuery = Query.parse(query); let options: IQueryOptions = { sortOrder: SortOrder.Default }; switch (parsedQuery.sortBy) { case 'installs': options.sortBy = SortBy.InstallCount; break; case 'rating': options.sortBy = SortBy.WeightedRating; break; case 'name': options.sortBy = SortBy.Title; break; case 'publishedDate': options.sortBy = SortBy.PublishedDate; break; } const request = createCancelablePromise(async token => { try { this.queryResult = await this.query(parsedQuery, options, token); const model = this.queryResult.model; this.setModel(model); if (this.queryResult.onDidChangeModel) { this.queryResult.disposables.add(this.queryResult.onDidChangeModel(model => this.updateModel(model))); } return model; } catch (e) { const model = new PagedModel([]); if (!isPromiseCanceledError(e)) { this.setModel(model, e); } return this.list ? this.list.model : model; } }); request.finally(() => this.queryRequest = null); this.queryRequest = { query, request }; return request; } count(): number { return this.list ? this.list.length : 0; } protected showEmptyModel(): Promise<IPagedModel<IExtension>> { const emptyModel = new PagedModel([]); this.setModel(emptyModel); return Promise.resolve(emptyModel); } private async onContextMenu(e: IListContextMenuEvent<IExtension>): Promise<void> { if (e.element) { const runningExtensions = await this.extensionService.getExtensions(); const manageExtensionAction = this.instantiationService.createInstance(ManageExtensionAction); manageExtensionAction.extension = e.element; let groups: IAction[][] = []; if (manageExtensionAction.enabled) { groups = await manageExtensionAction.getActionGroups(runningExtensions); } else if (e.element) { groups = getContextMenuActions(e.element, false, this.instantiationService); groups.forEach(group => group.forEach(extensionAction => { if (extensionAction instanceof ExtensionAction) { extensionAction.extension = e.element!; } })); } let actions: IAction[] = []; for (const menuActions of groups) { actions = [...actions, ...menuActions, new Separator()]; } actions.pop(); this.contextMenuService.showContextMenu({ getAnchor: () => e.anchor, getActions: () => actions, actionRunner: this.contextMenuActionRunner, }); } } private async query(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IQueryResult> { const idRegex = /@id:(([a-z0-9A-Z][a-z0-9\-A-Z]*)\.([a-z0-9A-Z][a-z0-9\-A-Z]*))/g; const ids: string[] = []; let idMatch; while ((idMatch = idRegex.exec(query.value)) !== null) { const name = idMatch[1]; ids.push(name); } if (ids.length) { const model = await this.queryByIds(ids, options, token); return { model, disposables: new DisposableStore() }; } if (ExtensionsListView.isLocalExtensionsQuery(query.value)) { return this.queryLocal(query, options); } try { const model = await this.queryGallery(query, options, token); return { model, disposables: new DisposableStore() }; } catch (e) { console.warn('Error querying extensions gallery', getErrorMessage(e)); return Promise.reject(new ExtensionListViewWarning(localize('galleryError', "We cannot connect to the Extensions Marketplace at this time, please try again later."))); } } private async queryByIds(ids: string[], options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> { const idsSet: Set<string> = ids.reduce((result, id) => { result.add(id.toLowerCase()); return result; }, new Set<string>()); const result = (await this.extensionsWorkbenchService.queryLocal(this.options.server)) .filter(e => idsSet.has(e.identifier.id.toLowerCase())); if (result.length) { return this.getPagedModel(this.sortExtensions(result, options)); } return this.extensionsWorkbenchService.queryGallery({ names: ids, source: 'queryById' }, token) .then(pager => this.getPagedModel(pager)); } private async queryLocal(query: Query, options: IQueryOptions): Promise<IQueryResult> { const local = await this.extensionsWorkbenchService.queryLocal(this.options.server); const runningExtensions = await this.extensionService.getExtensions(); let { extensions, canIncludeInstalledExtensions } = this.filterLocal(local, runningExtensions, query, options); const disposables = new DisposableStore(); const onDidChangeModel = disposables.add(new Emitter<IPagedModel<IExtension>>()); if (canIncludeInstalledExtensions) { let isDisposed: boolean = false; disposables.add(toDisposable(() => isDisposed = true)); disposables.add(Event.debounce(Event.any( Event.filter(this.extensionsWorkbenchService.onChange, e => e?.state === ExtensionState.Installed), this.extensionService.onDidChangeExtensions ), () => undefined)(async () => { const local = this.options.server ? this.extensionsWorkbenchService.installed.filter(e => e.server === this.options.server) : this.extensionsWorkbenchService.local; const runningExtensions = await this.extensionService.getExtensions(); const { extensions: newExtensions } = this.filterLocal(local, runningExtensions, query, options); if (!isDisposed) { const mergedExtensions = this.mergeAddedExtensions(extensions, newExtensions); if (mergedExtensions) { extensions = mergedExtensions; onDidChangeModel.fire(new PagedModel(extensions)); } } })); } return { model: new PagedModel(extensions), onDidChangeModel: onDidChangeModel.event, disposables }; } private filterLocal(local: IExtension[], runningExtensions: IExtensionDescription[], query: Query, options: IQueryOptions): { extensions: IExtension[], canIncludeInstalledExtensions: boolean } { let value = query.value; let extensions: IExtension[] = []; let canIncludeInstalledExtensions = true; if (/@builtin/i.test(value)) { extensions = this.filterBuiltinExtensions(local, query, options); canIncludeInstalledExtensions = false; } else if (/@installed/i.test(value)) { extensions = this.filterInstalledExtensions(local, runningExtensions, query, options); } else if (/@outdated/i.test(value)) { extensions = this.filterOutdatedExtensions(local, query, options); } else if (/@disabled/i.test(value)) { extensions = this.filterDisabledExtensions(local, runningExtensions, query, options); } else if (/@enabled/i.test(value)) { extensions = this.filterEnabledExtensions(local, runningExtensions, query, options); } else if (/@trustRequired/i.test(value)) { extensions = this.filterTrustRequiredExtensions(local, query, options); } return { extensions, canIncludeInstalledExtensions }; } private filterBuiltinExtensions(local: IExtension[], query: Query, options: IQueryOptions): IExtension[] { let value = query.value; const showThemesOnly = /@builtin:themes/i.test(value); if (showThemesOnly) { value = value.replace(/@builtin:themes/g, ''); } const showBasicsOnly = /@builtin:basics/i.test(value); if (showBasicsOnly) { value = value.replace(/@builtin:basics/g, ''); } const showFeaturesOnly = /@builtin:features/i.test(value); if (showFeaturesOnly) { value = value.replace(/@builtin:features/g, ''); } value = value.replace(/@builtin/g, '').replace(/@sort:(\w+)(-\w*)?/g, '').trim().toLowerCase(); let result = local .filter(e => e.isBuiltin && (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1)); const isThemeExtension = (e: IExtension): boolean => { return (Array.isArray(e.local?.manifest?.contributes?.themes) && e.local!.manifest!.contributes!.themes.length > 0) || (Array.isArray(e.local?.manifest?.contributes?.iconThemes) && e.local!.manifest!.contributes!.iconThemes.length > 0); }; if (showThemesOnly) { const themesExtensions = result.filter(isThemeExtension); return this.sortExtensions(themesExtensions, options); } const isLangaugeBasicExtension = (e: IExtension): boolean => { return FORCE_FEATURE_EXTENSIONS.indexOf(e.identifier.id) === -1 && (Array.isArray(e.local?.manifest?.contributes?.grammars) && e.local!.manifest!.contributes!.grammars.length > 0); }; if (showBasicsOnly) { const basics = result.filter(isLangaugeBasicExtension); return this.sortExtensions(basics, options); } if (showFeaturesOnly) { const others = result.filter(e => { return e.local && e.local.manifest && !isThemeExtension(e) && !isLangaugeBasicExtension(e); }); return this.sortExtensions(others, options); } return this.sortExtensions(result, options); } private parseCategories(value: string): { value: string, categories: string[] } { const categories: string[] = []; value = value.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category) => { const entry = (category || quotedCategory || '').toLowerCase(); if (categories.indexOf(entry) === -1) { categories.push(entry); } return ''; }); return { value, categories }; } private filterInstalledExtensions(local: IExtension[], runningExtensions: IExtensionDescription[], query: Query, options: IQueryOptions): IExtension[] { let { value, categories } = this.parseCategories(query.value); value = value.replace(/@installed/g, '').replace(/@sort:(\w+)(-\w*)?/g, '').trim().toLowerCase(); let result = local .filter(e => !e.isBuiltin && (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1) && (!categories.length || categories.some(category => (e.local && e.local.manifest.categories || []).some(c => c.toLowerCase() === category)))); if (options.sortBy !== undefined) { result = this.sortExtensions(result, options); } else { const runningExtensionsById = runningExtensions.reduce((result, e) => { result.set(ExtensionIdentifier.toKey(e.identifier.value), e); return result; }, new Map<string, IExtensionDescription>()); result = result.sort((e1, e2) => { const running1 = runningExtensionsById.get(ExtensionIdentifier.toKey(e1.identifier.id)); const isE1Running = running1 && this.extensionManagementServerService.getExtensionManagementServer(toExtension(running1)) === e1.server; const running2 = runningExtensionsById.get(ExtensionIdentifier.toKey(e2.identifier.id)); const isE2Running = running2 && this.extensionManagementServerService.getExtensionManagementServer(toExtension(running2)) === e2.server; if ((isE1Running && isE2Running)) { return e1.displayName.localeCompare(e2.displayName); } const isE1LanguagePackExtension = e1.local && isLanguagePackExtension(e1.local.manifest); const isE2LanguagePackExtension = e2.local && isLanguagePackExtension(e2.local.manifest); if (!isE1Running && !isE2Running) { if (isE1LanguagePackExtension) { return -1; } if (isE2LanguagePackExtension) { return 1; } return e1.displayName.localeCompare(e2.displayName); } if ((isE1Running && isE2LanguagePackExtension) || (isE2Running && isE1LanguagePackExtension)) { return e1.displayName.localeCompare(e2.displayName); } return isE1Running ? -1 : 1; }); } return result; } private filterOutdatedExtensions(local: IExtension[], query: Query, options: IQueryOptions): IExtension[] { let { value, categories } = this.parseCategories(query.value); value = value.replace(/@outdated/g, '').replace(/@sort:(\w+)(-\w*)?/g, '').trim().toLowerCase(); const result = local .sort((e1, e2) => e1.displayName.localeCompare(e2.displayName)) .filter(extension => extension.outdated && (extension.name.toLowerCase().indexOf(value) > -1 || extension.displayName.toLowerCase().indexOf(value) > -1) && (!categories.length || categories.some(category => !!extension.local && extension.local.manifest.categories!.some(c => c.toLowerCase() === category)))); return this.sortExtensions(result, options); } private filterDisabledExtensions(local: IExtension[], runningExtensions: IExtensionDescription[], query: Query, options: IQueryOptions): IExtension[] { let { value, categories } = this.parseCategories(query.value); value = value.replace(/@disabled/g, '').replace(/@sort:(\w+)(-\w*)?/g, '').trim().toLowerCase(); const result = local .sort((e1, e2) => e1.displayName.localeCompare(e2.displayName)) .filter(e => runningExtensions.every(r => !areSameExtensions({ id: r.identifier.value, uuid: r.uuid }, e.identifier)) && (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1) && (!categories.length || categories.some(category => (e.local && e.local.manifest.categories || []).some(c => c.toLowerCase() === category)))); return this.sortExtensions(result, options); } private filterEnabledExtensions(local: IExtension[], runningExtensions: IExtensionDescription[], query: Query, options: IQueryOptions): IExtension[] { let { value, categories } = this.parseCategories(query.value); value = value ? value.replace(/@enabled/g, '').replace(/@sort:(\w+)(-\w*)?/g, '').trim().toLowerCase() : ''; local = local.filter(e => !e.isBuiltin); const result = local .sort((e1, e2) => e1.displayName.localeCompare(e2.displayName)) .filter(e => runningExtensions.some(r => areSameExtensions({ id: r.identifier.value, uuid: r.uuid }, e.identifier)) && (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1) && (!categories.length || categories.some(category => (e.local && e.local.manifest.categories || []).some(c => c.toLowerCase() === category)))); return this.sortExtensions(result, options); } private filterTrustRequiredExtensions(local: IExtension[], query: Query, options: IQueryOptions): IExtension[] { let value = query.value; const onStartOnly = /@trustRequired:onStart/i.test(value); if (onStartOnly) { value = value.replace(/@trustRequired:onStart/g, ''); } const onDemandOnly = /@trustRequired:onDemand/i.test(value); if (onDemandOnly) { value = value.replace(/@trustRequired:onDemand/g, ''); } value = value.replace(/@trustRequired/g, '').replace(/@sort:(\w+)(-\w*)?/g, '').trim().toLowerCase(); const result = local.filter(extension => extension.local && this.extensionWorkspaceTrustRequestService.getExtensionWorkspaceTrustRequestType(extension.local.manifest) !== 'never' && (extension.name.toLowerCase().indexOf(value) > -1 || extension.displayName.toLowerCase().indexOf(value) > -1)); if (onStartOnly) { const onStartExtensions = result.filter(extension => extension.local && this.extensionWorkspaceTrustRequestService.getExtensionWorkspaceTrustRequestType(extension.local.manifest) === 'onStart'); return this.sortExtensions(onStartExtensions, options); } if (onDemandOnly) { const onDemandExtensions = result.filter(extension => extension.local && this.extensionWorkspaceTrustRequestService.getExtensionWorkspaceTrustRequestType(extension.local.manifest) === 'onDemand'); return this.sortExtensions(onDemandExtensions, options); } return this.sortExtensions(result, options); } private mergeAddedExtensions(extensions: IExtension[], newExtensions: IExtension[]): IExtension[] | undefined { const oldExtensions = [...extensions]; const findPreviousExtensionIndex = (from: number): number => { let index = -1; const previousExtensionInNew = newExtensions[from]; if (previousExtensionInNew) { index = oldExtensions.findIndex(e => areSameExtensions(e.identifier, previousExtensionInNew.identifier)); if (index === -1) { return findPreviousExtensionIndex(from - 1); } } return index; }; let hasChanged: boolean = false; for (let index = 0; index < newExtensions.length; index++) { const extension = newExtensions[index]; if (extensions.every(r => !areSameExtensions(r.identifier, extension.identifier))) { hasChanged = true; extensions.splice(findPreviousExtensionIndex(index - 1) + 1, 0, extension); } } return hasChanged ? extensions : undefined; } private async queryGallery(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> { const hasUserDefinedSortOrder = options.sortBy !== undefined; if (!hasUserDefinedSortOrder && !query.value.trim()) { options.sortBy = SortBy.InstallCount; } if (this.isRecommendationsQuery(query)) { return this.queryRecommendations(query, options, token); } if (/\bcurated:([^\s]+)\b/.test(query.value)) { return this.getCuratedModel(query, options, token); } const text = query.value; if (/\bext:([^\s]+)\b/g.test(text)) { options.text = text; options.source = 'file-extension-tags'; return this.extensionsWorkbenchService.queryGallery(options, token).then(pager => this.getPagedModel(pager)); } let preferredResults: string[] = []; if (text) { options.text = text.substr(0, 350); options.source = 'searchText'; if (!hasUserDefinedSortOrder) { const searchExperiments = await this.getSearchExperiments(); for (const experiment of searchExperiments) { if (experiment.action && text.toLowerCase() === experiment.action.properties['searchText'] && Array.isArray(experiment.action.properties['preferredResults'])) { preferredResults = experiment.action.properties['preferredResults']; options.source += `-experiment-${experiment.id}`; break; } } } } else { options.source = 'viewlet'; } const pager = await this.extensionsWorkbenchService.queryGallery(options, token); let positionToUpdate = 0; for (const preferredResult of preferredResults) { for (let j = positionToUpdate; j < pager.firstPage.length; j++) { if (areSameExtensions(pager.firstPage[j].identifier, { id: preferredResult })) { if (positionToUpdate !== j) { const preferredExtension = pager.firstPage.splice(j, 1)[0]; pager.firstPage.splice(positionToUpdate, 0, preferredExtension); positionToUpdate++; } break; } } } return this.getPagedModel(pager); } private _searchExperiments: Promise<IExperiment[]> | undefined; private getSearchExperiments(): Promise<IExperiment[]> { if (!this._searchExperiments) { this._searchExperiments = this.experimentService.getExperimentsByType(ExperimentActionType.ExtensionSearchResults); } return this._searchExperiments; } private sortExtensions(extensions: IExtension[], options: IQueryOptions): IExtension[] { switch (options.sortBy) { case SortBy.InstallCount: extensions = extensions.sort((e1, e2) => typeof e2.installCount === 'number' && typeof e1.installCount === 'number' ? e2.installCount - e1.installCount : NaN); break; case SortBy.AverageRating: case SortBy.WeightedRating: extensions = extensions.sort((e1, e2) => typeof e2.rating === 'number' && typeof e1.rating === 'number' ? e2.rating - e1.rating : NaN); break; default: extensions = extensions.sort((e1, e2) => e1.displayName.localeCompare(e2.displayName)); break; } if (options.sortOrder === SortOrder.Descending) { extensions = extensions.reverse(); } return extensions; } private async getCuratedModel(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> { const value = query.value.replace(/curated:/g, '').trim(); const names = await this.experimentService.getCuratedExtensionsList(value); if (Array.isArray(names) && names.length) { options.source = `curated:${value}`; options.names = names; options.pageSize = names.length; const pager = await this.extensionsWorkbenchService.queryGallery(options, token); this.sortFirstPage(pager, names); return this.getPagedModel(pager || []); } return new PagedModel([]); } private isRecommendationsQuery(query: Query): boolean { return ExtensionsListView.isWorkspaceRecommendedExtensionsQuery(query.value) || ExtensionsListView.isKeymapsRecommendedExtensionsQuery(query.value) || ExtensionsListView.isExeRecommendedExtensionsQuery(query.value) || /@recommended:all/i.test(query.value) || ExtensionsListView.isSearchRecommendedExtensionsQuery(query.value) || ExtensionsListView.isRecommendedExtensionsQuery(query.value); } private async queryRecommendations(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> { // Workspace recommendations if (ExtensionsListView.isWorkspaceRecommendedExtensionsQuery(query.value)) { return this.getWorkspaceRecommendationsModel(query, options, token); } // Keymap recommendations if (ExtensionsListView.isKeymapsRecommendedExtensionsQuery(query.value)) { return this.getKeymapRecommendationsModel(query, options, token); } // Exe recommendations if (ExtensionsListView.isExeRecommendedExtensionsQuery(query.value)) { return this.getExeRecommendationsModel(query, options, token); } // All recommendations if (/@recommended:all/i.test(query.value)) { return this.getAllRecommendationsModel(options, token); } // Search recommendations if (ExtensionsListView.isSearchRecommendedExtensionsQuery(query.value) || (ExtensionsListView.isRecommendedExtensionsQuery(query.value) && options.sortBy !== undefined)) { return this.searchRecommendations(query, options, token); } // Other recommendations if (ExtensionsListView.isRecommendedExtensionsQuery(query.value)) { return this.getOtherRecommendationsModel(query, options, token); } return new PagedModel([]); } protected async getInstallableRecommendations(recommendations: string[], options: IQueryOptions, token: CancellationToken): Promise<IExtension[]> { const extensions: IExtension[] = []; if (recommendations.length) { const pager = await this.extensionsWorkbenchService.queryGallery({ ...options, names: recommendations, pageSize: recommendations.length }, token); for (const extension of pager.firstPage) { if (extension.gallery && (await this.extensionManagementService.canInstall(extension.gallery))) { extensions.push(extension); } } } return extensions; } protected async getWorkspaceRecommendations(): Promise<string[]> { const recommendations = await this.extensionRecommendationsService.getWorkspaceRecommendations(); const { important } = await this.extensionRecommendationsService.getConfigBasedRecommendations(); for (const configBasedRecommendation of important) { if (!recommendations.find(extensionId => extensionId === configBasedRecommendation)) { recommendations.push(configBasedRecommendation); } } return recommendations; } private async getWorkspaceRecommendationsModel(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> { const recommendations = await this.getWorkspaceRecommendations(); const installableRecommendations = (await this.getInstallableRecommendations(recommendations, { ...options, source: 'recommendations-workspace' }, token)); this.telemetryService.publicLog2<{ count: number }, WorkspaceRecommendationsClassification>('extensionWorkspaceRecommendations:open', { count: installableRecommendations.length }); const result: IExtension[] = coalesce(recommendations.map(id => installableRecommendations.find(i => areSameExtensions(i.identifier, { id })))); return new PagedModel(result); } private async getKeymapRecommendationsModel(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> { const value = query.value.replace(/@recommended:keymaps/g, '').trim().toLowerCase(); const recommendations = this.extensionRecommendationsService.getKeymapRecommendations(); const installableRecommendations = (await this.getInstallableRecommendations(recommendations, { ...options, source: 'recommendations-keymaps' }, token)) .filter(extension => extension.identifier.id.toLowerCase().indexOf(value) > -1); return new PagedModel(installableRecommendations); } private async getExeRecommendationsModel(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> { const exe = query.value.replace(/@exe:/g, '').trim().toLowerCase(); const { important, others } = await this.extensionRecommendationsService.getExeBasedRecommendations(exe.startsWith('"') ? exe.substring(1, exe.length - 1) : exe); const installableRecommendations = await this.getInstallableRecommendations([...important, ...others], { ...options, source: 'recommendations-exe' }, token); return new PagedModel(installableRecommendations); } private async getOtherRecommendationsModel(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> { const otherRecommendations = await this.getOtherRecommendations(); const installableRecommendations = await this.getInstallableRecommendations(otherRecommendations, { ...options, source: 'recommendations-other', sortBy: undefined }, token); const result = coalesce(otherRecommendations.map(id => installableRecommendations.find(i => areSameExtensions(i.identifier, { id })))); return new PagedModel(result); } private async getOtherRecommendations(): Promise<string[]> { const local = (await this.extensionsWorkbenchService.queryLocal(this.options.server)) .map(e => e.identifier.id.toLowerCase()); const workspaceRecommendations = (await this.getWorkspaceRecommendations()) .map(extensionId => extensionId.toLowerCase()); return distinct( flatten(await Promise.all([ // Order is important this.extensionRecommendationsService.getImportantRecommendations(), this.extensionRecommendationsService.getFileBasedRecommendations(), this.extensionRecommendationsService.getOtherRecommendations() ])).filter(extensionId => !local.includes(extensionId.toLowerCase()) && !workspaceRecommendations.includes(extensionId.toLowerCase()) ), extensionId => extensionId.toLowerCase()); } // Get All types of recommendations, trimmed to show a max of 8 at any given time private async getAllRecommendationsModel(options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> { const local = (await this.extensionsWorkbenchService.queryLocal(this.options.server)).map(e => e.identifier.id.toLowerCase()); const allRecommendations = distinct( flatten(await Promise.all([ // Order is important this.getWorkspaceRecommendations(), this.extensionRecommendationsService.getImportantRecommendations(), this.extensionRecommendationsService.getFileBasedRecommendations(), this.extensionRecommendationsService.getOtherRecommendations() ])).filter(extensionId => !local.includes(extensionId.toLowerCase()) ), extensionId => extensionId.toLowerCase()); const installableRecommendations = await this.getInstallableRecommendations(allRecommendations, { ...options, source: 'recommendations-all', sortBy: undefined }, token); const result: IExtension[] = coalesce(allRecommendations.map(id => installableRecommendations.find(i => areSameExtensions(i.identifier, { id })))); return new PagedModel(result.slice(0, 8)); } private async searchRecommendations(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> { const value = query.value.replace(/@recommended/g, '').trim().toLowerCase(); const recommendations = distinct([...await this.getWorkspaceRecommendations(), ...await this.getOtherRecommendations()]); const installableRecommendations = (await this.getInstallableRecommendations(recommendations, { ...options, source: 'recommendations', sortBy: undefined }, token)) .filter(extension => extension.identifier.id.toLowerCase().indexOf(value) > -1); const result = coalesce(recommendations.map(id => installableRecommendations.find(i => areSameExtensions(i.identifier, { id })))); return new PagedModel(this.sortExtensions(result, options)); } // Sorts the firstPage of the pager in the same order as given array of extension ids private sortFirstPage(pager: IPager<IExtension>, ids: string[]) { ids = ids.map(x => x.toLowerCase()); pager.firstPage.sort((a, b) => { return ids.indexOf(a.identifier.id.toLowerCase()) < ids.indexOf(b.identifier.id.toLowerCase()) ? -1 : 1; }); } private setModel(model: IPagedModel<IExtension>, error?: any) { if (this.list) { this.list.model = new DelayedPagedModel(model); this.list.scrollTop = 0; this.updateBody(error); } } private updateBody(error?: any): void { const count = this.count(); if (this.bodyTemplate && this.badge) { this.bodyTemplate.extensionsList.classList.toggle('hidden', count === 0); this.bodyTemplate.messageContainer.classList.toggle('hidden', count > 0); this.badge.setCount(count); if (count === 0 && this.isBodyVisible()) { if (error) { if (error instanceof ExtensionListViewWarning) { this.bodyTemplate.messageSeverityIcon.className = SeverityIcon.className(Severity.Warning); this.bodyTemplate.messageBox.textContent = getErrorMessage(error); } else { this.bodyTemplate.messageSeverityIcon.className = SeverityIcon.className(Severity.Error); this.bodyTemplate.messageBox.textContent = localize('error', "Error while loading extensions. {0}", getErrorMessage(error)); } } else { this.bodyTemplate.messageSeverityIcon.className = ''; this.bodyTemplate.messageBox.textContent = localize('no extensions found', "No extensions found."); } alert(this.bodyTemplate.messageBox.textContent); } } this.updateSize(); } protected updateSize() { if (this.options.fixedHeight) { const length = this.list?.model.length || 0; this.minimumBodySize = Math.min(length, 3) * EXTENSION_LIST_ELEMENT_HEIGHT; this.maximumBodySize = length * EXTENSION_LIST_ELEMENT_HEIGHT; this.storageService.store(this.id, this.maximumBodySize, StorageScope.GLOBAL, StorageTarget.MACHINE); } } private updateModel(model: IPagedModel<IExtension>) { if (this.list) { this.list.model = new DelayedPagedModel(model); this.updateBody(); } } private openExtension(extension: IExtension, options: { sideByside?: boolean, preserveFocus?: boolean, pinned?: boolean }): void { extension = this.extensionsWorkbenchService.local.filter(e => areSameExtensions(e.identifier, extension.identifier))[0] || extension; this.extensionsWorkbenchService.open(extension, options).then(undefined, err => this.onError(err)); } private onError(err: any): void { if (isPromiseCanceledError(err)) { return; } const message = err && err.message || ''; if (/ECONNREFUSED/.test(message)) { const error = createErrorWithActions(localize('suggestProxyError', "Marketplace returned 'ECONNREFUSED'. Please check the 'http.proxy' setting."), { actions: [ new Action('open user settings', localize('open user settings', "Open User Settings"), undefined, true, () => this.preferencesService.openGlobalSettings()) ] }); this.notificationService.error(error); return; } this.notificationService.error(err); } private getPagedModel(arg: IPager<IExtension> | IExtension[]): IPagedModel<IExtension> { if (Array.isArray(arg)) { return new PagedModel(arg); } const pager = { total: arg.total, pageSize: arg.pageSize, firstPage: arg.firstPage, getPage: (pageIndex: number, cancellationToken: CancellationToken) => arg.getPage(pageIndex, cancellationToken) }; return new PagedModel(pager); } override dispose(): void { super.dispose(); if (this.queryRequest) { this.queryRequest.request.cancel(); this.queryRequest = null; } if (this.queryResult) { this.queryResult.disposables.dispose(); this.queryResult = undefined; } this.list = null; } static isLocalExtensionsQuery(query: string): boolean { return this.isInstalledExtensionsQuery(query) || this.isOutdatedExtensionsQuery(query) || this.isEnabledExtensionsQuery(query) || this.isDisabledExtensionsQuery(query) || this.isBuiltInExtensionsQuery(query) || this.isSearchBuiltInExtensionsQuery(query) || this.isBuiltInGroupExtensionsQuery(query) || this.isTrustRequiredExtensionsQuery(query) || this.isTrustRequiredGroupExtensionsQuery(query); } static isSearchBuiltInExtensionsQuery(query: string): boolean { return /@builtin\s.+/i.test(query); } static isBuiltInExtensionsQuery(query: string): boolean { return /^\s*@builtin$/i.test(query.trim()); } static isBuiltInGroupExtensionsQuery(query: string): boolean { return /^\s*@builtin:.+$/i.test(query.trim()); } static isTrustRequiredExtensionsQuery(query: string): boolean { return /^\s*@trustRequired$/i.test(query.trim()); } static isTrustRequiredGroupExtensionsQuery(query: string): boolean { return /^\s*@trustRequired:.+$/i.test(query.trim()); } static isInstalledExtensionsQuery(query: string): boolean { return /@installed/i.test(query); } static isOutdatedExtensionsQuery(query: string): boolean { return /@outdated/i.test(query); } static isEnabledExtensionsQuery(query: string): boolean { return /@enabled/i.test(query); } static isDisabledExtensionsQuery(query: string): boolean { return /@disabled/i.test(query); } static isRecommendedExtensionsQuery(query: string): boolean { return /^@recommended$/i.test(query.trim()); } static isSearchRecommendedExtensionsQuery(query: string): boolean { return /@recommended\s.+/i.test(query); } static isWorkspaceRecommendedExtensionsQuery(query: string): boolean { return /@recommended:workspace/i.test(query); } static isExeRecommendedExtensionsQuery(query: string): boolean { return /@exe:.+/i.test(query); } static isKeymapsRecommendedExtensionsQuery(query: string): boolean { return /@recommended:keymaps/i.test(query); } override focus(): void { super.focus(); if (!this.list) { return; } if (!(this.list.getFocus().length || this.list.getSelection().length)) { this.list.focusNext(); } this.list.domFocus(); } } export class ServerInstalledExtensionsView extends ExtensionsListView { async override show(query: string): Promise<IPagedModel<IExtension>> { query = query ? query : '@installed'; if (!ExtensionsListView.isLocalExtensionsQuery(query)) { query = query += ' @installed'; } return super.show(query.trim()); } } export class EnabledExtensionsView extends ExtensionsListView { async override show(query: string): Promise<IPagedModel<IExtension>> { query = query || '@enabled'; return ExtensionsListView.isEnabledExtensionsQuery(query) ? super.show(query) : this.showEmptyModel(); } } export class DisabledExtensionsView extends ExtensionsListView { async override show(query: string): Promise<IPagedModel<IExtension>> { query = query || '@disabled'; return ExtensionsListView.isDisabledExtensionsQuery(query) ? super.show(query) : this.showEmptyModel(); } } export class BuiltInFeatureExtensionsView extends ExtensionsListView { async override show(query: string): Promise<IPagedModel<IExtension>> { return (query && query.trim() !== '@builtin') ? this.showEmptyModel() : super.show('@builtin:features'); } } export class BuiltInThemesExtensionsView extends ExtensionsListView { async override show(query: string): Promise<IPagedModel<IExtension>> { return (query && query.trim() !== '@builtin') ? this.showEmptyModel() : super.show('@builtin:themes'); } } export class BuiltInProgrammingLanguageExtensionsView extends ExtensionsListView { async override show(query: string): Promise<IPagedModel<IExtension>> { return (query && query.trim() !== '@builtin') ? this.showEmptyModel() : super.show('@builtin:basics'); } } export class TrustRequiredOnStartExtensionsView extends ExtensionsListView { async override show(query: string): Promise<IPagedModel<IExtension>> { return (query && query.trim() !== '@trustRequired') ? this.showEmptyModel() : super.show('@trustRequired:onStart'); } } export class TrustRequiredOnDemandExtensionsView extends ExtensionsListView { async override show(query: string): Promise<IPagedModel<IExtension>> { return (query && query.trim() !== '@trustRequired') ? this.showEmptyModel() : super.show('@trustRequired:onDemand'); } } export class DefaultRecommendedExtensionsView extends ExtensionsListView { private readonly recommendedExtensionsQuery = '@recommended:all'; override renderBody(container: HTMLElement): void { super.renderBody(container); this._register(this.extensionRecommendationsService.onDidChangeRecommendations(() => { this.show(''); })); } async override show(query: string): Promise<IPagedModel<IExtension>> { if (query && query.trim() !== this.recommendedExtensionsQuery) { return this.showEmptyModel(); } const model = await super.show(this.recommendedExtensionsQuery); if (!this.extensionsWorkbenchService.local.some(e => !e.isBuiltin)) { // This is part of popular extensions view. Collapse if no installed extensions. this.setExpanded(model.length > 0); } return model; } } export class RecommendedExtensionsView extends ExtensionsListView { private readonly recommendedExtensionsQuery = '@recommended'; override renderBody(container: HTMLElement): void { super.renderBody(container); this._register(this.extensionRecommendationsService.onDidChangeRecommendations(() => { this.show(''); })); } async override show(query: string): Promise<IPagedModel<IExtension>> { return (query && query.trim() !== this.recommendedExtensionsQuery) ? this.showEmptyModel() : super.show(this.recommendedExtensionsQuery); } } export class WorkspaceRecommendedExtensionsView extends ExtensionsListView implements IWorkspaceRecommendedExtensionsView { private readonly recommendedExtensionsQuery = '@recommended:workspace'; override renderBody(container: HTMLElement): void { super.renderBody(container); this._register(this.extensionRecommendationsService.onDidChangeRecommendations(() => this.show(this.recommendedExtensionsQuery))); this._register(this.contextService.onDidChangeWorkbenchState(() => this.show(this.recommendedExtensionsQuery))); } async override show(query: string): Promise<IPagedModel<IExtension>> { let shouldShowEmptyView = query && query.trim() !== '@recommended' && query.trim() !== '@recommended:workspace'; let model = await (shouldShowEmptyView ? this.showEmptyModel() : super.show(this.recommendedExtensionsQuery)); this.setExpanded(model.length > 0); return model; } private async getInstallableWorkspaceRecommendations() { const installed = (await this.extensionsWorkbenchService.queryLocal()) .filter(l => l.enablementState !== EnablementState.DisabledByExtensionKind); // Filter extensions disabled by kind const recommendations = (await this.getWorkspaceRecommendations()) .filter(extensionId => installed.every(local => !areSameExtensions({ id: extensionId }, local.identifier))); return this.getInstallableRecommendations(recommendations, { source: 'install-all-workspace-recommendations' }, CancellationToken.None); } async installWorkspaceRecommendations(): Promise<void> { const installableRecommendations = await this.getInstallableWorkspaceRecommendations(); if (installableRecommendations.length) { await this.extensionManagementService.installExtensions(installableRecommendations.map(i => i.gallery!)); } else { this.notificationService.notify({ severity: Severity.Info, message: localize('no local extensions', "There are no extensions to install.") }); } } }
src/vs/workbench/contrib/extensions/browser/extensionsViews.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00028734729858115315, 0.00017219354049302638, 0.00016257123206742108, 0.00017118608229793608, 0.000011572075891308486 ]
{ "id": 3, "code_window": [ "\t$acceptEditorPropertiesChanged(id: string, data: INotebookEditorPropertiesChangeData): void;\n", "\t$acceptEditorViewColumns(data: INotebookEditorViewColumnInfo): void;\n", "}\n", "\n", "export interface ExtHostNotebookKernelsShape {\n", "\t$acceptSelection(handle: number, value: boolean): void;\n", "\t$executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void;\n", "\t$cancelCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void;\n", "}\n", "\n", "export interface ExtHostStorageShape {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t$acceptSelection(handle: number, uri: UriComponents, value: boolean): void;\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .token-inspect-widget { z-index: 50; user-select: text; -webkit-user-select: text; padding: 10px; } .tiw-token { font-family: var(--monaco-monospace-font); } .tiw-metadata-separator { height: 1px; border: 0; } .tiw-token-length { font-weight: normal; font-size: 60%; float: right; } .tiw-metadata-table { width: 100%; } .tiw-metadata-value { font-family: var(--monaco-monospace-font); word-break: break-word; } .tiw-metadata-values { list-style: none; max-height: 300px; overflow-y: auto; margin-right: -10px; padding-left: 0; } .tiw-metadata-values > .tiw-metadata-value { margin-right: 10px; } .tiw-metadata-key { width: 1px; min-width: 150px; padding-right: 10px; white-space: nowrap; vertical-align: top; } .tiw-metadata-semantic { font-style: italic; } .tiw-metadata-scopes { line-height: normal; } .tiw-theme-selector { font-family: var(--monaco-monospace-font); }
src/vs/workbench/contrib/codeEditor/browser/inspectEditorTokens/inspectEditorTokens.css
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017477732035331428, 0.00017144721641670913, 0.00016639759996905923, 0.00017210027726832777, 0.0000029800532956869574 ]
{ "id": 4, "code_window": [ "import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths';\n", "import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters';\n", "import * as extHostTypes from 'vs/workbench/api/common/extHostTypes';\n", "import { asWebviewUri, WebviewInitData } from 'vs/workbench/api/common/shared/webview';\n", "import { CellEditType, CellStatusbarAlignment, CellUri, ICellRange, INotebookCellStatusBarEntry, INotebookExclusiveDocumentFilter, NotebookCellMetadata, NotebookCellExecutionState, NotebookCellsChangedEventDto, NotebookCellsChangeType, NotebookDataDto, NullablePartialNotebookCellMetadata, IImmediateCellEditOperation } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n", "import * as vscode from 'vscode';\n", "import { ResourceMap } from 'vs/base/common/map';\n", "import { ExtHostCell, ExtHostNotebookDocument } from './extHostNotebookDocument';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { CellEditType, CellStatusbarAlignment, CellUri, ICellRange, INotebookCellStatusBarEntry, INotebookExclusiveDocumentFilter, NotebookCellExecutionState, NotebookCellsChangedEventDto, NotebookCellsChangeType, NotebookDataDto, NullablePartialNotebookCellMetadata, IImmediateCellEditOperation } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebook.ts", "type": "replace", "edit_start_line_idx": 19 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter } from 'vs/base/common/event'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { ExtHostNotebookKernelsShape, IMainContext, INotebookKernelDto2, MainContext, MainThreadNotebookKernelsShape } from 'vs/workbench/api/common/extHost.protocol'; import * as vscode from 'vscode'; import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { URI, UriComponents } from 'vs/base/common/uri'; import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { NotebookCellRange } from 'vs/workbench/api/common/extHostTypeConverters'; import { isNonEmptyArray } from 'vs/base/common/arrays'; type ExecuteHandler = (executions: vscode.NotebookCellExecutionTask[]) => void; type InterruptHandler = (notebook: vscode.NotebookDocument) => void; export class ExtHostNotebookKernels implements ExtHostNotebookKernelsShape { private readonly _proxy: MainThreadNotebookKernelsShape; private readonly _kernelData = new Map<number, { id: string, executeHandler: ExecuteHandler, interruptHandler?: InterruptHandler, selected: boolean, onDidChangeSelection: Emitter<boolean> }>(); private _handlePool: number = 0; constructor( mainContext: IMainContext, private readonly _extHostNotebook: ExtHostNotebookController ) { this._proxy = mainContext.getProxy(MainContext.MainThreadNotebookKernels); } createKernel(extension: IExtensionDescription, options: vscode.NotebookKernelOptions): vscode.NotebookKernel2 { const handle = this._handlePool++; const that = this; let isDisposed = false; const commandDisposables = new DisposableStore(); const emitter = new Emitter<boolean>(); this._kernelData.set(handle, { id: options.id, executeHandler: options.executeHandler, selected: false, onDidChangeSelection: emitter }); const data: INotebookKernelDto2 = { id: options.id, selector: options.selector, extensionId: extension.identifier, extensionLocation: extension.extensionLocation, label: options.label, supportedLanguages: isNonEmptyArray(options.supportedLanguages) ? options.supportedLanguages : ['plaintext'], supportsInterrupt: Boolean(options.interruptHandler), hasExecutionOrder: options.hasExecutionOrder, }; this._proxy.$addKernel(handle, data); // update: all setters write directly into the dto object // and trigger an update. the actual update will only happen // once per event loop execution let tokenPool = 0; const _update = () => { if (isDisposed) { return; } const myToken = ++tokenPool; Promise.resolve().then(() => { if (myToken === tokenPool) { this._proxy.$updateKernel(handle, data); } }); }; return { get id() { return data.id; }, get selector() { return data.selector; }, // get selected() { return that._kernelData.get(handle)?.selected ?? false; }, // onDidChangeSelection: emitter.event, get label() { return data.label; }, set label(value) { data.label = value; _update(); }, get description() { return data.description ?? ''; }, set description(value) { data.description = value; _update(); }, get supportedLanguages() { return data.supportedLanguages; }, set supportedLanguages(value) { data.supportedLanguages = isNonEmptyArray(value) ? value : ['plaintext']; _update(); }, get hasExecutionOrder() { return data.hasExecutionOrder ?? false; }, set hasExecutionOrder(value) { data.hasExecutionOrder = value; _update(); }, get executeHandler() { return that._kernelData.get(handle)!.executeHandler; }, get interruptHandler() { return that._kernelData.get(handle)!.interruptHandler; }, set interruptHandler(value) { that._kernelData.get(handle)!.interruptHandler = value; data.supportsInterrupt = Boolean(value); _update(); }, createNotebookCellExecutionTask(cell) { //todo@jrieken return that._extHostNotebook.createNotebookCellExecution(cell.document.uri, cell.index, data.id)!; }, dispose: () => { isDisposed = true; this._kernelData.delete(handle); commandDisposables.dispose(); emitter.dispose(); this._proxy.$removeKernel(handle); } }; } $acceptSelection(handle: number, value: boolean): void { const obj = this._kernelData.get(handle); if (obj) { obj.selected = value; obj.onDidChangeSelection.fire(value); } } $executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void { const obj = this._kernelData.get(handle); if (!obj) { // extension can dispose kernels in the meantime return; } const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri)); if (!document) { throw new Error('MISSING notebook'); } const execs: vscode.NotebookCellExecutionTask[] = []; for (let range of ranges) { const cells = document.notebookDocument.getCells(NotebookCellRange.to(range)); for (let cell of cells) { const exec = this._extHostNotebook.createNotebookCellExecution(document.uri, cell.index, obj.id); if (exec) { execs.push(exec); } else { // todo@jrieken there should always be an exec-object console.warn('could NOT create notebook cell execution task for: ' + cell.document.uri); } } } try { obj.executeHandler(execs); } catch (err) { // console.error(err); } } $cancelCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void { const obj = this._kernelData.get(handle); if (!obj) { // extension can dispose kernels in the meantime return; } const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri)); if (!document) { throw new Error('MISSING notebook'); } if (obj.interruptHandler) { obj.interruptHandler(document.notebookDocument); } } }
src/vs/workbench/api/common/extHostNotebookKernels.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.018161186948418617, 0.0011468781158328056, 0.00016689750191289932, 0.00017243289039470255, 0.004011085256934166 ]
{ "id": 4, "code_window": [ "import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths';\n", "import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters';\n", "import * as extHostTypes from 'vs/workbench/api/common/extHostTypes';\n", "import { asWebviewUri, WebviewInitData } from 'vs/workbench/api/common/shared/webview';\n", "import { CellEditType, CellStatusbarAlignment, CellUri, ICellRange, INotebookCellStatusBarEntry, INotebookExclusiveDocumentFilter, NotebookCellMetadata, NotebookCellExecutionState, NotebookCellsChangedEventDto, NotebookCellsChangeType, NotebookDataDto, NullablePartialNotebookCellMetadata, IImmediateCellEditOperation } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n", "import * as vscode from 'vscode';\n", "import { ResourceMap } from 'vs/base/common/map';\n", "import { ExtHostCell, ExtHostNotebookDocument } from './extHostNotebookDocument';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { CellEditType, CellStatusbarAlignment, CellUri, ICellRange, INotebookCellStatusBarEntry, INotebookExclusiveDocumentFilter, NotebookCellExecutionState, NotebookCellsChangedEventDto, NotebookCellsChangeType, NotebookDataDto, NullablePartialNotebookCellMetadata, IImmediateCellEditOperation } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebook.ts", "type": "replace", "edit_start_line_idx": 19 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { BaseTextEditorModel } from 'vs/workbench/common/editor/textEditorModel'; import { URI } from 'vs/base/common/uri'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IModelService } from 'vs/editor/common/services/modelService'; /** * An editor model for in-memory, readonly content that is backed by an existing editor model. */ export class ResourceEditorModel extends BaseTextEditorModel { constructor( resource: URI, @IModeService modeService: IModeService, @IModelService modelService: IModelService ) { super(modelService, modeService, resource); } override dispose(): void { // force this class to dispose the underlying model if (this.textEditorModelHandle) { this.modelService.destroyModel(this.textEditorModelHandle); } super.dispose(); } }
src/vs/workbench/common/editor/resourceEditorModel.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017134673544205725, 0.00016966905968729407, 0.0001675100502325222, 0.00016990973381325603, 0.0000016915083733692882 ]
{ "id": 4, "code_window": [ "import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths';\n", "import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters';\n", "import * as extHostTypes from 'vs/workbench/api/common/extHostTypes';\n", "import { asWebviewUri, WebviewInitData } from 'vs/workbench/api/common/shared/webview';\n", "import { CellEditType, CellStatusbarAlignment, CellUri, ICellRange, INotebookCellStatusBarEntry, INotebookExclusiveDocumentFilter, NotebookCellMetadata, NotebookCellExecutionState, NotebookCellsChangedEventDto, NotebookCellsChangeType, NotebookDataDto, NullablePartialNotebookCellMetadata, IImmediateCellEditOperation } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n", "import * as vscode from 'vscode';\n", "import { ResourceMap } from 'vs/base/common/map';\n", "import { ExtHostCell, ExtHostNotebookDocument } from './extHostNotebookDocument';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { CellEditType, CellStatusbarAlignment, CellUri, ICellRange, INotebookCellStatusBarEntry, INotebookExclusiveDocumentFilter, NotebookCellExecutionState, NotebookCellsChangedEventDto, NotebookCellsChangeType, NotebookDataDto, NullablePartialNotebookCellMetadata, IImmediateCellEditOperation } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebook.ts", "type": "replace", "edit_start_line_idx": 19 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'vs/base/common/path'; import * as fs from 'fs'; import * as pfs from 'vs/base/node/pfs'; import * as cp from 'child_process'; import * as nls from 'vs/nls'; import * as process from 'vs/base/common/process'; import * as Types from 'vs/base/common/types'; import { IStringDictionary } from 'vs/base/common/collections'; import * as Objects from 'vs/base/common/objects'; import * as extpath from 'vs/base/common/extpath'; import * as Platform from 'vs/base/common/platform'; import { LineDecoder } from 'vs/base/node/decoder'; import { CommandOptions, ForkOptions, SuccessData, Source, TerminateResponse, TerminateResponseCode, Executable } from 'vs/base/common/processes'; import { FileAccess } from 'vs/base/common/network'; export { CommandOptions, ForkOptions, SuccessData, Source, TerminateResponse, TerminateResponseCode }; export type ValueCallback<T> = (value: T | Promise<T>) => void; export type ErrorCallback = (error?: any) => void; export type ProgressCallback<T> = (progress: T) => void; export interface LineData { line: string; source: Source; } function getWindowsCode(status: number): TerminateResponseCode { switch (status) { case 0: return TerminateResponseCode.Success; case 1: return TerminateResponseCode.AccessDenied; case 128: return TerminateResponseCode.ProcessNotFound; default: return TerminateResponseCode.Unknown; } } function terminateProcess(process: cp.ChildProcess, cwd?: string): Promise<TerminateResponse> { if (Platform.isWindows) { try { const options: any = { stdio: ['pipe', 'pipe', 'ignore'] }; if (cwd) { options.cwd = cwd; } const killProcess = cp.execFile('taskkill', ['/T', '/F', '/PID', process.pid.toString()], options); return new Promise(resolve => { killProcess.once('error', (err) => { resolve({ success: false, error: err }); }); killProcess.once('exit', (code, signal) => { if (code === 0) { resolve({ success: true }); } else { resolve({ success: false, code: code !== null ? code : TerminateResponseCode.Unknown }); } }); }); } catch (err) { return Promise.resolve({ success: false, error: err, code: err.status ? getWindowsCode(err.status) : TerminateResponseCode.Unknown }); } } else if (Platform.isLinux || Platform.isMacintosh) { try { const cmd = FileAccess.asFileUri('vs/base/node/terminateProcess.sh', require).fsPath; return new Promise(resolve => { cp.execFile(cmd, [process.pid.toString()], { encoding: 'utf8', shell: true } as cp.ExecFileOptions, (err, stdout, stderr) => { if (err) { resolve({ success: false, error: err }); } else { resolve({ success: true }); } }); }); } catch (err) { return Promise.resolve({ success: false, error: err }); } } else { process.kill('SIGKILL'); } return Promise.resolve({ success: true }); } export function getWindowsShell(env = process.env as Platform.IProcessEnvironment): string { return env['comspec'] || 'cmd.exe'; } export abstract class AbstractProcess<TProgressData> { private cmd: string; private args: string[]; private options: CommandOptions | ForkOptions; protected shell: boolean; private childProcess: cp.ChildProcess | null; protected childProcessPromise: Promise<cp.ChildProcess> | null; private pidResolve: ValueCallback<number> | undefined; protected terminateRequested: boolean; private static WellKnowCommands: IStringDictionary<boolean> = { 'ant': true, 'cmake': true, 'eslint': true, 'gradle': true, 'grunt': true, 'gulp': true, 'jake': true, 'jenkins': true, 'jshint': true, 'make': true, 'maven': true, 'msbuild': true, 'msc': true, 'nmake': true, 'npm': true, 'rake': true, 'tsc': true, 'xbuild': true }; public constructor(executable: Executable); public constructor(cmd: string, args: string[] | undefined, shell: boolean, options: CommandOptions | undefined); public constructor(arg1: string | Executable, arg2?: string[], arg3?: boolean, arg4?: CommandOptions) { if (arg2 !== undefined && arg3 !== undefined && arg4 !== undefined) { this.cmd = <string>arg1; this.args = arg2; this.shell = arg3; this.options = arg4; } else { const executable = <Executable>arg1; this.cmd = executable.command; this.shell = executable.isShellCommand; this.args = executable.args.slice(0); this.options = executable.options || {}; } this.childProcess = null; this.childProcessPromise = null; this.terminateRequested = false; if (this.options.env) { const newEnv: IStringDictionary<string> = Object.create(null); Object.keys(process.env).forEach((key) => { newEnv[key] = process.env[key]!; }); Object.keys(this.options.env).forEach((key) => { newEnv[key] = this.options.env![key]!; }); this.options.env = newEnv; } } public getSanitizedCommand(): string { let result = this.cmd.toLowerCase(); const index = result.lastIndexOf(path.sep); if (index !== -1) { result = result.substring(index + 1); } if (AbstractProcess.WellKnowCommands[result]) { return result; } return 'other'; } public start(pp: ProgressCallback<TProgressData>): Promise<SuccessData> { if (Platform.isWindows && ((this.options && this.options.cwd && extpath.isUNC(this.options.cwd)) || !this.options && extpath.isUNC(process.cwd()))) { return Promise.reject(new Error(nls.localize('TaskRunner.UNC', 'Can\'t execute a shell command on a UNC drive.'))); } return this.useExec().then((useExec) => { let cc: ValueCallback<SuccessData>; let ee: ErrorCallback; const result = new Promise<any>((c, e) => { cc = c; ee = e; }); if (useExec) { let cmd: string = this.cmd; if (this.args) { cmd = cmd + ' ' + this.args.join(' '); } this.childProcess = cp.exec(cmd, this.options, (error, stdout, stderr) => { this.childProcess = null; const err: any = error; // This is tricky since executing a command shell reports error back in case the executed command return an // error or the command didn't exist at all. So we can't blindly treat an error as a failed command. So we // always parse the output and report success unless the job got killed. if (err && err.killed) { ee({ killed: this.terminateRequested, stdout: stdout.toString(), stderr: stderr.toString() }); } else { this.handleExec(cc, pp, error, stdout as any, stderr as any); } }); } else { let childProcess: cp.ChildProcess | null = null; const closeHandler = (data: any) => { this.childProcess = null; this.childProcessPromise = null; this.handleClose(data, cc, pp, ee); const result: SuccessData = { terminated: this.terminateRequested }; if (Types.isNumber(data)) { result.cmdCode = <number>data; } cc(result); }; if (this.shell && Platform.isWindows) { const options: any = Objects.deepClone(this.options); options.windowsVerbatimArguments = true; options.detached = false; let quotedCommand: boolean = false; let quotedArg: boolean = false; const commandLine: string[] = []; let quoted = this.ensureQuotes(this.cmd); commandLine.push(quoted.value); quotedCommand = quoted.quoted; if (this.args) { this.args.forEach((elem) => { quoted = this.ensureQuotes(elem); commandLine.push(quoted.value); quotedArg = quotedArg && quoted.quoted; }); } const args: string[] = [ '/s', '/c', ]; if (quotedCommand) { if (quotedArg) { args.push('"' + commandLine.join(' ') + '"'); } else if (commandLine.length > 1) { args.push('"' + commandLine[0] + '"' + ' ' + commandLine.slice(1).join(' ')); } else { args.push('"' + commandLine[0] + '"'); } } else { args.push(commandLine.join(' ')); } childProcess = cp.spawn(getWindowsShell(), args, options); } else { if (this.cmd) { childProcess = cp.spawn(this.cmd, this.args, this.options); } } if (childProcess) { this.childProcess = childProcess; this.childProcessPromise = Promise.resolve(childProcess); if (this.pidResolve) { this.pidResolve(Types.isNumber(childProcess.pid) ? childProcess.pid : -1); this.pidResolve = undefined; } childProcess.on('error', (error: Error) => { this.childProcess = null; ee({ terminated: this.terminateRequested, error: error }); }); if (childProcess.pid) { this.childProcess.on('close', closeHandler); this.handleSpawn(childProcess, cc!, pp, ee!, true); } } } return result; }); } protected abstract handleExec(cc: ValueCallback<SuccessData>, pp: ProgressCallback<TProgressData>, error: Error | null, stdout: Buffer, stderr: Buffer): void; protected abstract handleSpawn(childProcess: cp.ChildProcess, cc: ValueCallback<SuccessData>, pp: ProgressCallback<TProgressData>, ee: ErrorCallback, sync: boolean): void; protected handleClose(data: any, cc: ValueCallback<SuccessData>, pp: ProgressCallback<TProgressData>, ee: ErrorCallback): void { // Default is to do nothing. } private static readonly regexp = /^[^"].* .*[^"]/; private ensureQuotes(value: string) { if (AbstractProcess.regexp.test(value)) { return { value: '"' + value + '"', //`"${value}"`, quoted: true }; } else { return { value: value, quoted: value.length > 0 && value[0] === '"' && value[value.length - 1] === '"' }; } } public get pid(): Promise<number> { if (this.childProcessPromise) { return this.childProcessPromise.then(childProcess => childProcess.pid, err => -1); } else { return new Promise<number>((resolve) => { this.pidResolve = resolve; }); } } public terminate(): Promise<TerminateResponse> { if (!this.childProcessPromise) { return Promise.resolve<TerminateResponse>({ success: true }); } return this.childProcessPromise.then((childProcess) => { this.terminateRequested = true; return terminateProcess(childProcess, this.options.cwd).then(response => { if (response.success) { this.childProcess = null; } return response; }); }, (err) => { return { success: true }; }); } private useExec(): Promise<boolean> { return new Promise<boolean>(resolve => { if (!this.shell || !Platform.isWindows) { return resolve(false); } const cmdShell = cp.spawn(getWindowsShell(), ['/s', '/c']); cmdShell.on('error', (error: Error) => { return resolve(true); }); cmdShell.on('exit', (data: any) => { return resolve(false); }); }); } } export class LineProcess extends AbstractProcess<LineData> { private stdoutLineDecoder: LineDecoder | null; private stderrLineDecoder: LineDecoder | null; public constructor(executable: Executable); public constructor(cmd: string, args: string[], shell: boolean, options: CommandOptions); public constructor(arg1: string | Executable, arg2?: string[], arg3?: boolean | ForkOptions, arg4?: CommandOptions) { super(<any>arg1, arg2, <any>arg3, arg4); this.stdoutLineDecoder = null; this.stderrLineDecoder = null; } protected handleExec(cc: ValueCallback<SuccessData>, pp: ProgressCallback<LineData>, error: Error, stdout: Buffer, stderr: Buffer) { [stdout, stderr].forEach((buffer: Buffer, index: number) => { const lineDecoder = new LineDecoder(); const lines = lineDecoder.write(buffer); lines.forEach((line) => { pp({ line: line, source: index === 0 ? Source.stdout : Source.stderr }); }); const line = lineDecoder.end(); if (line) { pp({ line: line, source: index === 0 ? Source.stdout : Source.stderr }); } }); cc({ terminated: this.terminateRequested, error: error }); } protected handleSpawn(childProcess: cp.ChildProcess, cc: ValueCallback<SuccessData>, pp: ProgressCallback<LineData>, ee: ErrorCallback, sync: boolean): void { const stdoutLineDecoder = new LineDecoder(); const stderrLineDecoder = new LineDecoder(); childProcess.stdout!.on('data', (data: Buffer) => { const lines = stdoutLineDecoder.write(data); lines.forEach(line => pp({ line: line, source: Source.stdout })); }); childProcess.stderr!.on('data', (data: Buffer) => { const lines = stderrLineDecoder.write(data); lines.forEach(line => pp({ line: line, source: Source.stderr })); }); this.stdoutLineDecoder = stdoutLineDecoder; this.stderrLineDecoder = stderrLineDecoder; } protected override handleClose(data: any, cc: ValueCallback<SuccessData>, pp: ProgressCallback<LineData>, ee: ErrorCallback): void { const stdoutLine = this.stdoutLineDecoder ? this.stdoutLineDecoder.end() : null; if (stdoutLine) { pp({ line: stdoutLine, source: Source.stdout }); } const stderrLine = this.stderrLineDecoder ? this.stderrLineDecoder.end() : null; if (stderrLine) { pp({ line: stderrLine, source: Source.stderr }); } } } export interface IQueuedSender { send: (msg: any) => void; } // Wrapper around process.send() that will queue any messages if the internal node.js // queue is filled with messages and only continue sending messages when the internal // queue is free again to consume messages. // On Windows we always wait for the send() method to return before sending the next message // to workaround https://github.com/nodejs/node/issues/7657 (IPC can freeze process) export function createQueuedSender(childProcess: cp.ChildProcess): IQueuedSender { let msgQueue: string[] = []; let useQueue = false; const send = function (msg: any): void { if (useQueue) { msgQueue.push(msg); // add to the queue if the process cannot handle more messages return; } const result = childProcess.send(msg, (error: Error | null) => { if (error) { console.error(error); // unlikely to happen, best we can do is log this error } useQueue = false; // we are good again to send directly without queue // now send all the messages that we have in our queue and did not send yet if (msgQueue.length > 0) { const msgQueueCopy = msgQueue.slice(0); msgQueue = []; msgQueueCopy.forEach(entry => send(entry)); } }); if (!result || Platform.isWindows /* workaround https://github.com/nodejs/node/issues/7657 */) { useQueue = true; } }; return { send }; } export namespace win32 { export async function findExecutable(command: string, cwd?: string, paths?: string[]): Promise<string> { // If we have an absolute path then we take it. if (path.isAbsolute(command)) { return command; } if (cwd === undefined) { cwd = process.cwd(); } const dir = path.dirname(command); if (dir !== '.') { // We have a directory and the directory is relative (see above). Make the path absolute // to the current working directory. return path.join(cwd, command); } if (paths === undefined && Types.isString(process.env['PATH'])) { paths = process.env['PATH'].split(path.delimiter); } // No PATH environment. Make path absolute to the cwd. if (paths === undefined || paths.length === 0) { return path.join(cwd, command); } async function fileExists(path: string): Promise<boolean> { if (await pfs.exists(path)) { return !((await fs.promises.stat(path)).isDirectory()); } return false; } // We have a simple file name. We get the path variable from the env // and try to find the executable on the path. for (let pathEntry of paths) { // The path entry is absolute. let fullPath: string; if (path.isAbsolute(pathEntry)) { fullPath = path.join(pathEntry, command); } else { fullPath = path.join(cwd, pathEntry, command); } if (await fileExists(fullPath)) { return fullPath; } let withExtension = fullPath + '.com'; if (await fileExists(withExtension)) { return withExtension; } withExtension = fullPath + '.exe'; if (await fileExists(withExtension)) { return withExtension; } } return path.join(cwd, command); } }
src/vs/base/node/processes.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00027859213878400624, 0.00017452485917601734, 0.0001659245026530698, 0.00017279086750932038, 0.000015281852029147558 ]
{ "id": 4, "code_window": [ "import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths';\n", "import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters';\n", "import * as extHostTypes from 'vs/workbench/api/common/extHostTypes';\n", "import { asWebviewUri, WebviewInitData } from 'vs/workbench/api/common/shared/webview';\n", "import { CellEditType, CellStatusbarAlignment, CellUri, ICellRange, INotebookCellStatusBarEntry, INotebookExclusiveDocumentFilter, NotebookCellMetadata, NotebookCellExecutionState, NotebookCellsChangedEventDto, NotebookCellsChangeType, NotebookDataDto, NullablePartialNotebookCellMetadata, IImmediateCellEditOperation } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n", "import * as vscode from 'vscode';\n", "import { ResourceMap } from 'vs/base/common/map';\n", "import { ExtHostCell, ExtHostNotebookDocument } from './extHostNotebookDocument';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { CellEditType, CellStatusbarAlignment, CellUri, ICellRange, INotebookCellStatusBarEntry, INotebookExclusiveDocumentFilter, NotebookCellExecutionState, NotebookCellsChangedEventDto, NotebookCellsChangeType, NotebookDataDto, NullablePartialNotebookCellMetadata, IImmediateCellEditOperation } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebook.ts", "type": "replace", "edit_start_line_idx": 19 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/titlebarpart'; import { localize } from 'vs/nls'; import { dirname, basename } from 'vs/base/common/resources'; import { Part } from 'vs/workbench/browser/part'; import { ITitleService, ITitleProperties } from 'vs/workbench/services/title/common/titleService'; import { getZoomFactor } from 'vs/base/browser/browser'; import { MenuBarVisibility, getTitleBarStyle, getMenuBarVisibility } from 'vs/platform/windows/common/windows'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { IAction } from 'vs/base/common/actions'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { DisposableStore, dispose } from 'vs/base/common/lifecycle'; import { EditorResourceAccessor, Verbosity, SideBySideEditor } from 'vs/workbench/common/editor'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { TITLE_BAR_ACTIVE_BACKGROUND, TITLE_BAR_ACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_BACKGROUND, TITLE_BAR_BORDER, WORKBENCH_BACKGROUND } from 'vs/workbench/common/theme'; import { isMacintosh, isWindows, isLinux, isWeb } from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import { Color } from 'vs/base/common/color'; import { trim } from 'vs/base/common/strings'; import { EventType, EventHelper, Dimension, isAncestor, append, $, addDisposableListener, runAtThisOrScheduleAtNextAnimationFrame, prepend } from 'vs/base/browser/dom'; import { CustomMenubarControl } from 'vs/workbench/browser/parts/titlebar/menubarControl'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { template } from 'vs/base/common/labels'; import { ILabelService } from 'vs/platform/label/common/label'; import { Emitter } from 'vs/base/common/event'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { Parts, IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { RunOnceScheduler } from 'vs/base/common/async'; import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, IMenu, MenuId } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { IProductService } from 'vs/platform/product/common/productService'; import { Schemas } from 'vs/base/common/network'; import { withNullAsUndefined } from 'vs/base/common/types'; import { Codicon, iconRegistry } from 'vs/base/common/codicons'; export class TitlebarPart extends Part implements ITitleService { private static readonly NLS_UNSUPPORTED = localize('patchedWindowTitle', "[Unsupported]"); private static readonly NLS_USER_IS_ADMIN = isWindows ? localize('userIsAdmin', "[Administrator]") : localize('userIsSudo', "[Superuser]"); private static readonly NLS_EXTENSION_HOST = localize('devExtensionWindowTitlePrefix', "[Extension Development Host]"); private static readonly TITLE_DIRTY = '\u25cf '; //#region IView readonly minimumWidth: number = 0; readonly maximumWidth: number = Number.POSITIVE_INFINITY; get minimumHeight(): number { return 30 / (this.currentMenubarVisibility === 'hidden' ? getZoomFactor() : 1); } get maximumHeight(): number { return this.minimumHeight; } //#endregion private _onMenubarVisibilityChange = this._register(new Emitter<boolean>()); readonly onMenubarVisibilityChange = this._onMenubarVisibilityChange.event; declare readonly _serviceBrand: undefined; protected title!: HTMLElement; protected customMenubar: CustomMenubarControl | undefined; protected appIcon: HTMLElement | undefined; private appIconBadge: HTMLElement | undefined; protected menubar?: HTMLElement; protected lastLayoutDimensions: Dimension | undefined; private titleBarStyle: 'native' | 'custom'; private pendingTitle: string | undefined; private isInactive: boolean = false; private readonly properties: ITitleProperties = { isPure: true, isAdmin: false, prefix: undefined }; private readonly activeEditorListeners = this._register(new DisposableStore()); private readonly titleUpdater = this._register(new RunOnceScheduler(() => this.doUpdateTitle(), 0)); private contextMenu: IMenu; constructor( @IContextMenuService private readonly contextMenuService: IContextMenuService, @IConfigurationService protected readonly configurationService: IConfigurationService, @IEditorService private readonly editorService: IEditorService, @IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IInstantiationService protected readonly instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILabelService private readonly labelService: ILabelService, @IStorageService storageService: IStorageService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @IMenuService menuService: IMenuService, @IContextKeyService contextKeyService: IContextKeyService, @IHostService private readonly hostService: IHostService, @IProductService private readonly productService: IProductService, ) { super(Parts.TITLEBAR_PART, { hasTitle: false }, themeService, storageService, layoutService); this.contextMenu = this._register(menuService.createMenu(MenuId.TitleBarContext, contextKeyService)); this.titleBarStyle = getTitleBarStyle(this.configurationService); this.registerListeners(); } private registerListeners(): void { this._register(this.hostService.onDidChangeFocus(focused => focused ? this.onFocus() : this.onBlur())); this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChanged(e))); this._register(this.editorService.onDidActiveEditorChange(() => this.onActiveEditorChange())); this._register(this.contextService.onDidChangeWorkspaceFolders(() => this.titleUpdater.schedule())); this._register(this.contextService.onDidChangeWorkbenchState(() => this.titleUpdater.schedule())); this._register(this.contextService.onDidChangeWorkspaceName(() => this.titleUpdater.schedule())); this._register(this.labelService.onDidChangeFormatters(() => this.titleUpdater.schedule())); } private onBlur(): void { this.isInactive = true; this.updateStyles(); } private onFocus(): void { this.isInactive = false; this.updateStyles(); } protected onConfigurationChanged(event: IConfigurationChangeEvent): void { if (event.affectsConfiguration('window.title') || event.affectsConfiguration('window.titleSeparator')) { this.titleUpdater.schedule(); } if (this.titleBarStyle !== 'native' && (!isMacintosh || isWeb)) { if (event.affectsConfiguration('window.menuBarVisibility')) { if (this.currentMenubarVisibility === 'compact') { this.uninstallMenubar(); } else { this.installMenubar(); } } } } protected onMenubarVisibilityChanged(visible: boolean): void { if (isWeb || isWindows || isLinux) { this.adjustTitleMarginToCenter(); this._onMenubarVisibilityChange.fire(visible); } } private onActiveEditorChange(): void { // Dispose old listeners this.activeEditorListeners.clear(); // Calculate New Window Title this.titleUpdater.schedule(); // Apply listener for dirty and label changes const activeEditor = this.editorService.activeEditor; if (activeEditor) { this.activeEditorListeners.add(activeEditor.onDidChangeDirty(() => this.titleUpdater.schedule())); this.activeEditorListeners.add(activeEditor.onDidChangeLabel(() => this.titleUpdater.schedule())); } } private doUpdateTitle(): void { const title = this.getWindowTitle(); // Always set the native window title to identify us properly to the OS let nativeTitle = title; if (!trim(nativeTitle)) { nativeTitle = this.productService.nameLong; } window.document.title = nativeTitle; // Apply custom title if we can if (this.title) { this.title.innerText = title; } else { this.pendingTitle = title; } if ((isWeb || isWindows || isLinux) && this.title) { if (this.lastLayoutDimensions) { this.updateLayout(this.lastLayoutDimensions); } } } private getWindowTitle(): string { let title = this.doGetWindowTitle(); if (this.properties.prefix) { title = `${this.properties.prefix} ${title || this.productService.nameLong}`; } if (this.properties.isAdmin) { title = `${title || this.productService.nameLong} ${TitlebarPart.NLS_USER_IS_ADMIN}`; } if (!this.properties.isPure) { title = `${title || this.productService.nameLong} ${TitlebarPart.NLS_UNSUPPORTED}`; } if (this.environmentService.isExtensionDevelopment) { title = `${TitlebarPart.NLS_EXTENSION_HOST} - ${title || this.productService.nameLong}`; } // Replace non-space whitespace title = title.replace(/[^\S ]/g, ' '); return title; } updateProperties(properties: ITitleProperties): void { const isAdmin = typeof properties.isAdmin === 'boolean' ? properties.isAdmin : this.properties.isAdmin; const isPure = typeof properties.isPure === 'boolean' ? properties.isPure : this.properties.isPure; const prefix = typeof properties.prefix === 'string' ? properties.prefix : this.properties.prefix; if (isAdmin !== this.properties.isAdmin || isPure !== this.properties.isPure || prefix !== this.properties.prefix) { this.properties.isAdmin = isAdmin; this.properties.isPure = isPure; this.properties.prefix = prefix; this.titleUpdater.schedule(); } } /** * Possible template values: * * {activeEditorLong}: e.g. /Users/Development/myFolder/myFileFolder/myFile.txt * {activeEditorMedium}: e.g. myFolder/myFileFolder/myFile.txt * {activeEditorShort}: e.g. myFile.txt * {activeFolderLong}: e.g. /Users/Development/myFolder/myFileFolder * {activeFolderMedium}: e.g. myFolder/myFileFolder * {activeFolderShort}: e.g. myFileFolder * {rootName}: e.g. myFolder1, myFolder2, myFolder3 * {rootPath}: e.g. /Users/Development * {folderName}: e.g. myFolder * {folderPath}: e.g. /Users/Development/myFolder * {appName}: e.g. VS Code * {remoteName}: e.g. SSH * {dirty}: indicator * {separator}: conditional separator */ private doGetWindowTitle(): string { const editor = this.editorService.activeEditor; const workspace = this.contextService.getWorkspace(); // Compute root let root: URI | undefined; if (workspace.configuration) { root = workspace.configuration; } else if (workspace.folders.length) { root = workspace.folders[0].uri; } // Compute active editor folder const editorResource = EditorResourceAccessor.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY }); let editorFolderResource = editorResource ? dirname(editorResource) : undefined; if (editorFolderResource?.path === '.') { editorFolderResource = undefined; } // Compute folder resource // Single Root Workspace: always the root single workspace in this case // Otherwise: root folder of the currently active file if any let folder: IWorkspaceFolder | undefined = undefined; if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) { folder = workspace.folders[0]; } else if (editorResource) { folder = withNullAsUndefined(this.contextService.getWorkspaceFolder(editorResource)); } // Variables const activeEditorShort = editor ? editor.getTitle(Verbosity.SHORT) : ''; const activeEditorMedium = editor ? editor.getTitle(Verbosity.MEDIUM) : activeEditorShort; const activeEditorLong = editor ? editor.getTitle(Verbosity.LONG) : activeEditorMedium; const activeFolderShort = editorFolderResource ? basename(editorFolderResource) : ''; const activeFolderMedium = editorFolderResource ? this.labelService.getUriLabel(editorFolderResource, { relative: true }) : ''; const activeFolderLong = editorFolderResource ? this.labelService.getUriLabel(editorFolderResource) : ''; const rootName = this.labelService.getWorkspaceLabel(workspace); const rootPath = root ? this.labelService.getUriLabel(root) : ''; const folderName = folder ? folder.name : ''; const folderPath = folder ? this.labelService.getUriLabel(folder.uri) : ''; const dirty = editor?.isDirty() && !editor.isSaving() ? TitlebarPart.TITLE_DIRTY : ''; const appName = this.productService.nameLong; const remoteName = this.labelService.getHostLabel(Schemas.vscodeRemote, this.environmentService.remoteAuthority); const separator = this.configurationService.getValue<string>('window.titleSeparator'); const titleTemplate = this.configurationService.getValue<string>('window.title'); return template(titleTemplate, { activeEditorShort, activeEditorLong, activeEditorMedium, activeFolderShort, activeFolderMedium, activeFolderLong, rootName, rootPath, folderName, folderPath, dirty, appName, remoteName, separator: { label: separator } }); } private uninstallMenubar(): void { if (this.customMenubar) { this.customMenubar.dispose(); this.customMenubar = undefined; } if (this.menubar) { this.menubar.remove(); this.menubar = undefined; } } protected installMenubar(): void { // If the menubar is already installed, skip if (this.menubar) { return; } this.customMenubar = this._register(this.instantiationService.createInstance(CustomMenubarControl)); this.menubar = this.element.insertBefore($('div.menubar'), this.title); this.menubar.setAttribute('role', 'menubar'); this.customMenubar.create(this.menubar); this._register(this.customMenubar.onVisibilityChange(e => this.onMenubarVisibilityChanged(e))); } override createContentArea(parent: HTMLElement): HTMLElement { this.element = parent; // App Icon (Native Windows/Linux and Web) if (!isMacintosh || isWeb) { this.appIcon = prepend(this.element, $('a.window-appicon')); // Web-only home indicator and menu if (isWeb) { const homeIndicator = this.environmentService.options?.homeIndicator; if (homeIndicator) { let codicon = iconRegistry.get(homeIndicator.icon); if (!codicon) { codicon = Codicon.code; } this.appIcon.setAttribute('href', homeIndicator.href); this.appIcon.classList.add(...codicon.classNamesArray); this.appIconBadge = document.createElement('div'); this.appIconBadge.classList.add('home-bar-icon-badge'); this.appIcon.appendChild(this.appIconBadge); } } } // Menubar: install a custom menu bar depending on configuration // and when not in activity bar if (this.titleBarStyle !== 'native' && (!isMacintosh || isWeb) && this.currentMenubarVisibility !== 'compact') { this.installMenubar(); } // Title this.title = append(this.element, $('div.window-title')); if (this.pendingTitle) { this.title.innerText = this.pendingTitle; } else { this.titleUpdater.schedule(); } // Context menu on title [EventType.CONTEXT_MENU, EventType.MOUSE_DOWN].forEach(event => { this._register(addDisposableListener(this.title, event, e => { if (e.type === EventType.CONTEXT_MENU || e.metaKey) { EventHelper.stop(e); this.onContextMenu(e); } })); }); // Since the title area is used to drag the window, we do not want to steal focus from the // currently active element. So we restore focus after a timeout back to where it was. this._register(addDisposableListener(this.element, EventType.MOUSE_DOWN, e => { if (e.target && this.menubar && isAncestor(e.target as HTMLElement, this.menubar)) { return; } const active = document.activeElement; setTimeout(() => { if (active instanceof HTMLElement) { active.focus(); } }, 0 /* need a timeout because we are in capture phase */); }, true /* use capture to know the currently active element properly */)); this.updateStyles(); return this.element; } override updateStyles(): void { super.updateStyles(); // Part container if (this.element) { if (this.isInactive) { this.element.classList.add('inactive'); } else { this.element.classList.remove('inactive'); } const titleBackground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_BACKGROUND : TITLE_BAR_ACTIVE_BACKGROUND, (color, theme) => { // LCD Rendering Support: the title bar part is a defining its own GPU layer. // To benefit from LCD font rendering, we must ensure that we always set an // opaque background color. As such, we compute an opaque color given we know // the background color is the workbench background. return color.isOpaque() ? color : color.makeOpaque(WORKBENCH_BACKGROUND(theme)); }) || ''; this.element.style.backgroundColor = titleBackground; if (this.appIconBadge) { this.appIconBadge.style.backgroundColor = titleBackground; } if (titleBackground && Color.fromHex(titleBackground).isLighter()) { this.element.classList.add('light'); } else { this.element.classList.remove('light'); } const titleForeground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_FOREGROUND : TITLE_BAR_ACTIVE_FOREGROUND); this.element.style.color = titleForeground || ''; const titleBorder = this.getColor(TITLE_BAR_BORDER); this.element.style.borderBottom = titleBorder ? `1px solid ${titleBorder}` : ''; } } private onContextMenu(e: MouseEvent): void { // Find target anchor const event = new StandardMouseEvent(e); const anchor = { x: event.posx, y: event.posy }; // Fill in contributed actions const actions: IAction[] = []; const actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, undefined, actions); // Show it this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => actions, onHide: () => dispose(actionsDisposable) }); } protected adjustTitleMarginToCenter(): void { if (this.customMenubar && this.menubar) { const leftMarker = (this.appIcon ? this.appIcon.clientWidth : 0) + this.menubar.clientWidth + 10; const rightMarker = this.element.clientWidth - 10; // Not enough space to center the titlebar within window, // Center between menu and window controls if (leftMarker > (this.element.clientWidth - this.title.clientWidth) / 2 || rightMarker < (this.element.clientWidth + this.title.clientWidth) / 2) { this.title.style.position = ''; this.title.style.left = ''; this.title.style.transform = ''; return; } } this.title.style.position = 'absolute'; this.title.style.left = '50%'; this.title.style.transform = 'translate(-50%, 0)'; } protected get currentMenubarVisibility(): MenuBarVisibility { return getMenuBarVisibility(this.configurationService); } updateLayout(dimension: Dimension): void { this.lastLayoutDimensions = dimension; if (getTitleBarStyle(this.configurationService) === 'custom') { // Only prevent zooming behavior on macOS or when the menubar is not visible if ((!isWeb && isMacintosh) || this.currentMenubarVisibility === 'hidden') { this.title.style.zoom = `${1 / getZoomFactor()}`; } else { this.title.style.zoom = ''; } runAtThisOrScheduleAtNextAnimationFrame(() => this.adjustTitleMarginToCenter()); if (this.customMenubar) { const menubarDimension = new Dimension(0, dimension.height); this.customMenubar.layout(menubarDimension); } } } override layout(width: number, height: number): void { this.updateLayout(new Dimension(width, height)); super.layoutContents(width, height); } toJSON(): object { return { type: Parts.TITLEBAR_PART }; } } registerThemingParticipant((theme, collector) => { const titlebarActiveFg = theme.getColor(TITLE_BAR_ACTIVE_FOREGROUND); if (titlebarActiveFg) { collector.addRule(` .monaco-workbench .part.titlebar > .window-controls-container .window-icon { color: ${titlebarActiveFg}; } `); } const titlebarInactiveFg = theme.getColor(TITLE_BAR_INACTIVE_FOREGROUND); if (titlebarInactiveFg) { collector.addRule(` .monaco-workbench .part.titlebar.inactive > .window-controls-container .window-icon { color: ${titlebarInactiveFg}; } `); } });
src/vs/workbench/browser/parts/titlebar/titlebarPart.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.000898788042832166, 0.00018400208500679582, 0.00016438346938230097, 0.00017114066577050835, 0.0000973151545622386 ]
{ "id": 5, "code_window": [ "\n", "\tregisterNotebookContentProvider(\n", "\t\textension: IExtensionDescription,\n", "\t\tviewType: string,\n", "\t\tprovider: vscode.NotebookContentProvider,\n", "\t\toptions?: {\n", "\t\t\ttransientOutputs: boolean;\n", "\t\t\ttransientMetadata: { [K in keyof NotebookCellMetadata]?: boolean };\n", "\t\t\tviewOptions?: {\n", "\t\t\t\tdisplayName: string;\n", "\t\t\t\tfilenamePattern: (vscode.GlobPattern | { include: vscode.GlobPattern; exclude: vscode.GlobPattern })[];\n", "\t\t\t\texclusive?: boolean;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\toptions?: vscode.NotebookDocumentContentOptions & {\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebook.ts", "type": "replace", "edit_start_line_idx": 326 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { flatten } from 'vs/base/common/arrays'; import { Emitter, Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers'; import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookKernel2, INotebookKernel2ChangeEvent, INotebookKernelService } from 'vs/workbench/contrib/notebook/common/notebookKernelService'; import { NotebookSelector } from 'vs/workbench/contrib/notebook/common/notebookSelector'; import { ExtHostContext, ExtHostNotebookKernelsShape, IExtHostContext, INotebookKernelDto2, MainContext, MainThreadNotebookKernelsShape } from '../common/extHost.protocol'; abstract class MainThreadKernel implements INotebookKernel2 { private readonly _onDidChange = new Emitter<INotebookKernel2ChangeEvent>(); private readonly preloads: { uri: URI, provides: string[] }[]; readonly onDidChange: Event<INotebookKernel2ChangeEvent> = this._onDidChange.event; readonly id: string; readonly selector: NotebookSelector; readonly extensionId: ExtensionIdentifier; implementsInterrupt: boolean; label: string; description?: string; detail?: string; isPreferred?: boolean; supportedLanguages: string[]; implementsExecutionOrder: boolean; localResourceRoot: URI; public get preloadUris() { return this.preloads.map(p => p.uri); } public get preloadProvides() { return flatten(this.preloads.map(p => p.provides)); } constructor(data: INotebookKernelDto2) { this.id = data.id; this.selector = data.selector; this.extensionId = data.extensionId; this.implementsInterrupt = data.supportsInterrupt ?? false; this.label = data.label; this.description = data.description; this.isPreferred = data.isPreferred; this.supportedLanguages = data.supportedLanguages; this.implementsExecutionOrder = data.hasExecutionOrder ?? false; this.localResourceRoot = URI.revive(data.extensionLocation); this.preloads = data.preloads?.map(u => ({ uri: URI.revive(u.uri), provides: u.provides })) ?? []; } update(data: Partial<INotebookKernelDto2>) { const event: INotebookKernel2ChangeEvent = Object.create(null); if (data.label !== undefined) { this.label = data.label; event.label = true; } if (data.description !== undefined) { this.description = data.description; event.description = true; } if (data.isPreferred !== undefined) { this.isPreferred = data.isPreferred; event.isPreferred = true; } if (data.supportedLanguages !== undefined) { this.supportedLanguages = data.supportedLanguages; event.supportedLanguages = true; } if (data.hasExecutionOrder !== undefined) { this.implementsExecutionOrder = data.hasExecutionOrder; event.hasExecutionOrder = true; } this._onDidChange.fire(event); } abstract setSelected(value: boolean): void; abstract executeCells(uri: URI, ranges: ICellRange[]): void; abstract cancelCells(uri: URI, ranges: ICellRange[]): void; } @extHostNamedCustomer(MainContext.MainThreadNotebookKernels) export class MainThreadNotebookKernels implements MainThreadNotebookKernelsShape { private readonly _kernels = new Map<number, [kernel: MainThreadKernel, registraion: IDisposable]>(); private readonly _proxy: ExtHostNotebookKernelsShape; constructor( extHostContext: IExtHostContext, @INotebookKernelService private readonly _notebookKernelService: INotebookKernelService, ) { this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostNotebookKernels); } dispose(): void { for (let [, registration] of this._kernels.values()) { registration.dispose(); } } $addKernel(handle: number, data: INotebookKernelDto2): void { const that = this; const kernel = new class extends MainThreadKernel { setSelected(value: boolean): void { that._proxy.$acceptSelection(handle, value); } executeCells(uri: URI, ranges: ICellRange[]): void { that._proxy.$executeCells(handle, uri, ranges); } cancelCells(uri: URI, ranges: ICellRange[]): void { that._proxy.$cancelCells(handle, uri, ranges); } }(data); const disposable = this._notebookKernelService.addKernel(kernel); this._kernels.set(handle, [kernel, disposable]); } $updateKernel(handle: number, data: Partial<INotebookKernelDto2>): void { const tuple = this._kernels.get(handle); if (tuple) { tuple[0].update(data); } } $removeKernel(handle: number): void { const tuple = this._kernels.get(handle); if (tuple) { tuple[1].dispose(); this._kernels.delete(handle); } } }
src/vs/workbench/api/browser/mainThreadNotebookKernels.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00043212922173552215, 0.00018819954129867256, 0.00016177562065422535, 0.00017230880621355027, 0.00006531873077619821 ]
{ "id": 5, "code_window": [ "\n", "\tregisterNotebookContentProvider(\n", "\t\textension: IExtensionDescription,\n", "\t\tviewType: string,\n", "\t\tprovider: vscode.NotebookContentProvider,\n", "\t\toptions?: {\n", "\t\t\ttransientOutputs: boolean;\n", "\t\t\ttransientMetadata: { [K in keyof NotebookCellMetadata]?: boolean };\n", "\t\t\tviewOptions?: {\n", "\t\t\t\tdisplayName: string;\n", "\t\t\t\tfilenamePattern: (vscode.GlobPattern | { include: vscode.GlobPattern; exclude: vscode.GlobPattern })[];\n", "\t\t\t\texclusive?: boolean;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\toptions?: vscode.NotebookDocumentContentOptions & {\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebook.ts", "type": "replace", "edit_start_line_idx": 326 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyCode } from 'vs/base/common/keyCodes'; import { EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation'; import { LinkedList } from 'vs/base/common/linkedList'; import { createDecorator, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { localize } from 'vs/nls'; const IEditorCancellationTokens = createDecorator<IEditorCancellationTokens>('IEditorCancelService'); interface IEditorCancellationTokens { readonly _serviceBrand: undefined; add(editor: ICodeEditor, cts: CancellationTokenSource): () => void; cancel(editor: ICodeEditor): void; } const ctxCancellableOperation = new RawContextKey('cancellableOperation', false, localize('cancellableOperation', 'Whether the editor runs a cancellable operation, e.g. like \'Peek References\'')); registerSingleton(IEditorCancellationTokens, class implements IEditorCancellationTokens { declare readonly _serviceBrand: undefined; private readonly _tokens = new WeakMap<ICodeEditor, { key: IContextKey<boolean>, tokens: LinkedList<CancellationTokenSource> }>(); add(editor: ICodeEditor, cts: CancellationTokenSource): () => void { let data = this._tokens.get(editor); if (!data) { data = editor.invokeWithinContext(accessor => { const key = ctxCancellableOperation.bindTo(accessor.get(IContextKeyService)); const tokens = new LinkedList<CancellationTokenSource>(); return { key, tokens }; }); this._tokens.set(editor, data); } let removeFn: Function | undefined; data.key.set(true); removeFn = data.tokens.push(cts); return () => { // remove w/o cancellation if (removeFn) { removeFn(); data!.key.set(!data!.tokens.isEmpty()); removeFn = undefined; } }; } cancel(editor: ICodeEditor): void { const data = this._tokens.get(editor); if (!data) { return; } // remove with cancellation const cts = data.tokens.pop(); if (cts) { cts.cancel(); data.key.set(!data.tokens.isEmpty()); } } }, true); export class EditorKeybindingCancellationTokenSource extends CancellationTokenSource { private readonly _unregister: Function; constructor(readonly editor: ICodeEditor, parent?: CancellationToken) { super(parent); this._unregister = editor.invokeWithinContext(accessor => accessor.get(IEditorCancellationTokens).add(editor, this)); } override dispose(): void { this._unregister(); super.dispose(); } } registerEditorCommand(new class extends EditorCommand { constructor() { super({ id: 'editor.cancelOperation', kbOpts: { weight: KeybindingWeight.EditorContrib, primary: KeyCode.Escape }, precondition: ctxCancellableOperation }); } runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { accessor.get(IEditorCancellationTokens).cancel(editor); } });
src/vs/editor/browser/core/keybindingCancellation.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017718097660690546, 0.0001734069228405133, 0.00016953388694673777, 0.00017355720046907663, 0.000002125358150806278 ]
{ "id": 5, "code_window": [ "\n", "\tregisterNotebookContentProvider(\n", "\t\textension: IExtensionDescription,\n", "\t\tviewType: string,\n", "\t\tprovider: vscode.NotebookContentProvider,\n", "\t\toptions?: {\n", "\t\t\ttransientOutputs: boolean;\n", "\t\t\ttransientMetadata: { [K in keyof NotebookCellMetadata]?: boolean };\n", "\t\t\tviewOptions?: {\n", "\t\t\t\tdisplayName: string;\n", "\t\t\t\tfilenamePattern: (vscode.GlobPattern | { include: vscode.GlobPattern; exclude: vscode.GlobPattern })[];\n", "\t\t\t\texclusive?: boolean;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\toptions?: vscode.NotebookDocumentContentOptions & {\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebook.ts", "type": "replace", "edit_start_line_idx": 326 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@octokit/auth-token@^2.4.0": version "2.4.2" resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-2.4.2.tgz#10d0ae979b100fa6b72fa0e8e63e27e6d0dbff8a" integrity sha512-jE/lE/IKIz2v1+/P0u4fJqv0kYwXOTujKemJMFr6FeopsxlIK3+wKDCJGnysg81XID5TgZQbIfuJ5J0lnTiuyQ== dependencies: "@octokit/types" "^5.0.0" "@octokit/core@^3.0.0": version "3.1.1" resolved "https://registry.yarnpkg.com/@octokit/core/-/core-3.1.1.tgz#1856745aa8fb154cf1544a2a1b82586c809c5e66" integrity sha512-cQ2HGrtyNJ1IBxpTP1U5m/FkMAJvgw7d2j1q3c9P0XUuYilEgF6e4naTpsgm4iVcQeOnccZlw7XHRIUBy0ymcg== dependencies: "@octokit/auth-token" "^2.4.0" "@octokit/graphql" "^4.3.1" "@octokit/request" "^5.4.0" "@octokit/types" "^5.0.0" before-after-hook "^2.1.0" universal-user-agent "^6.0.0" "@octokit/endpoint@^6.0.1": version "6.0.4" resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-6.0.4.tgz#da3eafdee1fabd6e5b6ca311efcba26f0dd99848" integrity sha512-ZJHIsvsClEE+6LaZXskDvWIqD3Ao7+2gc66pRG5Ov4MQtMvCU9wGu1TItw9aGNmRuU9x3Fei1yb+uqGaQnm0nw== dependencies: "@octokit/types" "^5.0.0" is-plain-object "^3.0.0" universal-user-agent "^6.0.0" "@octokit/graphql@^4.3.1": version "4.5.2" resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-4.5.2.tgz#33021ebf94939cf47562823851ab11fe64392274" integrity sha512-SpB/JGdB7bxRj8qowwfAXjMpICUYSJqRDj26MKJAryRQBqp/ZzARsaO2LEFWzDaps0FLQoPYVGppS0HQXkBhdg== dependencies: "@octokit/request" "^5.3.0" "@octokit/types" "^5.0.0" universal-user-agent "^6.0.0" "@octokit/plugin-paginate-rest@^2.2.0": version "2.2.3" resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.2.3.tgz#a6ad4377e7e7832fb4bdd9d421e600cb7640ac27" integrity sha512-eKTs91wXnJH8Yicwa30jz6DF50kAh7vkcqCQ9D7/tvBAP5KKkg6I2nNof8Mp/65G0Arjsb4QcOJcIEQY+rK1Rg== dependencies: "@octokit/types" "^5.0.0" "@octokit/plugin-request-log@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@octokit/plugin-request-log/-/plugin-request-log-1.0.0.tgz#eef87a431300f6148c39a7f75f8cfeb218b2547e" integrity sha512-ywoxP68aOT3zHCLgWZgwUJatiENeHE7xJzYjfz8WI0goynp96wETBF+d95b8g/uL4QmS6owPVlaxiz3wyMAzcw== "@octokit/[email protected]": version "4.1.0" resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-4.1.0.tgz#338c568177c4d4d753f9525af88b29cd0f091734" integrity sha512-zbRTjm+xplSNlixotTVMvLJe8aRogUXS+r37wZK5EjLsNYH4j02K5XLMOWyYaSS4AJEZtPmzCcOcui4VzVGq+A== dependencies: "@octokit/types" "^5.1.0" deprecation "^2.3.1" "@octokit/request-error@^2.0.0": version "2.0.2" resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-2.0.2.tgz#0e76b83f5d8fdda1db99027ea5f617c2e6ba9ed0" integrity sha512-2BrmnvVSV1MXQvEkrb9zwzP0wXFNbPJij922kYBTLIlIafukrGOb+ABBT2+c6wZiuyWDH1K1zmjGQ0toN/wMWw== dependencies: "@octokit/types" "^5.0.1" deprecation "^2.0.0" once "^1.4.0" "@octokit/request@^5.3.0", "@octokit/request@^5.4.0": version "5.4.6" resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.4.6.tgz#e8cc8d4cfc654d30428ea92aaa62168fd5ead7eb" integrity sha512-9r8Sn4CvqFI9LDLHl9P17EZHwj3ehwQnTpTE+LEneb0VBBqSiI/VS4rWIBfBhDrDs/aIGEGZRSB0QWAck8u+2g== dependencies: "@octokit/endpoint" "^6.0.1" "@octokit/request-error" "^2.0.0" "@octokit/types" "^5.0.0" deprecation "^2.0.0" is-plain-object "^3.0.0" node-fetch "^2.3.0" once "^1.4.0" universal-user-agent "^6.0.0" "@octokit/rest@^18.0.1": version "18.0.1" resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-18.0.1.tgz#46ee234770c5ff4c646f7e18708c56b6d7fa3c66" integrity sha512-KLlJpgsJx88OZ0VLBH3gvUK4sfcXjr/nE0Qzyoe76dNqMzDzkSmmvILF3f2XviGgrzuP6Ie0ay/QX478Vrpn9A== dependencies: "@octokit/core" "^3.0.0" "@octokit/plugin-paginate-rest" "^2.2.0" "@octokit/plugin-request-log" "^1.0.0" "@octokit/plugin-rest-endpoint-methods" "4.1.0" "@octokit/types@^5.0.0", "@octokit/types@^5.0.1", "@octokit/types@^5.1.0": version "5.1.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-5.1.0.tgz#4377a3f39edad3e60753fb5c3c310756f1ded57f" integrity sha512-OFxUBgrEllAbdEmWp/wNmKIu5EuumKHG4sgy56vjZ8lXPgMhF05c76hmulfOdFHHYRpPj49ygOZJ8wgVsPecuA== dependencies: "@types/node" ">= 8" "@types/node@>= 8": version "14.0.23" resolved "https://registry.yarnpkg.com/@types/node/-/node-14.0.23.tgz#676fa0883450ed9da0bb24156213636290892806" integrity sha512-Z4U8yDAl5TFkmYsZdFPdjeMa57NOvnaf1tljHzhouaPEp7LCj2JKkejpI1ODviIAQuW4CcQmxkQ77rnLsOOoKw== "@types/node@^12.19.9": version "12.19.9" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.19.9.tgz#990ad687ad8b26ef6dcc34a4f69c33d40c95b679" integrity sha512-yj0DOaQeUrk3nJ0bd3Y5PeDRJ6W0r+kilosLA+dzF3dola/o9hxhMSg2sFvVcA2UHS5JSOsZp4S0c1OEXc4m1Q== before-after-hook@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.1.0.tgz#b6c03487f44e24200dd30ca5e6a1979c5d2fb635" integrity sha512-IWIbu7pMqyw3EAJHzzHbWa85b6oud/yfKYg5rqB5hNE8CeMi3nX+2C2sj0HswfblST86hpVEOAb9x34NZd6P7A== deprecation@^2.0.0, deprecation@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919" integrity sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ== is-plain-object@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-3.0.1.tgz#662d92d24c0aa4302407b0d45d21f2251c85f85b" integrity sha512-Xnpx182SBMrr/aBik8y+GuR4U1L9FqMSojwDQwPMmxyC6bvEqly9UBCxhauBF5vNh2gwWJNX6oDV7O+OM4z34g== node-fetch@^2.3.0: version "2.6.1" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.1.tgz#045bd323631f76ed2e2b55573394416b639a0052" integrity sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw== once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= dependencies: wrappy "1" tunnel@^0.0.6: version "0.0.6" resolved "https://registry.yarnpkg.com/tunnel/-/tunnel-0.0.6.tgz#72f1314b34a5b192db012324df2cc587ca47f92c" integrity sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg== universal-user-agent@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-6.0.0.tgz#3381f8503b251c0d9cd21bc1de939ec9df5480ee" integrity sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w== vscode-nls@^4.1.2: version "4.1.2" resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-4.1.2.tgz#ca8bf8bb82a0987b32801f9fddfdd2fb9fd3c167" integrity sha512-7bOHxPsfyuCqmP+hZXscLhiHwe7CSuFE4hyhbs22xPIhQ4jv99FcR4eBzfYYVLP356HNFpdvz63FFb/xw6T4Iw== wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=
extensions/github/yarn.lock
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00023631441581528634, 0.00017598312115296721, 0.0001633358479011804, 0.00016989969299174845, 0.00001915228676807601 ]
{ "id": 5, "code_window": [ "\n", "\tregisterNotebookContentProvider(\n", "\t\textension: IExtensionDescription,\n", "\t\tviewType: string,\n", "\t\tprovider: vscode.NotebookContentProvider,\n", "\t\toptions?: {\n", "\t\t\ttransientOutputs: boolean;\n", "\t\t\ttransientMetadata: { [K in keyof NotebookCellMetadata]?: boolean };\n", "\t\t\tviewOptions?: {\n", "\t\t\t\tdisplayName: string;\n", "\t\t\t\tfilenamePattern: (vscode.GlobPattern | { include: vscode.GlobPattern; exclude: vscode.GlobPattern })[];\n", "\t\t\t\texclusive?: boolean;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\toptions?: vscode.NotebookDocumentContentOptions & {\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebook.ts", "type": "replace", "edit_start_line_idx": 326 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Connection, TextDocuments, InitializeParams, InitializeResult, NotificationType, RequestType, DocumentRangeFormattingRequest, Disposable, ServerCapabilities, TextDocumentSyncKind, TextEdit } from 'vscode-languageserver'; import { formatError, runSafe, runSafeAsync } from './utils/runner'; import { TextDocument, JSONDocument, JSONSchema, getLanguageService, DocumentLanguageSettings, SchemaConfiguration, ClientCapabilities, Diagnostic, Range, Position } from 'vscode-json-languageservice'; import { getLanguageModelCache } from './languageModelCache'; import { RequestService, basename, resolvePath } from './requests'; type ISchemaAssociations = Record<string, string[]>; namespace SchemaAssociationNotification { export const type: NotificationType<ISchemaAssociations | SchemaConfiguration[]> = new NotificationType('json/schemaAssociations'); } namespace VSCodeContentRequest { export const type: RequestType<string, string, any> = new RequestType('vscode/content'); } namespace SchemaContentChangeNotification { export const type: NotificationType<string> = new NotificationType('json/schemaContent'); } namespace ResultLimitReachedNotification { export const type: NotificationType<string> = new NotificationType('json/resultLimitReached'); } namespace ForceValidateRequest { export const type: RequestType<string, Diagnostic[], any> = new RequestType('json/validate'); } const workspaceContext = { resolveRelativePath: (relativePath: string, resource: string) => { const base = resource.substr(0, resource.lastIndexOf('/') + 1); return resolvePath(base, relativePath); } }; export interface RuntimeEnvironment { file?: RequestService; http?: RequestService configureHttpRequests?(proxy: string, strictSSL: boolean): void; } export function startServer(connection: Connection, runtime: RuntimeEnvironment) { function getSchemaRequestService(handledSchemas: string[] = ['https', 'http', 'file']) { const builtInHandlers: { [protocol: string]: RequestService | undefined } = {}; for (let protocol of handledSchemas) { if (protocol === 'file') { builtInHandlers[protocol] = runtime.file; } else if (protocol === 'http' || protocol === 'https') { builtInHandlers[protocol] = runtime.http; } } return (uri: string): Thenable<string> => { const protocol = uri.substr(0, uri.indexOf(':')); const builtInHandler = builtInHandlers[protocol]; if (builtInHandler) { return builtInHandler.getContent(uri); } return connection.sendRequest(VSCodeContentRequest.type, uri).then(responseText => { return responseText; }, error => { return Promise.reject(error.message); }); }; } // create the JSON language service let languageService = getLanguageService({ workspaceContext, contributions: [], clientCapabilities: ClientCapabilities.LATEST }); // Create a text document manager. const documents = new TextDocuments(TextDocument); // Make the text document manager listen on the connection // for open, change and close text document events documents.listen(connection); let clientSnippetSupport = false; let dynamicFormatterRegistration = false; let hierarchicalDocumentSymbolSupport = false; let foldingRangeLimitDefault = Number.MAX_VALUE; let foldingRangeLimit = Number.MAX_VALUE; let resultLimit = Number.MAX_VALUE; let formatterMaxNumberOfEdits = Number.MAX_VALUE; // After the server has started the client sends an initialize request. The server receives // in the passed params the rootPath of the workspace plus the client capabilities. connection.onInitialize((params: InitializeParams): InitializeResult => { const handledProtocols = params.initializationOptions?.handledSchemaProtocols; languageService = getLanguageService({ schemaRequestService: getSchemaRequestService(handledProtocols), workspaceContext, contributions: [], clientCapabilities: params.capabilities }); function getClientCapability<T>(name: string, def: T) { const keys = name.split('.'); let c: any = params.capabilities; for (let i = 0; c && i < keys.length; i++) { if (!c.hasOwnProperty(keys[i])) { return def; } c = c[keys[i]]; } return c; } clientSnippetSupport = getClientCapability('textDocument.completion.completionItem.snippetSupport', false); dynamicFormatterRegistration = getClientCapability('textDocument.rangeFormatting.dynamicRegistration', false) && (typeof params.initializationOptions?.provideFormatter !== 'boolean'); foldingRangeLimitDefault = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE); hierarchicalDocumentSymbolSupport = getClientCapability('textDocument.documentSymbol.hierarchicalDocumentSymbolSupport', false); formatterMaxNumberOfEdits = params.initializationOptions?.customCapabilities?.rangeFormatting?.editLimit || Number.MAX_VALUE; const capabilities: ServerCapabilities = { textDocumentSync: TextDocumentSyncKind.Incremental, completionProvider: clientSnippetSupport ? { resolveProvider: false, // turn off resolving as the current language service doesn't do anything on resolve. Also fixes #91747 triggerCharacters: ['"', ':'] } : undefined, hoverProvider: true, documentSymbolProvider: true, documentRangeFormattingProvider: params.initializationOptions?.provideFormatter === true, colorProvider: {}, foldingRangeProvider: true, selectionRangeProvider: true, documentLinkProvider: {} }; return { capabilities }; }); // The settings interface describes the server relevant settings part interface Settings { json: { schemas: JSONSchemaSettings[]; format: { enable: boolean; }; resultLimit?: number; }; http: { proxy: string; proxyStrictSSL: boolean; }; } interface JSONSchemaSettings { fileMatch?: string[]; url?: string; schema?: JSONSchema; } const limitExceededWarnings = function () { const pendingWarnings: { [uri: string]: { features: { [name: string]: string }; timeout?: NodeJS.Timeout; } } = {}; return { cancel(uri: string) { const warning = pendingWarnings[uri]; if (warning && warning.timeout) { clearTimeout(warning.timeout); delete pendingWarnings[uri]; } }, onResultLimitExceeded(uri: string, resultLimit: number, name: string) { return () => { let warning = pendingWarnings[uri]; if (warning) { if (!warning.timeout) { // already shown return; } warning.features[name] = name; warning.timeout.refresh(); } else { warning = { features: { [name]: name } }; warning.timeout = setTimeout(() => { connection.sendNotification(ResultLimitReachedNotification.type, `${basename(uri)}: For performance reasons, ${Object.keys(warning.features).join(' and ')} have been limited to ${resultLimit} items.`); warning.timeout = undefined; }, 2000); pendingWarnings[uri] = warning; } }; } }; }(); let jsonConfigurationSettings: JSONSchemaSettings[] | undefined = undefined; let schemaAssociations: ISchemaAssociations | SchemaConfiguration[] | undefined = undefined; let formatterRegistration: Thenable<Disposable> | null = null; // The settings have changed. Is send on server activation as well. connection.onDidChangeConfiguration((change) => { let settings = <Settings>change.settings; if (runtime.configureHttpRequests) { runtime.configureHttpRequests(settings.http && settings.http.proxy, settings.http && settings.http.proxyStrictSSL); } jsonConfigurationSettings = settings.json && settings.json.schemas; updateConfiguration(); foldingRangeLimit = Math.trunc(Math.max(settings.json && settings.json.resultLimit || foldingRangeLimitDefault, 0)); resultLimit = Math.trunc(Math.max(settings.json && settings.json.resultLimit || Number.MAX_VALUE, 0)); // dynamically enable & disable the formatter if (dynamicFormatterRegistration) { const enableFormatter = settings && settings.json && settings.json.format && settings.json.format.enable; if (enableFormatter) { if (!formatterRegistration) { formatterRegistration = connection.client.register(DocumentRangeFormattingRequest.type, { documentSelector: [{ language: 'json' }, { language: 'jsonc' }] }); } } else if (formatterRegistration) { formatterRegistration.then(r => r.dispose()); formatterRegistration = null; } } }); // The jsonValidation extension configuration has changed connection.onNotification(SchemaAssociationNotification.type, associations => { schemaAssociations = associations; updateConfiguration(); }); // A schema has changed connection.onNotification(SchemaContentChangeNotification.type, uri => { languageService.resetSchema(uri); }); // Retry schema validation on all open documents connection.onRequest(ForceValidateRequest.type, uri => { return new Promise<Diagnostic[]>(resolve => { const document = documents.get(uri); if (document) { updateConfiguration(); validateTextDocument(document, diagnostics => { resolve(diagnostics); }); } else { resolve([]); } }); }); function updateConfiguration() { const languageSettings = { validate: true, allowComments: true, schemas: new Array<SchemaConfiguration>() }; if (schemaAssociations) { if (Array.isArray(schemaAssociations)) { Array.prototype.push.apply(languageSettings.schemas, schemaAssociations); } else { for (const pattern in schemaAssociations) { const association = schemaAssociations[pattern]; if (Array.isArray(association)) { association.forEach(uri => { languageSettings.schemas.push({ uri, fileMatch: [pattern] }); }); } } } } if (jsonConfigurationSettings) { jsonConfigurationSettings.forEach((schema, index) => { let uri = schema.url; if (!uri && schema.schema) { uri = schema.schema.id || `vscode://schemas/custom/${index}`; } if (uri) { languageSettings.schemas.push({ uri, fileMatch: schema.fileMatch, schema: schema.schema }); } }); } languageService.configure(languageSettings); // Revalidate any open text documents documents.all().forEach(triggerValidation); } // The content of a text document has changed. This event is emitted // when the text document first opened or when its content has changed. documents.onDidChangeContent((change) => { limitExceededWarnings.cancel(change.document.uri); triggerValidation(change.document); }); // a document has closed: clear all diagnostics documents.onDidClose(event => { limitExceededWarnings.cancel(event.document.uri); cleanPendingValidation(event.document); connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] }); }); const pendingValidationRequests: { [uri: string]: NodeJS.Timer; } = {}; const validationDelayMs = 300; function cleanPendingValidation(textDocument: TextDocument): void { const request = pendingValidationRequests[textDocument.uri]; if (request) { clearTimeout(request); delete pendingValidationRequests[textDocument.uri]; } } function triggerValidation(textDocument: TextDocument): void { cleanPendingValidation(textDocument); pendingValidationRequests[textDocument.uri] = setTimeout(() => { delete pendingValidationRequests[textDocument.uri]; validateTextDocument(textDocument); }, validationDelayMs); } function validateTextDocument(textDocument: TextDocument, callback?: (diagnostics: Diagnostic[]) => void): void { const respond = (diagnostics: Diagnostic[]) => { connection.sendDiagnostics({ uri: textDocument.uri, diagnostics }); if (callback) { callback(diagnostics); } }; if (textDocument.getText().length === 0) { respond([]); // ignore empty documents return; } const jsonDocument = getJSONDocument(textDocument); const version = textDocument.version; const documentSettings: DocumentLanguageSettings = textDocument.languageId === 'jsonc' ? { comments: 'ignore', trailingCommas: 'warning' } : { comments: 'error', trailingCommas: 'error' }; languageService.doValidation(textDocument, jsonDocument, documentSettings).then(diagnostics => { setImmediate(() => { const currDocument = documents.get(textDocument.uri); if (currDocument && currDocument.version === version) { respond(diagnostics); // Send the computed diagnostics to VSCode. } }); }, error => { connection.console.error(formatError(`Error while validating ${textDocument.uri}`, error)); }); } connection.onDidChangeWatchedFiles((change) => { // Monitored files have changed in VSCode let hasChanges = false; change.changes.forEach(c => { if (languageService.resetSchema(c.uri)) { hasChanges = true; } }); if (hasChanges) { documents.all().forEach(triggerValidation); } }); const jsonDocuments = getLanguageModelCache<JSONDocument>(10, 60, document => languageService.parseJSONDocument(document)); documents.onDidClose(e => { jsonDocuments.onDocumentRemoved(e.document); }); connection.onShutdown(() => { jsonDocuments.dispose(); }); function getJSONDocument(document: TextDocument): JSONDocument { return jsonDocuments.get(document); } connection.onCompletion((textDocumentPosition, token) => { return runSafeAsync(async () => { const document = documents.get(textDocumentPosition.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); return languageService.doComplete(document, textDocumentPosition.position, jsonDocument); } return null; }, null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token); }); connection.onHover((textDocumentPositionParams, token) => { return runSafeAsync(async () => { const document = documents.get(textDocumentPositionParams.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); return languageService.doHover(document, textDocumentPositionParams.position, jsonDocument); } return null; }, null, `Error while computing hover for ${textDocumentPositionParams.textDocument.uri}`, token); }); connection.onDocumentSymbol((documentSymbolParams, token) => { return runSafe(() => { const document = documents.get(documentSymbolParams.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); const onResultLimitExceeded = limitExceededWarnings.onResultLimitExceeded(document.uri, resultLimit, 'document symbols'); if (hierarchicalDocumentSymbolSupport) { return languageService.findDocumentSymbols2(document, jsonDocument, { resultLimit, onResultLimitExceeded }); } else { return languageService.findDocumentSymbols(document, jsonDocument, { resultLimit, onResultLimitExceeded }); } } return []; }, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token); }); connection.onDocumentRangeFormatting((formatParams, token) => { return runSafe(() => { const document = documents.get(formatParams.textDocument.uri); if (document) { const edits = languageService.format(document, formatParams.range, formatParams.options); if (edits.length > formatterMaxNumberOfEdits) { const newText = TextDocument.applyEdits(document, edits); return [TextEdit.replace(Range.create(Position.create(0, 0), document.positionAt(document.getText().length)), newText)]; } return edits; } return []; }, [], `Error while formatting range for ${formatParams.textDocument.uri}`, token); }); connection.onDocumentColor((params, token) => { return runSafeAsync(async () => { const document = documents.get(params.textDocument.uri); if (document) { const onResultLimitExceeded = limitExceededWarnings.onResultLimitExceeded(document.uri, resultLimit, 'document colors'); const jsonDocument = getJSONDocument(document); return languageService.findDocumentColors(document, jsonDocument, { resultLimit, onResultLimitExceeded }); } return []; }, [], `Error while computing document colors for ${params.textDocument.uri}`, token); }); connection.onColorPresentation((params, token) => { return runSafe(() => { const document = documents.get(params.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); return languageService.getColorPresentations(document, jsonDocument, params.color, params.range); } return []; }, [], `Error while computing color presentations for ${params.textDocument.uri}`, token); }); connection.onFoldingRanges((params, token) => { return runSafe(() => { const document = documents.get(params.textDocument.uri); if (document) { const onRangeLimitExceeded = limitExceededWarnings.onResultLimitExceeded(document.uri, foldingRangeLimit, 'folding ranges'); return languageService.getFoldingRanges(document, { rangeLimit: foldingRangeLimit, onRangeLimitExceeded }); } return null; }, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token); }); connection.onSelectionRanges((params, token) => { return runSafe(() => { const document = documents.get(params.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); return languageService.getSelectionRanges(document, params.positions, jsonDocument); } return []; }, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token); }); connection.onDocumentLinks((params, token) => { return runSafeAsync(async () => { const document = documents.get(params.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); return languageService.findLinks(document, jsonDocument); } return []; }, [], `Error while computing links for ${params.textDocument.uri}`, token); }); // Listen on the connection connection.listen(); }
extensions/json-language-features/server/src/jsonServer.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00018838584946934134, 0.0001734564284561202, 0.0001639951951801777, 0.00017395077156834304, 0.0000035297216527396813 ]
{ "id": 7, "code_window": [ "\n", "\t\tlet isDisposed = false;\n", "\t\tconst commandDisposables = new DisposableStore();\n", "\n", "\t\tconst emitter = new Emitter<boolean>();\n", "\t\tthis._kernelData.set(handle, { id: options.id, executeHandler: options.executeHandler, selected: false, onDidChangeSelection: emitter });\n", "\n", "\t\tconst data: INotebookKernelDto2 = {\n", "\t\t\tid: options.id,\n", "\t\t\tselector: options.selector,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst emitter = new Emitter<{ selected: boolean, uri: URI }>();\n", "\t\tthis._kernelData.set(handle, { id: options.id, executeHandler: options.executeHandler, onDidChangeSelection: emitter });\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import * as errors from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import Severity from 'vs/base/common/severity'; import { URI } from 'vs/base/common/uri'; import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions'; import { OverviewRulerLane } from 'vs/editor/common/model'; import * as languageConfiguration from 'vs/editor/common/modes/languageConfiguration'; import { score } from 'vs/editor/common/modes/languageSelector'; import * as files from 'vs/platform/files/common/files'; import { ExtHostContext, MainContext, ExtHostLogServiceShape, UIKind, CandidatePortSource } from 'vs/workbench/api/common/extHost.protocol'; import { ExtHostApiCommands } from 'vs/workbench/api/common/extHostApiCommands'; import { ExtHostClipboard } from 'vs/workbench/api/common/extHostClipboard'; import { IExtHostCommands } from 'vs/workbench/api/common/extHostCommands'; import { ExtHostComments } from 'vs/workbench/api/common/extHostComments'; import { ExtHostConfigProvider, IExtHostConfiguration } from 'vs/workbench/api/common/extHostConfiguration'; import { ExtHostDiagnostics } from 'vs/workbench/api/common/extHostDiagnostics'; import { ExtHostDialogs } from 'vs/workbench/api/common/extHostDialogs'; import { ExtHostDocumentContentProvider } from 'vs/workbench/api/common/extHostDocumentContentProviders'; import { ExtHostDocumentSaveParticipant } from 'vs/workbench/api/common/extHostDocumentSaveParticipant'; import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments'; import { IExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors'; import { Extension, IExtHostExtensionService } from 'vs/workbench/api/common/extHostExtensionService'; import { ExtHostFileSystem } from 'vs/workbench/api/common/extHostFileSystem'; import { ExtHostFileSystemEventService } from 'vs/workbench/api/common/extHostFileSystemEventService'; import { ExtHostLanguageFeatures } from 'vs/workbench/api/common/extHostLanguageFeatures'; import { ExtHostLanguages } from 'vs/workbench/api/common/extHostLanguages'; import { ExtHostMessageService } from 'vs/workbench/api/common/extHostMessageService'; import { IExtHostOutputService } from 'vs/workbench/api/common/extHostOutput'; import { ExtHostProgress } from 'vs/workbench/api/common/extHostProgress'; import { createExtHostQuickOpen } from 'vs/workbench/api/common/extHostQuickOpen'; import { ExtHostSCM } from 'vs/workbench/api/common/extHostSCM'; import { ExtHostStatusBar } from 'vs/workbench/api/common/extHostStatusBar'; import { IExtHostStorage } from 'vs/workbench/api/common/extHostStorage'; import { IExtHostTerminalService } from 'vs/workbench/api/common/extHostTerminalService'; import { ExtHostEditors } from 'vs/workbench/api/common/extHostTextEditors'; import { ExtHostTreeViews } from 'vs/workbench/api/common/extHostTreeViews'; import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters'; import * as extHostTypes from 'vs/workbench/api/common/extHostTypes'; import { ExtHostUrls } from 'vs/workbench/api/common/extHostUrls'; import { ExtHostWebviews } from 'vs/workbench/api/common/extHostWebview'; import { IExtHostWindow } from 'vs/workbench/api/common/extHostWindow'; import { IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace'; import { throwProposedApiError, checkProposedApiEnabled } from 'vs/workbench/services/extensions/common/extensions'; import { ProxyIdentifier } from 'vs/workbench/services/extensions/common/proxyIdentifier'; import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/common/extensionDescriptionRegistry'; import type * as vscode from 'vscode'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { values } from 'vs/base/common/collections'; import { ExtHostEditorInsets } from 'vs/workbench/api/common/extHostCodeInsets'; import { ExtHostLabelService } from 'vs/workbench/api/common/extHostLabelService'; import { getRemoteName } from 'vs/platform/remote/common/remoteHosts'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IExtHostDecorations } from 'vs/workbench/api/common/extHostDecorations'; import { IExtHostTask } from 'vs/workbench/api/common/extHostTask'; import { IExtHostDebugService } from 'vs/workbench/api/common/extHostDebugService'; import { IExtHostSearch } from 'vs/workbench/api/common/extHostSearch'; import { ILogService } from 'vs/platform/log/common/log'; import { IURITransformerService } from 'vs/workbench/api/common/extHostUriTransformerService'; import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService'; import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService'; import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook'; import { ExtHostTheming } from 'vs/workbench/api/common/extHostTheming'; import { IExtHostTunnelService } from 'vs/workbench/api/common/extHostTunnelService'; import { IExtHostApiDeprecationService } from 'vs/workbench/api/common/extHostApiDeprecationService'; import { ExtHostAuthentication } from 'vs/workbench/api/common/extHostAuthentication'; import { ExtHostTimeline } from 'vs/workbench/api/common/extHostTimeline'; import { ExtHostNotebookConcatDocument } from 'vs/workbench/api/common/extHostNotebookConcatDocument'; import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths'; import { IExtHostConsumerFileSystem } from 'vs/workbench/api/common/extHostFileSystemConsumer'; import { ExtHostWebviewViews } from 'vs/workbench/api/common/extHostWebviewView'; import { ExtHostCustomEditors } from 'vs/workbench/api/common/extHostCustomEditors'; import { ExtHostWebviewPanels } from 'vs/workbench/api/common/extHostWebviewPanels'; import { ExtHostBulkEdits } from 'vs/workbench/api/common/extHostBulkEdits'; import { IExtHostFileSystemInfo } from 'vs/workbench/api/common/extHostFileSystemInfo'; import { ExtHostTesting } from 'vs/workbench/api/common/extHostTesting'; import { ExtHostUriOpeners } from 'vs/workbench/api/common/extHostUriOpener'; import { IExtHostSecretState } from 'vs/workbench/api/common/exHostSecretState'; import { ExtHostEditorTabs } from 'vs/workbench/api/common/extHostEditorTabs'; import { IExtHostTelemetry } from 'vs/workbench/api/common/extHostTelemetry'; import { ExtHostNotebookKernels } from 'vs/workbench/api/common/extHostNotebookKernels'; export interface IExtensionApiFactory { (extension: IExtensionDescription, registry: ExtensionDescriptionRegistry, configProvider: ExtHostConfigProvider): typeof vscode; } /** * This method instantiates and returns the extension API surface */ export function createApiFactoryAndRegisterActors(accessor: ServicesAccessor): IExtensionApiFactory { // services const initData = accessor.get(IExtHostInitDataService); const extHostFileSystemInfo = accessor.get(IExtHostFileSystemInfo); const extHostConsumerFileSystem = accessor.get(IExtHostConsumerFileSystem); const extensionService = accessor.get(IExtHostExtensionService); const extHostWorkspace = accessor.get(IExtHostWorkspace); const extHostTelemetry = accessor.get(IExtHostTelemetry); const extHostConfiguration = accessor.get(IExtHostConfiguration); const uriTransformer = accessor.get(IURITransformerService); const rpcProtocol = accessor.get(IExtHostRpcService); const extHostStorage = accessor.get(IExtHostStorage); const extensionStoragePaths = accessor.get(IExtensionStoragePaths); const extHostLogService = accessor.get(ILogService); const extHostTunnelService = accessor.get(IExtHostTunnelService); const extHostApiDeprecation = accessor.get(IExtHostApiDeprecationService); const extHostWindow = accessor.get(IExtHostWindow); const extHostSecretState = accessor.get(IExtHostSecretState); // register addressable instances rpcProtocol.set(ExtHostContext.ExtHostFileSystemInfo, extHostFileSystemInfo); rpcProtocol.set(ExtHostContext.ExtHostLogService, <ExtHostLogServiceShape><any>extHostLogService); rpcProtocol.set(ExtHostContext.ExtHostWorkspace, extHostWorkspace); rpcProtocol.set(ExtHostContext.ExtHostConfiguration, extHostConfiguration); rpcProtocol.set(ExtHostContext.ExtHostExtensionService, extensionService); rpcProtocol.set(ExtHostContext.ExtHostStorage, extHostStorage); rpcProtocol.set(ExtHostContext.ExtHostTunnelService, extHostTunnelService); rpcProtocol.set(ExtHostContext.ExtHostWindow, extHostWindow); rpcProtocol.set(ExtHostContext.ExtHostSecretState, extHostSecretState); rpcProtocol.set(ExtHostContext.ExtHostTelemetry, extHostTelemetry); // automatically create and register addressable instances const extHostDecorations = rpcProtocol.set(ExtHostContext.ExtHostDecorations, accessor.get(IExtHostDecorations)); const extHostDocumentsAndEditors = rpcProtocol.set(ExtHostContext.ExtHostDocumentsAndEditors, accessor.get(IExtHostDocumentsAndEditors)); const extHostCommands = rpcProtocol.set(ExtHostContext.ExtHostCommands, accessor.get(IExtHostCommands)); const extHostTerminalService = rpcProtocol.set(ExtHostContext.ExtHostTerminalService, accessor.get(IExtHostTerminalService)); const extHostDebugService = rpcProtocol.set(ExtHostContext.ExtHostDebugService, accessor.get(IExtHostDebugService)); const extHostSearch = rpcProtocol.set(ExtHostContext.ExtHostSearch, accessor.get(IExtHostSearch)); const extHostTask = rpcProtocol.set(ExtHostContext.ExtHostTask, accessor.get(IExtHostTask)); const extHostOutputService = rpcProtocol.set(ExtHostContext.ExtHostOutputService, accessor.get(IExtHostOutputService)); // manually create and register addressable instances const extHostEditorTabs = rpcProtocol.set(ExtHostContext.ExtHostEditorTabs, new ExtHostEditorTabs()); const extHostUrls = rpcProtocol.set(ExtHostContext.ExtHostUrls, new ExtHostUrls(rpcProtocol)); const extHostDocuments = rpcProtocol.set(ExtHostContext.ExtHostDocuments, new ExtHostDocuments(rpcProtocol, extHostDocumentsAndEditors)); const extHostDocumentContentProviders = rpcProtocol.set(ExtHostContext.ExtHostDocumentContentProviders, new ExtHostDocumentContentProvider(rpcProtocol, extHostDocumentsAndEditors, extHostLogService)); const extHostDocumentSaveParticipant = rpcProtocol.set(ExtHostContext.ExtHostDocumentSaveParticipant, new ExtHostDocumentSaveParticipant(extHostLogService, extHostDocuments, rpcProtocol.getProxy(MainContext.MainThreadBulkEdits))); const extHostNotebook = rpcProtocol.set(ExtHostContext.ExtHostNotebook, new ExtHostNotebookController(rpcProtocol, extHostCommands, extHostDocumentsAndEditors, extHostDocuments, initData.environment, extHostLogService, extensionStoragePaths)); const extHostNotebookKernels = rpcProtocol.set(ExtHostContext.ExtHostNotebookKernels, new ExtHostNotebookKernels(rpcProtocol, extHostNotebook)); const extHostEditors = rpcProtocol.set(ExtHostContext.ExtHostEditors, new ExtHostEditors(rpcProtocol, extHostDocumentsAndEditors)); const extHostTreeViews = rpcProtocol.set(ExtHostContext.ExtHostTreeViews, new ExtHostTreeViews(rpcProtocol.getProxy(MainContext.MainThreadTreeViews), extHostCommands, extHostLogService)); const extHostEditorInsets = rpcProtocol.set(ExtHostContext.ExtHostEditorInsets, new ExtHostEditorInsets(rpcProtocol.getProxy(MainContext.MainThreadEditorInsets), extHostEditors, initData.environment)); const extHostDiagnostics = rpcProtocol.set(ExtHostContext.ExtHostDiagnostics, new ExtHostDiagnostics(rpcProtocol, extHostLogService)); const extHostLanguageFeatures = rpcProtocol.set(ExtHostContext.ExtHostLanguageFeatures, new ExtHostLanguageFeatures(rpcProtocol, uriTransformer, extHostDocuments, extHostCommands, extHostDiagnostics, extHostLogService, extHostApiDeprecation)); const extHostFileSystem = rpcProtocol.set(ExtHostContext.ExtHostFileSystem, new ExtHostFileSystem(rpcProtocol, extHostLanguageFeatures)); const extHostFileSystemEvent = rpcProtocol.set(ExtHostContext.ExtHostFileSystemEventService, new ExtHostFileSystemEventService(rpcProtocol, extHostLogService, extHostDocumentsAndEditors)); const extHostQuickOpen = rpcProtocol.set(ExtHostContext.ExtHostQuickOpen, createExtHostQuickOpen(rpcProtocol, extHostWorkspace, extHostCommands)); const extHostSCM = rpcProtocol.set(ExtHostContext.ExtHostSCM, new ExtHostSCM(rpcProtocol, extHostCommands, extHostLogService)); const extHostComment = rpcProtocol.set(ExtHostContext.ExtHostComments, new ExtHostComments(rpcProtocol, extHostCommands, extHostDocuments)); const extHostProgress = rpcProtocol.set(ExtHostContext.ExtHostProgress, new ExtHostProgress(rpcProtocol.getProxy(MainContext.MainThreadProgress))); const extHostLabelService = rpcProtocol.set(ExtHostContext.ExtHosLabelService, new ExtHostLabelService(rpcProtocol)); const extHostTheming = rpcProtocol.set(ExtHostContext.ExtHostTheming, new ExtHostTheming(rpcProtocol)); const extHostAuthentication = rpcProtocol.set(ExtHostContext.ExtHostAuthentication, new ExtHostAuthentication(rpcProtocol)); const extHostTimeline = rpcProtocol.set(ExtHostContext.ExtHostTimeline, new ExtHostTimeline(rpcProtocol, extHostCommands)); const extHostWebviews = rpcProtocol.set(ExtHostContext.ExtHostWebviews, new ExtHostWebviews(rpcProtocol, initData.environment, extHostWorkspace, extHostLogService, extHostApiDeprecation)); const extHostWebviewPanels = rpcProtocol.set(ExtHostContext.ExtHostWebviewPanels, new ExtHostWebviewPanels(rpcProtocol, extHostWebviews, extHostWorkspace)); const extHostCustomEditors = rpcProtocol.set(ExtHostContext.ExtHostCustomEditors, new ExtHostCustomEditors(rpcProtocol, extHostDocuments, extensionStoragePaths, extHostWebviews, extHostWebviewPanels)); const extHostWebviewViews = rpcProtocol.set(ExtHostContext.ExtHostWebviewViews, new ExtHostWebviewViews(rpcProtocol, extHostWebviews)); const extHostTesting = rpcProtocol.set(ExtHostContext.ExtHostTesting, new ExtHostTesting(rpcProtocol, extHostDocumentsAndEditors, extHostWorkspace)); const extHostUriOpeners = rpcProtocol.set(ExtHostContext.ExtHostUriOpeners, new ExtHostUriOpeners(rpcProtocol)); // Check that no named customers are missing const expected: ProxyIdentifier<any>[] = values(ExtHostContext); rpcProtocol.assertRegistered(expected); // Other instances const extHostBulkEdits = new ExtHostBulkEdits(rpcProtocol, extHostDocumentsAndEditors); const extHostClipboard = new ExtHostClipboard(rpcProtocol); const extHostMessageService = new ExtHostMessageService(rpcProtocol, extHostLogService); const extHostDialogs = new ExtHostDialogs(rpcProtocol); const extHostStatusBar = new ExtHostStatusBar(rpcProtocol, extHostCommands.converter); const extHostLanguages = new ExtHostLanguages(rpcProtocol, extHostDocuments); // Register API-ish commands ExtHostApiCommands.register(extHostCommands); return function (extension: IExtensionDescription, extensionRegistry: ExtensionDescriptionRegistry, configProvider: ExtHostConfigProvider): typeof vscode { // Check document selectors for being overly generic. Technically this isn't a problem but // in practice many extensions say they support `fooLang` but need fs-access to do so. Those // extension should specify then the `file`-scheme, e.g. `{ scheme: 'fooLang', language: 'fooLang' }` // We only inform once, it is not a warning because we just want to raise awareness and because // we cannot say if the extension is doing it right or wrong... const checkSelector = (function () { let done = (!extension.isUnderDevelopment); function informOnce(selector: vscode.DocumentSelector) { if (!done) { extHostLogService.info(`Extension '${extension.identifier.value}' uses a document selector without scheme. Learn more about this: https://go.microsoft.com/fwlink/?linkid=872305`); done = true; } } return function perform(selector: vscode.DocumentSelector): vscode.DocumentSelector { if (Array.isArray(selector)) { selector.forEach(perform); } else if (typeof selector === 'string') { informOnce(selector); } else { const filter = selector as vscode.DocumentFilter; // TODO: microsoft/TypeScript#42768 if (typeof filter.scheme === 'undefined') { informOnce(selector); } if (!extension.enableProposedApi && typeof filter.exclusive === 'boolean') { throwProposedApiError(extension); } } return selector; }; })(); const authentication: typeof vscode.authentication = { getSession(providerId: string, scopes: string[], options?: vscode.AuthenticationGetSessionOptions) { return extHostAuthentication.getSession(extension, providerId, scopes, options as any); }, get onDidChangeSessions(): Event<vscode.AuthenticationSessionsChangeEvent> { return extHostAuthentication.onDidChangeSessions; }, registerAuthenticationProvider(id: string, label: string, provider: vscode.AuthenticationProvider, options?: vscode.AuthenticationProviderOptions): vscode.Disposable { return extHostAuthentication.registerAuthenticationProvider(id, label, provider, options); }, get onDidChangeAuthenticationProviders(): Event<vscode.AuthenticationProvidersChangeEvent> { checkProposedApiEnabled(extension); return extHostAuthentication.onDidChangeAuthenticationProviders; }, get providers(): ReadonlyArray<vscode.AuthenticationProviderInformation> { checkProposedApiEnabled(extension); return extHostAuthentication.providers; }, logout(providerId: string, sessionId: string): Thenable<void> { checkProposedApiEnabled(extension); return extHostAuthentication.removeSession(providerId, sessionId); } }; // namespace: commands const commands: typeof vscode.commands = { registerCommand(id: string, command: <T>(...args: any[]) => T | Thenable<T>, thisArgs?: any): vscode.Disposable { return extHostCommands.registerCommand(true, id, command, thisArgs); }, registerTextEditorCommand(id: string, callback: (textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, ...args: any[]) => void, thisArg?: any): vscode.Disposable { return extHostCommands.registerCommand(true, id, (...args: any[]): any => { const activeTextEditor = extHostEditors.getActiveTextEditor(); if (!activeTextEditor) { extHostLogService.warn('Cannot execute ' + id + ' because there is no active text editor.'); return undefined; } return activeTextEditor.edit((edit: vscode.TextEditorEdit) => { callback.apply(thisArg, [activeTextEditor, edit, ...args]); }).then((result) => { if (!result) { extHostLogService.warn('Edits from command ' + id + ' were not applied.'); } }, (err) => { extHostLogService.warn('An error occurred while running command ' + id, err); }); }); }, registerDiffInformationCommand: (id: string, callback: (diff: vscode.LineChange[], ...args: any[]) => any, thisArg?: any): vscode.Disposable => { checkProposedApiEnabled(extension); return extHostCommands.registerCommand(true, id, async (...args: any[]): Promise<any> => { const activeTextEditor = extHostDocumentsAndEditors.activeEditor(true); if (!activeTextEditor) { extHostLogService.warn('Cannot execute ' + id + ' because there is no active text editor.'); return undefined; } const diff = await extHostEditors.getDiffInformation(activeTextEditor.id); callback.apply(thisArg, [diff, ...args]); }); }, executeCommand<T>(id: string, ...args: any[]): Thenable<T> { return extHostCommands.executeCommand<T>(id, ...args); }, getCommands(filterInternal: boolean = false): Thenable<string[]> { return extHostCommands.getCommands(filterInternal); } }; // namespace: env const env: typeof vscode.env = { get machineId() { return initData.telemetryInfo.machineId; }, get sessionId() { return initData.telemetryInfo.sessionId; }, get language() { return initData.environment.appLanguage; }, get appName() { return initData.environment.appName; }, get appRoot() { return initData.environment.appRoot?.fsPath ?? ''; }, get uriScheme() { return initData.environment.appUriScheme; }, get clipboard(): vscode.Clipboard { return extHostClipboard.value; }, get shell() { return extHostTerminalService.getDefaultShell(false, configProvider); }, get isTelemetryEnabled() { return extHostTelemetry.getTelemetryEnabled(); }, get onDidChangeTelemetryEnabled(): Event<boolean> { return extHostTelemetry.onDidChangeTelemetryEnabled; }, get isNewAppInstall() { const installAge = Date.now() - new Date(initData.telemetryInfo.firstSessionDate).getTime(); return isNaN(installAge) ? false : installAge < 1000 * 60 * 60 * 24; // install age is less than a day }, openExternal(uri: URI, options?: { allowContributedOpeners?: boolean | string; }) { return extHostWindow.openUri(uri, { allowTunneling: !!initData.remote.authority, allowContributedOpeners: options?.allowContributedOpeners, }); }, asExternalUri(uri: URI) { if (uri.scheme === initData.environment.appUriScheme) { return extHostUrls.createAppUri(uri); } return extHostWindow.asExternalUri(uri, { allowTunneling: !!initData.remote.authority }); }, get remoteName() { return getRemoteName(initData.remote.authority); }, get uiKind() { return initData.uiKind; } }; if (!initData.environment.extensionTestsLocationURI) { // allow to patch env-function when running tests Object.freeze(env); } const extensionKind = initData.remote.isRemote ? extHostTypes.ExtensionKind.Workspace : extHostTypes.ExtensionKind.UI; const test: typeof vscode.test = { registerTestProvider(provider) { checkProposedApiEnabled(extension); return extHostTesting.registerTestProvider(provider); }, createDocumentTestObserver(document) { checkProposedApiEnabled(extension); return extHostTesting.createTextDocumentTestObserver(document); }, createWorkspaceTestObserver(workspaceFolder) { checkProposedApiEnabled(extension); return extHostTesting.createWorkspaceTestObserver(workspaceFolder); }, runTests(provider) { checkProposedApiEnabled(extension); return extHostTesting.runTests(provider); }, publishTestResult(results, persist = true) { checkProposedApiEnabled(extension); return extHostTesting.publishExtensionProvidedResults(results, persist); }, get onDidChangeTestResults() { checkProposedApiEnabled(extension); return extHostTesting.onResultsChanged; }, get testResults() { checkProposedApiEnabled(extension); return extHostTesting.results; }, }; // namespace: extensions const extensions: typeof vscode.extensions = { getExtension(extensionId: string): vscode.Extension<any> | undefined { const desc = extensionRegistry.getExtensionDescription(extensionId); if (desc) { return new Extension(extensionService, extension.identifier, desc, extensionKind); } return undefined; }, get all(): vscode.Extension<any>[] { return extensionRegistry.getAllExtensionDescriptions().map((desc) => new Extension(extensionService, extension.identifier, desc, extensionKind)); }, get onDidChange() { return extensionRegistry.onDidChange; } }; // namespace: languages const languages: typeof vscode.languages = { createDiagnosticCollection(name?: string): vscode.DiagnosticCollection { return extHostDiagnostics.createDiagnosticCollection(extension.identifier, name); }, get onDidChangeDiagnostics() { return extHostDiagnostics.onDidChangeDiagnostics; }, getDiagnostics: (resource?: vscode.Uri) => { return <any>extHostDiagnostics.getDiagnostics(resource); }, getLanguages(): Thenable<string[]> { return extHostLanguages.getLanguages(); }, setTextDocumentLanguage(document: vscode.TextDocument, languageId: string): Thenable<vscode.TextDocument> { return extHostLanguages.changeLanguage(document.uri, languageId); }, match(selector: vscode.DocumentSelector, document: vscode.TextDocument): number { return score(typeConverters.LanguageSelector.from(selector), document.uri, document.languageId, true); }, registerCodeActionsProvider(selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable { return extHostLanguageFeatures.registerCodeActionProvider(extension, checkSelector(selector), provider, metadata); }, registerCodeLensProvider(selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { return extHostLanguageFeatures.registerCodeLensProvider(extension, checkSelector(selector), provider); }, registerDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable { return extHostLanguageFeatures.registerDefinitionProvider(extension, checkSelector(selector), provider); }, registerDeclarationProvider(selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable { return extHostLanguageFeatures.registerDeclarationProvider(extension, checkSelector(selector), provider); }, registerImplementationProvider(selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable { return extHostLanguageFeatures.registerImplementationProvider(extension, checkSelector(selector), provider); }, registerTypeDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable { return extHostLanguageFeatures.registerTypeDefinitionProvider(extension, checkSelector(selector), provider); }, registerHoverProvider(selector: vscode.DocumentSelector, provider: vscode.HoverProvider): vscode.Disposable { return extHostLanguageFeatures.registerHoverProvider(extension, checkSelector(selector), provider, extension.identifier); }, registerEvaluatableExpressionProvider(selector: vscode.DocumentSelector, provider: vscode.EvaluatableExpressionProvider): vscode.Disposable { return extHostLanguageFeatures.registerEvaluatableExpressionProvider(extension, checkSelector(selector), provider, extension.identifier); }, registerInlineValuesProvider(selector: vscode.DocumentSelector, provider: vscode.InlineValuesProvider): vscode.Disposable { return extHostLanguageFeatures.registerInlineValuesProvider(extension, checkSelector(selector), provider, extension.identifier); }, registerDocumentHighlightProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable { return extHostLanguageFeatures.registerDocumentHighlightProvider(extension, checkSelector(selector), provider); }, registerLinkedEditingRangeProvider(selector: vscode.DocumentSelector, provider: vscode.LinkedEditingRangeProvider): vscode.Disposable { return extHostLanguageFeatures.registerLinkedEditingRangeProvider(extension, checkSelector(selector), provider); }, registerReferenceProvider(selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable { return extHostLanguageFeatures.registerReferenceProvider(extension, checkSelector(selector), provider); }, registerRenameProvider(selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable { return extHostLanguageFeatures.registerRenameProvider(extension, checkSelector(selector), provider); }, registerDocumentSymbolProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { return extHostLanguageFeatures.registerDocumentSymbolProvider(extension, checkSelector(selector), provider, metadata); }, registerWorkspaceSymbolProvider(provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { return extHostLanguageFeatures.registerWorkspaceSymbolProvider(extension, provider); }, registerDocumentFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable { return extHostLanguageFeatures.registerDocumentFormattingEditProvider(extension, checkSelector(selector), provider); }, registerDocumentRangeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable { return extHostLanguageFeatures.registerDocumentRangeFormattingEditProvider(extension, checkSelector(selector), provider); }, registerOnTypeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, firstTriggerCharacter: string, ...moreTriggerCharacters: string[]): vscode.Disposable { return extHostLanguageFeatures.registerOnTypeFormattingEditProvider(extension, checkSelector(selector), provider, [firstTriggerCharacter].concat(moreTriggerCharacters)); }, registerDocumentSemanticTokensProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSemanticTokensProvider, legend: vscode.SemanticTokensLegend): vscode.Disposable { return extHostLanguageFeatures.registerDocumentSemanticTokensProvider(extension, checkSelector(selector), provider, legend); }, registerDocumentRangeSemanticTokensProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentRangeSemanticTokensProvider, legend: vscode.SemanticTokensLegend): vscode.Disposable { return extHostLanguageFeatures.registerDocumentRangeSemanticTokensProvider(extension, checkSelector(selector), provider, legend); }, registerSignatureHelpProvider(selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, firstItem?: string | vscode.SignatureHelpProviderMetadata, ...remaining: string[]): vscode.Disposable { if (typeof firstItem === 'object') { return extHostLanguageFeatures.registerSignatureHelpProvider(extension, checkSelector(selector), provider, firstItem); } return extHostLanguageFeatures.registerSignatureHelpProvider(extension, checkSelector(selector), provider, typeof firstItem === 'undefined' ? [] : [firstItem, ...remaining]); }, registerCompletionItemProvider(selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, ...triggerCharacters: string[]): vscode.Disposable { return extHostLanguageFeatures.registerCompletionItemProvider(extension, checkSelector(selector), provider, triggerCharacters); }, registerDocumentLinkProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable { return extHostLanguageFeatures.registerDocumentLinkProvider(extension, checkSelector(selector), provider); }, registerColorProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable { return extHostLanguageFeatures.registerColorProvider(extension, checkSelector(selector), provider); }, registerFoldingRangeProvider(selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable { return extHostLanguageFeatures.registerFoldingRangeProvider(extension, checkSelector(selector), provider); }, registerSelectionRangeProvider(selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable { return extHostLanguageFeatures.registerSelectionRangeProvider(extension, selector, provider); }, registerCallHierarchyProvider(selector: vscode.DocumentSelector, provider: vscode.CallHierarchyProvider): vscode.Disposable { return extHostLanguageFeatures.registerCallHierarchyProvider(extension, selector, provider); }, setLanguageConfiguration: (language: string, configuration: vscode.LanguageConfiguration): vscode.Disposable => { return extHostLanguageFeatures.setLanguageConfiguration(extension, language, configuration); }, getTokenInformationAtPosition(doc: vscode.TextDocument, pos: vscode.Position) { checkProposedApiEnabled(extension); return extHostLanguages.tokenAtPosition(doc, pos); }, registerInlineHintsProvider(selector: vscode.DocumentSelector, provider: vscode.InlineHintsProvider): vscode.Disposable { checkProposedApiEnabled(extension); return extHostLanguageFeatures.registerInlineHintsProvider(extension, selector, provider); } }; // namespace: window const window: typeof vscode.window = { get activeTextEditor() { return extHostEditors.getActiveTextEditor(); }, get visibleTextEditors() { return extHostEditors.getVisibleTextEditors(); }, get activeTerminal() { return extHostTerminalService.activeTerminal; }, get terminals() { return extHostTerminalService.terminals; }, async showTextDocument(documentOrUri: vscode.TextDocument | vscode.Uri, columnOrOptions?: vscode.ViewColumn | vscode.TextDocumentShowOptions, preserveFocus?: boolean): Promise<vscode.TextEditor> { const document = await (URI.isUri(documentOrUri) ? Promise.resolve(workspace.openTextDocument(documentOrUri)) : Promise.resolve(<vscode.TextDocument>documentOrUri)); return extHostEditors.showTextDocument(document, columnOrOptions, preserveFocus); }, createTextEditorDecorationType(options: vscode.DecorationRenderOptions): vscode.TextEditorDecorationType { return extHostEditors.createTextEditorDecorationType(options); }, onDidChangeActiveTextEditor(listener, thisArg?, disposables?) { return extHostEditors.onDidChangeActiveTextEditor(listener, thisArg, disposables); }, onDidChangeVisibleTextEditors(listener, thisArg, disposables) { return extHostEditors.onDidChangeVisibleTextEditors(listener, thisArg, disposables); }, onDidChangeTextEditorSelection(listener: (e: vscode.TextEditorSelectionChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) { return extHostEditors.onDidChangeTextEditorSelection(listener, thisArgs, disposables); }, onDidChangeTextEditorOptions(listener: (e: vscode.TextEditorOptionsChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) { return extHostEditors.onDidChangeTextEditorOptions(listener, thisArgs, disposables); }, onDidChangeTextEditorVisibleRanges(listener: (e: vscode.TextEditorVisibleRangesChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) { return extHostEditors.onDidChangeTextEditorVisibleRanges(listener, thisArgs, disposables); }, onDidChangeTextEditorViewColumn(listener, thisArg?, disposables?) { return extHostEditors.onDidChangeTextEditorViewColumn(listener, thisArg, disposables); }, onDidCloseTerminal(listener, thisArg?, disposables?) { return extHostTerminalService.onDidCloseTerminal(listener, thisArg, disposables); }, onDidOpenTerminal(listener, thisArg?, disposables?) { return extHostTerminalService.onDidOpenTerminal(listener, thisArg, disposables); }, onDidChangeActiveTerminal(listener, thisArg?, disposables?) { return extHostTerminalService.onDidChangeActiveTerminal(listener, thisArg, disposables); }, onDidChangeTerminalDimensions(listener, thisArg?, disposables?) { checkProposedApiEnabled(extension); return extHostTerminalService.onDidChangeTerminalDimensions(listener, thisArg, disposables); }, onDidWriteTerminalData(listener, thisArg?, disposables?) { checkProposedApiEnabled(extension); return extHostTerminalService.onDidWriteTerminalData(listener, thisArg, disposables); }, get state() { return extHostWindow.state; }, onDidChangeWindowState(listener, thisArg?, disposables?) { return extHostWindow.onDidChangeWindowState(listener, thisArg, disposables); }, showInformationMessage(message: string, ...rest: Array<vscode.MessageOptions | string | vscode.MessageItem>) { return <Thenable<any>>extHostMessageService.showMessage(extension, Severity.Info, message, rest[0], <Array<string | vscode.MessageItem>>rest.slice(1)); }, showWarningMessage(message: string, ...rest: Array<vscode.MessageOptions | string | vscode.MessageItem>) { return <Thenable<any>>extHostMessageService.showMessage(extension, Severity.Warning, message, rest[0], <Array<string | vscode.MessageItem>>rest.slice(1)); }, showErrorMessage(message: string, ...rest: Array<vscode.MessageOptions | string | vscode.MessageItem>) { return <Thenable<any>>extHostMessageService.showMessage(extension, Severity.Error, message, rest[0], <Array<string | vscode.MessageItem>>rest.slice(1)); }, showQuickPick(items: any, options?: vscode.QuickPickOptions, token?: vscode.CancellationToken): any { return extHostQuickOpen.showQuickPick(items, !!extension.enableProposedApi, options, token); }, showWorkspaceFolderPick(options?: vscode.WorkspaceFolderPickOptions) { return extHostQuickOpen.showWorkspaceFolderPick(options); }, showInputBox(options?: vscode.InputBoxOptions, token?: vscode.CancellationToken) { return extHostQuickOpen.showInput(options, token); }, showOpenDialog(options) { return extHostDialogs.showOpenDialog(options); }, showSaveDialog(options) { return extHostDialogs.showSaveDialog(options); }, createStatusBarItem(alignmentOrOptions?: vscode.StatusBarAlignment | vscode.StatusBarItemOptions, priority?: number): vscode.StatusBarItem { let id: string; let name: string; let alignment: number | undefined; let accessibilityInformation: vscode.AccessibilityInformation | undefined = undefined; if (alignmentOrOptions && typeof alignmentOrOptions !== 'number') { id = alignmentOrOptions.id; name = alignmentOrOptions.name; alignment = alignmentOrOptions.alignment; priority = alignmentOrOptions.priority; accessibilityInformation = alignmentOrOptions.accessibilityInformation; } else { id = extension.identifier.value; name = nls.localize('extensionLabel', "{0} (Extension)", extension.displayName || extension.name); alignment = alignmentOrOptions; } return extHostStatusBar.createStatusBarEntry(id, name, alignment, priority, accessibilityInformation); }, setStatusBarMessage(text: string, timeoutOrThenable?: number | Thenable<any>): vscode.Disposable { return extHostStatusBar.setStatusBarMessage(text, timeoutOrThenable); }, withScmProgress<R>(task: (progress: vscode.Progress<number>) => Thenable<R>) { extHostApiDeprecation.report('window.withScmProgress', extension, `Use 'withProgress' instead.`); return extHostProgress.withProgress(extension, { location: extHostTypes.ProgressLocation.SourceControl }, (progress, token) => task({ report(n: number) { /*noop*/ } })); }, withProgress<R>(options: vscode.ProgressOptions, task: (progress: vscode.Progress<{ message?: string; worked?: number }>, token: vscode.CancellationToken) => Thenable<R>) { return extHostProgress.withProgress(extension, options, task); }, createOutputChannel(name: string): vscode.OutputChannel { return extHostOutputService.createOutputChannel(name); }, createWebviewPanel(viewType: string, title: string, showOptions: vscode.ViewColumn | { viewColumn: vscode.ViewColumn, preserveFocus?: boolean }, options?: vscode.WebviewPanelOptions & vscode.WebviewOptions): vscode.WebviewPanel { return extHostWebviewPanels.createWebviewPanel(extension, viewType, title, showOptions, options); }, createWebviewTextEditorInset(editor: vscode.TextEditor, line: number, height: number, options?: vscode.WebviewOptions): vscode.WebviewEditorInset { checkProposedApiEnabled(extension); return extHostEditorInsets.createWebviewEditorInset(editor, line, height, options, extension); }, createTerminal(nameOrOptions?: vscode.TerminalOptions | vscode.ExtensionTerminalOptions | string, shellPath?: string, shellArgs?: string[] | string): vscode.Terminal { if (typeof nameOrOptions === 'object') { if ('pty' in nameOrOptions) { return extHostTerminalService.createExtensionTerminal(nameOrOptions); } if (nameOrOptions.message) { checkProposedApiEnabled(extension); } if (nameOrOptions.icon) { checkProposedApiEnabled(extension); } return extHostTerminalService.createTerminalFromOptions(nameOrOptions); } return extHostTerminalService.createTerminal(nameOrOptions, shellPath, shellArgs); }, registerTerminalLinkProvider(handler: vscode.TerminalLinkProvider): vscode.Disposable { return extHostTerminalService.registerLinkProvider(handler); }, registerTreeDataProvider(viewId: string, treeDataProvider: vscode.TreeDataProvider<any>): vscode.Disposable { return extHostTreeViews.registerTreeDataProvider(viewId, treeDataProvider, extension); }, createTreeView(viewId: string, options: { treeDataProvider: vscode.TreeDataProvider<any> }): vscode.TreeView<any> { return extHostTreeViews.createTreeView(viewId, options, extension); }, registerWebviewPanelSerializer: (viewType: string, serializer: vscode.WebviewPanelSerializer) => { return extHostWebviewPanels.registerWebviewPanelSerializer(extension, viewType, serializer); }, registerCustomEditorProvider: (viewType: string, provider: vscode.CustomTextEditorProvider | vscode.CustomReadonlyEditorProvider, options: { webviewOptions?: vscode.WebviewPanelOptions, supportsMultipleEditorsPerDocument?: boolean } = {}) => { return extHostCustomEditors.registerCustomEditorProvider(extension, viewType, provider, options); }, registerFileDecorationProvider(provider: vscode.FileDecorationProvider) { return extHostDecorations.registerFileDecorationProvider(provider, extension.identifier); }, registerUriHandler(handler: vscode.UriHandler) { return extHostUrls.registerUriHandler(extension.identifier, handler); }, createQuickPick<T extends vscode.QuickPickItem>(): vscode.QuickPick<T> { return extHostQuickOpen.createQuickPick(extension.identifier, !!extension.enableProposedApi); }, createInputBox(): vscode.InputBox { return extHostQuickOpen.createInputBox(extension.identifier); }, get activeColorTheme(): vscode.ColorTheme { return extHostTheming.activeColorTheme; }, onDidChangeActiveColorTheme(listener, thisArg?, disposables?) { return extHostTheming.onDidChangeActiveColorTheme(listener, thisArg, disposables); }, registerWebviewViewProvider(viewId: string, provider: vscode.WebviewViewProvider, options?: { webviewOptions?: { retainContextWhenHidden?: boolean } }) { return extHostWebviewViews.registerWebviewViewProvider(extension, viewId, provider, options?.webviewOptions); }, get activeNotebookEditor(): vscode.NotebookEditor | undefined { checkProposedApiEnabled(extension); return extHostNotebook.activeNotebookEditor; }, onDidChangeActiveNotebookEditor(listener, thisArgs?, disposables?) { checkProposedApiEnabled(extension); return extHostNotebook.onDidChangeActiveNotebookEditor(listener, thisArgs, disposables); }, get visibleNotebookEditors() { checkProposedApiEnabled(extension); return extHostNotebook.visibleNotebookEditors; }, get onDidChangeVisibleNotebookEditors() { checkProposedApiEnabled(extension); return extHostNotebook.onDidChangeVisibleNotebookEditors; }, onDidChangeNotebookEditorSelection(listener, thisArgs?, disposables?) { checkProposedApiEnabled(extension); return extHostNotebook.onDidChangeNotebookEditorSelection(listener, thisArgs, disposables); }, onDidChangeNotebookEditorVisibleRanges(listener, thisArgs?, disposables?) { checkProposedApiEnabled(extension); return extHostNotebook.onDidChangeNotebookEditorVisibleRanges(listener, thisArgs, disposables); }, showNotebookDocument(uriOrDocument, options?) { checkProposedApiEnabled(extension); return extHostNotebook.showNotebookDocument(uriOrDocument, options); }, registerExternalUriOpener(id: string, opener: vscode.ExternalUriOpener, metadata: vscode.ExternalUriOpenerMetadata) { checkProposedApiEnabled(extension); return extHostUriOpeners.registerExternalUriOpener(extension.identifier, id, opener, metadata); }, get openEditors() { checkProposedApiEnabled(extension); return extHostEditorTabs.tabs; }, get onDidChangeOpenEditors() { checkProposedApiEnabled(extension); return extHostEditorTabs.onDidChangeTabs; } }; // namespace: workspace const workspace: typeof vscode.workspace = { get rootPath() { extHostApiDeprecation.report('workspace.rootPath', extension, `Please use 'workspace.workspaceFolders' instead. More details: https://aka.ms/vscode-eliminating-rootpath`); return extHostWorkspace.getPath(); }, set rootPath(value) { throw errors.readonly(); }, getWorkspaceFolder(resource) { return extHostWorkspace.getWorkspaceFolder(resource); }, get workspaceFolders() { return extHostWorkspace.getWorkspaceFolders(); }, get name() { return extHostWorkspace.name; }, set name(value) { throw errors.readonly(); }, get workspaceFile() { return extHostWorkspace.workspaceFile; }, set workspaceFile(value) { throw errors.readonly(); }, updateWorkspaceFolders: (index, deleteCount, ...workspaceFoldersToAdd) => { return extHostWorkspace.updateWorkspaceFolders(extension, index, deleteCount || 0, ...workspaceFoldersToAdd); }, onDidChangeWorkspaceFolders: function (listener, thisArgs?, disposables?) { return extHostWorkspace.onDidChangeWorkspace(listener, thisArgs, disposables); }, asRelativePath: (pathOrUri, includeWorkspace?) => { return extHostWorkspace.getRelativePath(pathOrUri, includeWorkspace); }, findFiles: (include, exclude, maxResults?, token?) => { // Note, undefined/null have different meanings on "exclude" return extHostWorkspace.findFiles(typeConverters.GlobPattern.from(include), typeConverters.GlobPattern.from(exclude), maxResults, extension.identifier, token); }, findTextInFiles: (query: vscode.TextSearchQuery, optionsOrCallback: vscode.FindTextInFilesOptions | ((result: vscode.TextSearchResult) => void), callbackOrToken?: vscode.CancellationToken | ((result: vscode.TextSearchResult) => void), token?: vscode.CancellationToken) => { let options: vscode.FindTextInFilesOptions; let callback: (result: vscode.TextSearchResult) => void; if (typeof optionsOrCallback === 'object') { options = optionsOrCallback; callback = callbackOrToken as (result: vscode.TextSearchResult) => void; } else { options = {}; callback = optionsOrCallback; token = callbackOrToken as vscode.CancellationToken; } return extHostWorkspace.findTextInFiles(query, options || {}, callback, extension.identifier, token); }, saveAll: (includeUntitled?) => { return extHostWorkspace.saveAll(includeUntitled); }, applyEdit(edit: vscode.WorkspaceEdit): Thenable<boolean> { return extHostBulkEdits.applyWorkspaceEdit(edit); }, createFileSystemWatcher: (pattern, ignoreCreate, ignoreChange, ignoreDelete): vscode.FileSystemWatcher => { return extHostFileSystemEvent.createFileSystemWatcher(typeConverters.GlobPattern.from(pattern), ignoreCreate, ignoreChange, ignoreDelete); }, get textDocuments() { return extHostDocuments.getAllDocumentData().map(data => data.document); }, set textDocuments(value) { throw errors.readonly(); }, openTextDocument(uriOrFileNameOrOptions?: vscode.Uri | string | { language?: string; content?: string; }) { let uriPromise: Thenable<URI>; const options = uriOrFileNameOrOptions as { language?: string; content?: string; }; if (typeof uriOrFileNameOrOptions === 'string') { uriPromise = Promise.resolve(URI.file(uriOrFileNameOrOptions)); } else if (URI.isUri(uriOrFileNameOrOptions)) { uriPromise = Promise.resolve(uriOrFileNameOrOptions); } else if (!options || typeof options === 'object') { uriPromise = extHostDocuments.createDocumentData(options); } else { throw new Error('illegal argument - uriOrFileNameOrOptions'); } return uriPromise.then(uri => { return extHostDocuments.ensureDocumentData(uri).then(documentData => { return documentData.document; }); }); }, onDidOpenTextDocument: (listener, thisArgs?, disposables?) => { return extHostDocuments.onDidAddDocument(listener, thisArgs, disposables); }, onDidCloseTextDocument: (listener, thisArgs?, disposables?) => { return extHostDocuments.onDidRemoveDocument(listener, thisArgs, disposables); }, onDidChangeTextDocument: (listener, thisArgs?, disposables?) => { return extHostDocuments.onDidChangeDocument(listener, thisArgs, disposables); }, onDidSaveTextDocument: (listener, thisArgs?, disposables?) => { return extHostDocuments.onDidSaveDocument(listener, thisArgs, disposables); }, onWillSaveTextDocument: (listener, thisArgs?, disposables?) => { return extHostDocumentSaveParticipant.getOnWillSaveTextDocumentEvent(extension)(listener, thisArgs, disposables); }, onDidChangeConfiguration: (listener: (_: any) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) => { return configProvider.onDidChangeConfiguration(listener, thisArgs, disposables); }, getConfiguration(section?: string, scope?: vscode.ConfigurationScope | null): vscode.WorkspaceConfiguration { scope = arguments.length === 1 ? undefined : scope; return configProvider.getConfiguration(section, scope, extension); }, registerTextDocumentContentProvider(scheme: string, provider: vscode.TextDocumentContentProvider) { return extHostDocumentContentProviders.registerTextDocumentContentProvider(scheme, provider); }, registerTaskProvider: (type: string, provider: vscode.TaskProvider) => { extHostApiDeprecation.report('window.registerTaskProvider', extension, `Use the corresponding function on the 'tasks' namespace instead`); return extHostTask.registerTaskProvider(extension, type, provider); }, registerFileSystemProvider(scheme, provider, options) { return extHostFileSystem.registerFileSystemProvider(extension.identifier, scheme, provider, options); }, get fs() { return extHostConsumerFileSystem.value; }, registerFileSearchProvider: (scheme: string, provider: vscode.FileSearchProvider) => { checkProposedApiEnabled(extension); return extHostSearch.registerFileSearchProvider(scheme, provider); }, registerTextSearchProvider: (scheme: string, provider: vscode.TextSearchProvider) => { checkProposedApiEnabled(extension); return extHostSearch.registerTextSearchProvider(scheme, provider); }, registerRemoteAuthorityResolver: (authorityPrefix: string, resolver: vscode.RemoteAuthorityResolver) => { checkProposedApiEnabled(extension); return extensionService.registerRemoteAuthorityResolver(authorityPrefix, resolver); }, registerResourceLabelFormatter: (formatter: vscode.ResourceLabelFormatter) => { checkProposedApiEnabled(extension); return extHostLabelService.$registerResourceLabelFormatter(formatter); }, onDidCreateFiles: (listener, thisArg, disposables) => { return extHostFileSystemEvent.onDidCreateFile(listener, thisArg, disposables); }, onDidDeleteFiles: (listener, thisArg, disposables) => { return extHostFileSystemEvent.onDidDeleteFile(listener, thisArg, disposables); }, onDidRenameFiles: (listener, thisArg, disposables) => { return extHostFileSystemEvent.onDidRenameFile(listener, thisArg, disposables); }, onWillCreateFiles: (listener: (e: vscode.FileWillCreateEvent) => any, thisArg?: any, disposables?: vscode.Disposable[]) => { return extHostFileSystemEvent.getOnWillCreateFileEvent(extension)(listener, thisArg, disposables); }, onWillDeleteFiles: (listener: (e: vscode.FileWillDeleteEvent) => any, thisArg?: any, disposables?: vscode.Disposable[]) => { return extHostFileSystemEvent.getOnWillDeleteFileEvent(extension)(listener, thisArg, disposables); }, onWillRenameFiles: (listener: (e: vscode.FileWillRenameEvent) => any, thisArg?: any, disposables?: vscode.Disposable[]) => { return extHostFileSystemEvent.getOnWillRenameFileEvent(extension)(listener, thisArg, disposables); }, openTunnel: (forward: vscode.TunnelOptions) => { checkProposedApiEnabled(extension); return extHostTunnelService.openTunnel(extension, forward).then(value => { if (!value) { throw new Error('cannot open tunnel'); } return value; }); }, get tunnels() { checkProposedApiEnabled(extension); return extHostTunnelService.getTunnels(); }, onDidChangeTunnels: (listener, thisArg?, disposables?) => { checkProposedApiEnabled(extension); return extHostTunnelService.onDidChangeTunnels(listener, thisArg, disposables); }, registerPortAttributesProvider: (portSelector: { pid?: number, portRange?: [number, number], commandMatcher?: RegExp }, provider: vscode.PortAttributesProvider) => { checkProposedApiEnabled(extension); return extHostTunnelService.registerPortsAttributesProvider(portSelector, provider); }, registerTimelineProvider: (scheme: string | string[], provider: vscode.TimelineProvider) => { checkProposedApiEnabled(extension); return extHostTimeline.registerTimelineProvider(scheme, provider, extension.identifier, extHostCommands.converter); }, get trustState() { checkProposedApiEnabled(extension); return extHostWorkspace.trustState; }, requestWorkspaceTrust: (options?: vscode.WorkspaceTrustRequestOptions) => { checkProposedApiEnabled(extension); return extHostWorkspace.requestWorkspaceTrust(options); }, onDidChangeWorkspaceTrustState: (listener, thisArgs?, disposables?) => { return extHostWorkspace.onDidChangeWorkspaceTrustState(listener, thisArgs, disposables); } }; // namespace: scm const scm: typeof vscode.scm = { get inputBox() { extHostApiDeprecation.report('scm.inputBox', extension, `Use 'SourceControl.inputBox' instead`); return extHostSCM.getLastInputBox(extension)!; // Strict null override - Deprecated api }, createSourceControl(id: string, label: string, rootUri?: vscode.Uri) { return extHostSCM.createSourceControl(extension, id, label, rootUri); } }; // namespace: comments const comments: typeof vscode.comments = { createCommentController(id: string, label: string) { return extHostComment.createCommentController(extension, id, label); } }; // namespace: debug const debug: typeof vscode.debug = { get activeDebugSession() { return extHostDebugService.activeDebugSession; }, get activeDebugConsole() { return extHostDebugService.activeDebugConsole; }, get breakpoints() { return extHostDebugService.breakpoints; }, onDidStartDebugSession(listener, thisArg?, disposables?) { return extHostDebugService.onDidStartDebugSession(listener, thisArg, disposables); }, onDidTerminateDebugSession(listener, thisArg?, disposables?) { return extHostDebugService.onDidTerminateDebugSession(listener, thisArg, disposables); }, onDidChangeActiveDebugSession(listener, thisArg?, disposables?) { return extHostDebugService.onDidChangeActiveDebugSession(listener, thisArg, disposables); }, onDidReceiveDebugSessionCustomEvent(listener, thisArg?, disposables?) { return extHostDebugService.onDidReceiveDebugSessionCustomEvent(listener, thisArg, disposables); }, onDidChangeBreakpoints(listener, thisArgs?, disposables?) { return extHostDebugService.onDidChangeBreakpoints(listener, thisArgs, disposables); }, registerDebugConfigurationProvider(debugType: string, provider: vscode.DebugConfigurationProvider, triggerKind?: vscode.DebugConfigurationProviderTriggerKind) { return extHostDebugService.registerDebugConfigurationProvider(debugType, provider, triggerKind || extHostTypes.DebugConfigurationProviderTriggerKind.Initial); }, registerDebugAdapterDescriptorFactory(debugType: string, factory: vscode.DebugAdapterDescriptorFactory) { return extHostDebugService.registerDebugAdapterDescriptorFactory(extension, debugType, factory); }, registerDebugAdapterTrackerFactory(debugType: string, factory: vscode.DebugAdapterTrackerFactory) { return extHostDebugService.registerDebugAdapterTrackerFactory(debugType, factory); }, startDebugging(folder: vscode.WorkspaceFolder | undefined, nameOrConfig: string | vscode.DebugConfiguration, parentSessionOrOptions?: vscode.DebugSession | vscode.DebugSessionOptions) { if (!parentSessionOrOptions || (typeof parentSessionOrOptions === 'object' && 'configuration' in parentSessionOrOptions)) { return extHostDebugService.startDebugging(folder, nameOrConfig, { parentSession: parentSessionOrOptions }); } return extHostDebugService.startDebugging(folder, nameOrConfig, parentSessionOrOptions || {}); }, stopDebugging(session?: vscode.DebugSession) { return extHostDebugService.stopDebugging(session); }, addBreakpoints(breakpoints: vscode.Breakpoint[]) { return extHostDebugService.addBreakpoints(breakpoints); }, removeBreakpoints(breakpoints: vscode.Breakpoint[]) { return extHostDebugService.removeBreakpoints(breakpoints); }, asDebugSourceUri(source: vscode.DebugProtocolSource, session?: vscode.DebugSession): vscode.Uri { return extHostDebugService.asDebugSourceUri(source, session); } }; const tasks: typeof vscode.tasks = { registerTaskProvider: (type: string, provider: vscode.TaskProvider) => { return extHostTask.registerTaskProvider(extension, type, provider); }, fetchTasks: (filter?: vscode.TaskFilter): Thenable<vscode.Task[]> => { return extHostTask.fetchTasks(filter); }, executeTask: (task: vscode.Task): Thenable<vscode.TaskExecution> => { return extHostTask.executeTask(extension, task); }, get taskExecutions(): vscode.TaskExecution[] { return extHostTask.taskExecutions; }, onDidStartTask: (listeners, thisArgs?, disposables?) => { return extHostTask.onDidStartTask(listeners, thisArgs, disposables); }, onDidEndTask: (listeners, thisArgs?, disposables?) => { return extHostTask.onDidEndTask(listeners, thisArgs, disposables); }, onDidStartTaskProcess: (listeners, thisArgs?, disposables?) => { return extHostTask.onDidStartTaskProcess(listeners, thisArgs, disposables); }, onDidEndTaskProcess: (listeners, thisArgs?, disposables?) => { return extHostTask.onDidEndTaskProcess(listeners, thisArgs, disposables); } }; // namespace: notebook const notebook: typeof vscode.notebook = { openNotebookDocument: (uriComponents) => { checkProposedApiEnabled(extension); return extHostNotebook.openNotebookDocument(uriComponents); }, get onDidOpenNotebookDocument(): Event<vscode.NotebookDocument> { checkProposedApiEnabled(extension); return extHostNotebook.onDidOpenNotebookDocument; }, get onDidCloseNotebookDocument(): Event<vscode.NotebookDocument> { checkProposedApiEnabled(extension); return extHostNotebook.onDidCloseNotebookDocument; }, get onDidSaveNotebookDocument(): Event<vscode.NotebookDocument> { checkProposedApiEnabled(extension); return extHostNotebook.onDidSaveNotebookDocument; }, get notebookDocuments(): vscode.NotebookDocument[] { checkProposedApiEnabled(extension); return extHostNotebook.notebookDocuments.map(d => d.notebookDocument); }, get onDidChangeActiveNotebookKernel() { checkProposedApiEnabled(extension); return extHostNotebook.onDidChangeActiveNotebookKernel; }, registerNotebookSerializer(viewType, serializer, options) { checkProposedApiEnabled(extension); return extHostNotebook.registerNotebookSerializer(extension, viewType, serializer, options); }, registerNotebookContentProvider: (viewType: string, provider: vscode.NotebookContentProvider, options?: { transientOutputs: boolean; transientMetadata: { [K in keyof vscode.NotebookCellMetadata]?: boolean } }) => { checkProposedApiEnabled(extension); return extHostNotebook.registerNotebookContentProvider(extension, viewType, provider, options); }, registerNotebookKernelProvider: (selector: vscode.NotebookDocumentFilter, provider: vscode.NotebookKernelProvider) => { checkProposedApiEnabled(extension); return extHostNotebook.registerNotebookKernelProvider(extension, selector, provider); }, createNotebookEditorDecorationType(options: vscode.NotebookDecorationRenderOptions): vscode.NotebookEditorDecorationType { checkProposedApiEnabled(extension); return extHostNotebook.createNotebookEditorDecorationType(options); }, onDidChangeNotebookDocumentMetadata(listener, thisArgs?, disposables?) { checkProposedApiEnabled(extension); return extHostNotebook.onDidChangeNotebookDocumentMetadata(listener, thisArgs, disposables); }, onDidChangeNotebookCells(listener, thisArgs?, disposables?) { checkProposedApiEnabled(extension); return extHostNotebook.onDidChangeNotebookCells(listener, thisArgs, disposables); }, onDidChangeCellExecutionState(listener, thisArgs?, disposables?) { checkProposedApiEnabled(extension); return extHostNotebook.onDidChangeNotebookCellExecutionState(listener, thisArgs, disposables); }, onDidChangeCellOutputs(listener, thisArgs?, disposables?) { checkProposedApiEnabled(extension); return extHostNotebook.onDidChangeCellOutputs(listener, thisArgs, disposables); }, onDidChangeCellMetadata(listener, thisArgs?, disposables?) { checkProposedApiEnabled(extension); return extHostNotebook.onDidChangeCellMetadata(listener, thisArgs, disposables); }, createConcatTextDocument(notebook, selector) { checkProposedApiEnabled(extension); return new ExtHostNotebookConcatDocument(extHostNotebook, extHostDocuments, notebook, selector); }, createCellStatusBarItem(cell: vscode.NotebookCell, alignment?: vscode.NotebookCellStatusBarAlignment, priority?: number): vscode.NotebookCellStatusBarItem { checkProposedApiEnabled(extension); return extHostNotebook.createNotebookCellStatusBarItemInternal(cell, alignment, priority); }, createNotebookCellExecutionTask(uri: vscode.Uri, index: number, kernelId: string): vscode.NotebookCellExecutionTask | undefined { checkProposedApiEnabled(extension); return extHostNotebook.createNotebookCellExecution(uri, index, kernelId); }, createNotebookKernel(options) { checkProposedApiEnabled(extension); return extHostNotebookKernels.createKernel(extension, options); } }; return <typeof vscode>{ version: initData.version, // namespaces authentication, commands, comments, debug, env, extensions, languages, notebook, scm, tasks, test, window, workspace, // types Breakpoint: extHostTypes.Breakpoint, CallHierarchyIncomingCall: extHostTypes.CallHierarchyIncomingCall, CallHierarchyItem: extHostTypes.CallHierarchyItem, CallHierarchyOutgoingCall: extHostTypes.CallHierarchyOutgoingCall, CancellationError: errors.CancellationError, CancellationTokenSource: CancellationTokenSource, CandidatePortSource: CandidatePortSource, CodeAction: extHostTypes.CodeAction, CodeActionKind: extHostTypes.CodeActionKind, CodeActionTriggerKind: extHostTypes.CodeActionTriggerKind, CodeLens: extHostTypes.CodeLens, Color: extHostTypes.Color, ColorInformation: extHostTypes.ColorInformation, ColorPresentation: extHostTypes.ColorPresentation, ColorThemeKind: extHostTypes.ColorThemeKind, CommentMode: extHostTypes.CommentMode, CommentThreadCollapsibleState: extHostTypes.CommentThreadCollapsibleState, CompletionItem: extHostTypes.CompletionItem, CompletionItemKind: extHostTypes.CompletionItemKind, CompletionItemTag: extHostTypes.CompletionItemTag, CompletionList: extHostTypes.CompletionList, CompletionTriggerKind: extHostTypes.CompletionTriggerKind, ConfigurationTarget: extHostTypes.ConfigurationTarget, CustomExecution: extHostTypes.CustomExecution, DebugAdapterExecutable: extHostTypes.DebugAdapterExecutable, DebugAdapterInlineImplementation: extHostTypes.DebugAdapterInlineImplementation, DebugAdapterNamedPipeServer: extHostTypes.DebugAdapterNamedPipeServer, DebugAdapterServer: extHostTypes.DebugAdapterServer, DebugConfigurationProviderTriggerKind: extHostTypes.DebugConfigurationProviderTriggerKind, DebugConsoleMode: extHostTypes.DebugConsoleMode, DecorationRangeBehavior: extHostTypes.DecorationRangeBehavior, Diagnostic: extHostTypes.Diagnostic, DiagnosticRelatedInformation: extHostTypes.DiagnosticRelatedInformation, DiagnosticSeverity: extHostTypes.DiagnosticSeverity, DiagnosticTag: extHostTypes.DiagnosticTag, Disposable: extHostTypes.Disposable, DocumentHighlight: extHostTypes.DocumentHighlight, DocumentHighlightKind: extHostTypes.DocumentHighlightKind, DocumentLink: extHostTypes.DocumentLink, DocumentSymbol: extHostTypes.DocumentSymbol, EndOfLine: extHostTypes.EndOfLine, EnvironmentVariableMutatorType: extHostTypes.EnvironmentVariableMutatorType, EvaluatableExpression: extHostTypes.EvaluatableExpression, InlineValueText: extHostTypes.InlineValueText, InlineValueVariableLookup: extHostTypes.InlineValueVariableLookup, InlineValueEvaluatableExpression: extHostTypes.InlineValueEvaluatableExpression, EventEmitter: Emitter, ExtensionKind: extHostTypes.ExtensionKind, ExtensionMode: extHostTypes.ExtensionMode, ExternalUriOpenerPriority: extHostTypes.ExternalUriOpenerPriority, FileChangeType: extHostTypes.FileChangeType, FileDecoration: extHostTypes.FileDecoration, FileSystemError: extHostTypes.FileSystemError, FileType: files.FileType, FoldingRange: extHostTypes.FoldingRange, FoldingRangeKind: extHostTypes.FoldingRangeKind, FunctionBreakpoint: extHostTypes.FunctionBreakpoint, Hover: extHostTypes.Hover, IndentAction: languageConfiguration.IndentAction, Location: extHostTypes.Location, MarkdownString: extHostTypes.MarkdownString, OverviewRulerLane: OverviewRulerLane, ParameterInformation: extHostTypes.ParameterInformation, PortAutoForwardAction: extHostTypes.PortAutoForwardAction, Position: extHostTypes.Position, ProcessExecution: extHostTypes.ProcessExecution, ProgressLocation: extHostTypes.ProgressLocation, QuickInputButtons: extHostTypes.QuickInputButtons, Range: extHostTypes.Range, RelativePattern: extHostTypes.RelativePattern, Selection: extHostTypes.Selection, SelectionRange: extHostTypes.SelectionRange, SemanticTokens: extHostTypes.SemanticTokens, SemanticTokensBuilder: extHostTypes.SemanticTokensBuilder, SemanticTokensEdit: extHostTypes.SemanticTokensEdit, SemanticTokensEdits: extHostTypes.SemanticTokensEdits, SemanticTokensLegend: extHostTypes.SemanticTokensLegend, ShellExecution: extHostTypes.ShellExecution, ShellQuoting: extHostTypes.ShellQuoting, SignatureHelp: extHostTypes.SignatureHelp, SignatureHelpTriggerKind: extHostTypes.SignatureHelpTriggerKind, SignatureInformation: extHostTypes.SignatureInformation, SnippetString: extHostTypes.SnippetString, SourceBreakpoint: extHostTypes.SourceBreakpoint, StandardTokenType: extHostTypes.StandardTokenType, StatusBarAlignment: extHostTypes.StatusBarAlignment, SymbolInformation: extHostTypes.SymbolInformation, SymbolKind: extHostTypes.SymbolKind, SymbolTag: extHostTypes.SymbolTag, Task: extHostTypes.Task, TaskGroup: extHostTypes.TaskGroup, TaskPanelKind: extHostTypes.TaskPanelKind, TaskRevealKind: extHostTypes.TaskRevealKind, TaskScope: extHostTypes.TaskScope, TextDocumentSaveReason: extHostTypes.TextDocumentSaveReason, TextEdit: extHostTypes.TextEdit, TextEditorCursorStyle: TextEditorCursorStyle, TextEditorLineNumbersStyle: extHostTypes.TextEditorLineNumbersStyle, TextEditorRevealType: extHostTypes.TextEditorRevealType, TextEditorSelectionChangeKind: extHostTypes.TextEditorSelectionChangeKind, ThemeColor: extHostTypes.ThemeColor, ThemeIcon: extHostTypes.ThemeIcon, TreeItem: extHostTypes.TreeItem, TreeItemCollapsibleState: extHostTypes.TreeItemCollapsibleState, UIKind: UIKind, Uri: URI, ViewColumn: extHostTypes.ViewColumn, WorkspaceEdit: extHostTypes.WorkspaceEdit, // proposed api types InlineHint: extHostTypes.InlineHint, InlineHintKind: extHostTypes.InlineHintKind, RemoteAuthorityResolverError: extHostTypes.RemoteAuthorityResolverError, ResolvedAuthority: extHostTypes.ResolvedAuthority, SourceControlInputBoxValidationType: extHostTypes.SourceControlInputBoxValidationType, ExtensionRuntime: extHostTypes.ExtensionRuntime, TimelineItem: extHostTypes.TimelineItem, NotebookCellRange: extHostTypes.NotebookCellRange, NotebookCellKind: extHostTypes.NotebookCellKind, NotebookCellExecutionState: extHostTypes.NotebookCellExecutionState, NotebookDocumentMetadata: extHostTypes.NotebookDocumentMetadata, NotebookCellMetadata: extHostTypes.NotebookCellMetadata, NotebookCellData: extHostTypes.NotebookCellData, NotebookData: extHostTypes.NotebookData, NotebookCellStatusBarAlignment: extHostTypes.NotebookCellStatusBarAlignment, NotebookEditorRevealType: extHostTypes.NotebookEditorRevealType, NotebookCellOutput: extHostTypes.NotebookCellOutput, NotebookCellOutputItem: extHostTypes.NotebookCellOutputItem, LinkedEditingRanges: extHostTypes.LinkedEditingRanges, TestItem: extHostTypes.TestItem, TestResultState: extHostTypes.TestResultState, TestMessage: extHostTypes.TestMessage, TestMessageSeverity: extHostTypes.TestMessageSeverity, WorkspaceTrustState: extHostTypes.WorkspaceTrustState }; }; }
src/vs/workbench/api/common/extHost.api.impl.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.0015349736204370856, 0.00019698702089954168, 0.000158793744049035, 0.0001719257707009092, 0.00015374431677628309 ]
{ "id": 7, "code_window": [ "\n", "\t\tlet isDisposed = false;\n", "\t\tconst commandDisposables = new DisposableStore();\n", "\n", "\t\tconst emitter = new Emitter<boolean>();\n", "\t\tthis._kernelData.set(handle, { id: options.id, executeHandler: options.executeHandler, selected: false, onDidChangeSelection: emitter });\n", "\n", "\t\tconst data: INotebookKernelDto2 = {\n", "\t\t\tid: options.id,\n", "\t\t\tselector: options.selector,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst emitter = new Emitter<{ selected: boolean, uri: URI }>();\n", "\t\tthis._kernelData.set(handle, { id: options.id, executeHandler: options.executeHandler, onDidChangeSelection: emitter });\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 41 }
{ "comments": { // symbols used for start and end a block comment. Remove this entry if your language does not support block comments "blockComment": [ "<!--", "-->" ] }, // symbols used as brackets "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ { "open": "{", "close": "}" }, { "open": "[", "close": "]" }, { "open": "(", "close": ")" }, { "open": "<", "close": ">", "notIn": [ "string" ] } ], "surroundingPairs": [ ["(", ")"], ["[", "]"], ["`", "`"], ["_", "_"], ["*", "*"] ], "folding": { "offSide": true, "markers": { "start": "^\\s*<!--\\s*#?region\\b.*-->", "end": "^\\s*<!--\\s*#?endregion\\b.*-->" } } }
extensions/markdown-basics/language-configuration.json
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.0001729970972519368, 0.00017102390120271593, 0.00016770038928370923, 0.00017191395454574376, 0.0000019710653305082815 ]
{ "id": 7, "code_window": [ "\n", "\t\tlet isDisposed = false;\n", "\t\tconst commandDisposables = new DisposableStore();\n", "\n", "\t\tconst emitter = new Emitter<boolean>();\n", "\t\tthis._kernelData.set(handle, { id: options.id, executeHandler: options.executeHandler, selected: false, onDidChangeSelection: emitter });\n", "\n", "\t\tconst data: INotebookKernelDto2 = {\n", "\t\t\tid: options.id,\n", "\t\t\tselector: options.selector,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst emitter = new Emitter<{ selected: boolean, uri: URI }>();\n", "\t\tthis._kernelData.set(handle, { id: options.id, executeHandler: options.executeHandler, onDidChangeSelection: emitter });\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event, Disposable, EventEmitter } from 'vscode'; import { dirname, sep } from 'path'; import { Readable } from 'stream'; import { promises as fs, createReadStream } from 'fs'; import * as byline from 'byline'; export function log(...args: any[]): void { console.log.apply(console, ['git:', ...args]); } export interface IDisposable { dispose(): void; } export function dispose<T extends IDisposable>(disposables: T[]): T[] { disposables.forEach(d => d.dispose()); return []; } export function toDisposable(dispose: () => void): IDisposable { return { dispose }; } export function combinedDisposable(disposables: IDisposable[]): IDisposable { return toDisposable(() => dispose(disposables)); } export const EmptyDisposable = toDisposable(() => null); export function fireEvent<T>(event: Event<T>): Event<T> { return (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]) => event(_ => (listener as any).call(thisArgs), null, disposables); } export function mapEvent<I, O>(event: Event<I>, map: (i: I) => O): Event<O> { return (listener: (e: O) => any, thisArgs?: any, disposables?: Disposable[]) => event(i => listener.call(thisArgs, map(i)), null, disposables); } export function filterEvent<T>(event: Event<T>, filter: (e: T) => boolean): Event<T> { return (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables); } export function anyEvent<T>(...events: Event<T>[]): Event<T> { return (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]) => { const result = combinedDisposable(events.map(event => event(i => listener.call(thisArgs, i)))); if (disposables) { disposables.push(result); } return result; }; } export function done<T>(promise: Promise<T>): Promise<void> { return promise.then<void>(() => undefined); } export function onceEvent<T>(event: Event<T>): Event<T> { return (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]) => { const result = event(e => { result.dispose(); return listener.call(thisArgs, e); }, null, disposables); return result; }; } export function debounceEvent<T>(event: Event<T>, delay: number): Event<T> { return (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]) => { let timer: NodeJS.Timer; return event(e => { clearTimeout(timer); timer = setTimeout(() => listener.call(thisArgs, e), delay); }, null, disposables); }; } export function eventToPromise<T>(event: Event<T>): Promise<T> { return new Promise<T>(c => onceEvent(event)(c)); } export function once(fn: (...args: any[]) => any): (...args: any[]) => any { let didRun = false; return (...args) => { if (didRun) { return; } return fn(...args); }; } export function assign<T>(destination: T, ...sources: any[]): T { for (const source of sources) { Object.keys(source).forEach(key => (destination as any)[key] = source[key]); } return destination; } export function uniqBy<T>(arr: T[], fn: (el: T) => string): T[] { const seen = Object.create(null); return arr.filter(el => { const key = fn(el); if (seen[key]) { return false; } seen[key] = true; return true; }); } export function groupBy<T>(arr: T[], fn: (el: T) => string): { [key: string]: T[] } { return arr.reduce((result, el) => { const key = fn(el); result[key] = [...(result[key] || []), el]; return result; }, Object.create(null)); } export async function mkdirp(path: string, mode?: number): Promise<boolean> { const mkdir = async () => { try { await fs.mkdir(path, mode); } catch (err) { if (err.code === 'EEXIST') { const stat = await fs.stat(path); if (stat.isDirectory()) { return; } throw new Error(`'${path}' exists and is not a directory.`); } throw err; } }; // is root? if (path === dirname(path)) { return true; } try { await mkdir(); } catch (err) { if (err.code !== 'ENOENT') { throw err; } await mkdirp(dirname(path), mode); await mkdir(); } return true; } export function uniqueFilter<T>(keyFn: (t: T) => string): (t: T) => boolean { const seen: { [key: string]: boolean; } = Object.create(null); return element => { const key = keyFn(element); if (seen[key]) { return false; } seen[key] = true; return true; }; } export function find<T>(array: T[], fn: (t: T) => boolean): T | undefined { let result: T | undefined = undefined; array.some(e => { if (fn(e)) { result = e; return true; } return false; }); return result; } export async function grep(filename: string, pattern: RegExp): Promise<boolean> { return new Promise<boolean>((c, e) => { const fileStream = createReadStream(filename, { encoding: 'utf8' }); const stream = byline(fileStream); stream.on('data', (line: string) => { if (pattern.test(line)) { fileStream.close(); c(true); } }); stream.on('error', e); stream.on('end', () => c(false)); }); } export function readBytes(stream: Readable, bytes: number): Promise<Buffer> { return new Promise<Buffer>((complete, error) => { let done = false; let buffer = Buffer.allocUnsafe(bytes); let bytesRead = 0; stream.on('data', (data: Buffer) => { let bytesToRead = Math.min(bytes - bytesRead, data.length); data.copy(buffer, bytesRead, 0, bytesToRead); bytesRead += bytesToRead; if (bytesRead === bytes) { (stream as any).destroy(); // Will trigger the close event eventually } }); stream.on('error', (e: Error) => { if (!done) { done = true; error(e); } }); stream.on('close', () => { if (!done) { done = true; complete(buffer.slice(0, bytesRead)); } }); }); } export const enum Encoding { UTF8 = 'utf8', UTF16be = 'utf16be', UTF16le = 'utf16le' } export function detectUnicodeEncoding(buffer: Buffer): Encoding | null { if (buffer.length < 2) { return null; } const b0 = buffer.readUInt8(0); const b1 = buffer.readUInt8(1); if (b0 === 0xFE && b1 === 0xFF) { return Encoding.UTF16be; } if (b0 === 0xFF && b1 === 0xFE) { return Encoding.UTF16le; } if (buffer.length < 3) { return null; } const b2 = buffer.readUInt8(2); if (b0 === 0xEF && b1 === 0xBB && b2 === 0xBF) { return Encoding.UTF8; } return null; } function isWindowsPath(path: string): boolean { return /^[a-zA-Z]:\\/.test(path); } export function isDescendant(parent: string, descendant: string): boolean { if (parent === descendant) { return true; } if (parent.charAt(parent.length - 1) !== sep) { parent += sep; } // Windows is case insensitive if (isWindowsPath(parent)) { parent = parent.toLowerCase(); descendant = descendant.toLowerCase(); } return descendant.startsWith(parent); } export function pathEquals(a: string, b: string): boolean { // Windows is case insensitive if (isWindowsPath(a)) { a = a.toLowerCase(); b = b.toLowerCase(); } return a === b; } export function* splitInChunks(array: string[], maxChunkLength: number): IterableIterator<string[]> { let current: string[] = []; let length = 0; for (const value of array) { let newLength = length + value.length; if (newLength > maxChunkLength && current.length > 0) { yield current; current = []; newLength = value.length; } current.push(value); length = newLength; } if (current.length > 0) { yield current; } } interface ILimitedTaskFactory<T> { factory: () => Promise<T>; c: (value: T | Promise<T>) => void; e: (error?: any) => void; } export class Limiter<T> { private runningPromises: number; private maxDegreeOfParalellism: number; private outstandingPromises: ILimitedTaskFactory<T>[]; constructor(maxDegreeOfParalellism: number) { this.maxDegreeOfParalellism = maxDegreeOfParalellism; this.outstandingPromises = []; this.runningPromises = 0; } queue(factory: () => Promise<T>): Promise<T> { return new Promise<T>((c, e) => { this.outstandingPromises.push({ factory, c, e }); this.consume(); }); } private consume(): void { while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) { const iLimitedTask = this.outstandingPromises.shift()!; this.runningPromises++; const promise = iLimitedTask.factory(); promise.then(iLimitedTask.c, iLimitedTask.e); promise.then(() => this.consumed(), () => this.consumed()); } } private consumed(): void { this.runningPromises--; if (this.outstandingPromises.length > 0) { this.consume(); } } } type Completion<T> = { success: true, value: T } | { success: false, err: any }; export class PromiseSource<T> { private _onDidComplete = new EventEmitter<Completion<T>>(); private _promise: Promise<T> | undefined; get promise(): Promise<T> { if (this._promise) { return this._promise; } return eventToPromise(this._onDidComplete.event).then(completion => { if (completion.success) { return completion.value; } else { throw completion.err; } }); } resolve(value: T): void { if (!this._promise) { this._promise = Promise.resolve(value); this._onDidComplete.fire({ success: true, value }); } } reject(err: any): void { if (!this._promise) { this._promise = Promise.reject(err); this._onDidComplete.fire({ success: false, err }); } } } export namespace Versions { declare type VersionComparisonResult = -1 | 0 | 1; export interface Version { major: number; minor: number; patch: number; pre?: string; } export function compare(v1: string | Version, v2: string | Version): VersionComparisonResult { if (typeof v1 === 'string') { v1 = fromString(v1); } if (typeof v2 === 'string') { v2 = fromString(v2); } if (v1.major > v2.major) { return 1; } if (v1.major < v2.major) { return -1; } if (v1.minor > v2.minor) { return 1; } if (v1.minor < v2.minor) { return -1; } if (v1.patch > v2.patch) { return 1; } if (v1.patch < v2.patch) { return -1; } if (v1.pre === undefined && v2.pre !== undefined) { return 1; } if (v1.pre !== undefined && v2.pre === undefined) { return -1; } if (v1.pre !== undefined && v2.pre !== undefined) { return v1.pre.localeCompare(v2.pre) as VersionComparisonResult; } return 0; } export function from(major: string | number, minor: string | number, patch?: string | number, pre?: string): Version { return { major: typeof major === 'string' ? parseInt(major, 10) : major, minor: typeof minor === 'string' ? parseInt(minor, 10) : minor, patch: patch === undefined || patch === null ? 0 : typeof patch === 'string' ? parseInt(patch, 10) : patch, pre: pre, }; } export function fromString(version: string): Version { const [ver, pre] = version.split('-'); const [major, minor, patch] = ver.split('.'); return from(major, minor, patch, pre); } }
extensions/git/src/util.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.003922383766621351, 0.00029817046015523374, 0.00016444367065560073, 0.00017228121578227729, 0.0006183486548252404 ]
{ "id": 7, "code_window": [ "\n", "\t\tlet isDisposed = false;\n", "\t\tconst commandDisposables = new DisposableStore();\n", "\n", "\t\tconst emitter = new Emitter<boolean>();\n", "\t\tthis._kernelData.set(handle, { id: options.id, executeHandler: options.executeHandler, selected: false, onDidChangeSelection: emitter });\n", "\n", "\t\tconst data: INotebookKernelDto2 = {\n", "\t\t\tid: options.id,\n", "\t\t\tselector: options.selector,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst emitter = new Emitter<{ selected: boolean, uri: URI }>();\n", "\t\tthis._kernelData.set(handle, { id: options.id, executeHandler: options.executeHandler, onDidChangeSelection: emitter });\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 41 }
{ "information_for_contributors": [ "This file has been converted from https://github.com/jeff-hykin/better-go-syntax/blob/master/export/generated.tmLanguage.json", "If you want to provide a fix or improvement, please create a pull request against the original repository.", "Once accepted there, we are happy to receive an update request." ], "version": "https://github.com/jeff-hykin/better-go-syntax/commit/6175663a7a0e23d58ccf9aab95054cb6e5c92aff", "name": "Go", "scopeName": "source.go", "patterns": [ { "include": "#comments" }, { "include": "#comments" }, { "comment": "Interpreted string literals", "begin": "\"", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.go" } }, "end": "\"", "endCaptures": { "0": { "name": "punctuation.definition.string.end.go" } }, "name": "string.quoted.double.go", "patterns": [ { "include": "#string_escaped_char" }, { "include": "#string_placeholder" } ] }, { "comment": "Raw string literals", "begin": "`", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.go" } }, "end": "`", "endCaptures": { "0": { "name": "punctuation.definition.string.end.go" } }, "name": "string.quoted.raw.go", "patterns": [ { "include": "#string_placeholder" } ] }, { "comment": "Syntax error receiving channels", "match": "<\\-([\\t ]+)chan\\b", "captures": { "1": { "name": "invalid.illegal.receive-channel.go" } } }, { "comment": "Syntax error sending channels", "match": "\\bchan([\\t ]+)<-", "captures": { "1": { "name": "invalid.illegal.send-channel.go" } } }, { "comment": "Syntax error using slices", "match": "\\[\\](\\s+)", "captures": { "1": { "name": "invalid.illegal.slice.go" } } }, { "comment": "Syntax error numeric literals", "match": "\\b0[0-7]*[89]\\d*\\b", "name": "invalid.illegal.numeric.go" }, { "comment": "Built-in functions", "match": "\\b(append|cap|close|complex|copy|delete|imag|len|make|new|panic|print|println|real|recover)\\b(?=\\()", "name": "support.function.builtin.go" }, { "comment": "Function declarations", "match": "^(\\bfunc\\b)(?:\\s+(\\([^\\)]+\\)\\s+)?(\\w+)(?=\\())?", "captures": { "1": { "name": "keyword.function.go" }, "2": { "patterns": [ { "include": "#brackets" }, { "include": "#operators" } ] }, "3": { "patterns": [ { "match": "\\d\\w*", "name": "invalid.illegal.identifier.go" }, { "match": "\\w+", "name": "entity.name.function.go" } ] } } }, { "comment": "Functions", "match": "(\\bfunc\\b)|(\\w+)(?=\\()", "captures": { "1": { "name": "keyword.function.go" }, "2": { "patterns": [ { "match": "\\d\\w*", "name": "invalid.illegal.identifier.go" }, { "match": "\\w+", "name": "support.function.go" } ] } } }, { "include": "#numeric_literals" }, { "comment": "Language constants", "match": "\\b(true|false|nil|iota)\\b", "name": "constant.language.go" }, { "begin": "\\b(package)\\s+", "beginCaptures": { "1": { "name": "keyword.package.go" } }, "end": "(?!\\G)", "patterns": [ { "match": "\\d\\w*", "name": "invalid.illegal.identifier.go" }, { "match": "\\w+", "name": "entity.name.package.go" } ] }, { "begin": "\\b(type)\\s+", "beginCaptures": { "1": { "name": "keyword.type.go" } }, "end": "(?!\\G)", "patterns": [ { "match": "\\d\\w*", "name": "invalid.illegal.identifier.go" }, { "match": "\\w+", "name": "entity.name.type.go" } ] }, { "begin": "\\b(import)\\s+", "beginCaptures": { "1": { "name": "keyword.import.go" } }, "end": "(?!\\G)", "patterns": [ { "include": "#imports" } ] }, { "begin": "\\b(var)\\s+", "beginCaptures": { "1": { "name": "keyword.var.go" } }, "end": "(?!\\G)", "patterns": [ { "include": "#variables" } ] }, { "match": "(?<!var)\\s*(\\w+(?:\\.\\w+)*(?>,\\s*\\w+(?:\\.\\w+)*)*)(?=\\s*=(?!=))", "captures": { "1": { "patterns": [ { "match": "\\d\\w*", "name": "invalid.illegal.identifier.go" }, { "match": "\\w+(?:\\.\\w+)*", "name": "variable.other.assignment.go", "captures": { "0": { "patterns": [ { "include": "#delimiters" } ] } } }, { "include": "#delimiters" } ] } } }, { "match": "\\b\\w+(?:,\\s*\\w+)*(?=\\s*:=)", "captures": { "0": { "patterns": [ { "match": "\\d\\w*", "name": "invalid.illegal.identifier.go" }, { "match": "\\w+", "name": "variable.other.assignment.go" }, { "include": "#delimiters" } ] } } }, { "comment": "Terminators", "match": ";", "name": "punctuation.terminator.go" }, { "include": "#brackets" }, { "include": "#delimiters" }, { "include": "#keywords" }, { "include": "#operators" }, { "include": "#runes" }, { "include": "#storage_types" } ], "repository": { "brackets": { "patterns": [ { "begin": "{", "beginCaptures": { "0": { "name": "punctuation.definition.begin.bracket.curly.go" } }, "end": "}", "endCaptures": { "0": { "name": "punctuation.definition.end.bracket.curly.go" } }, "patterns": [ { "include": "$self" } ] }, { "begin": "\\(", "beginCaptures": { "0": { "name": "punctuation.definition.begin.bracket.round.go" } }, "end": "\\)", "endCaptures": { "0": { "name": "punctuation.definition.end.bracket.round.go" } }, "patterns": [ { "include": "$self" } ] }, { "match": "\\[|\\]", "name": "punctuation.definition.bracket.square.go" } ] }, "comments": { "patterns": [ { "name": "comment.block.go", "begin": "(\\/\\*)", "beginCaptures": { "1": { "name": "punctuation.definition.comment.go" } }, "end": "(\\*\\/)", "endCaptures": { "1": { "name": "punctuation.definition.comment.go" } } }, { "name": "comment.line.double-slash.go", "begin": "(\\/\\/)", "beginCaptures": { "1": { "name": "punctuation.definition.comment.go" } }, "end": "(?:\\n|$)" } ] }, "delimiters": { "patterns": [ { "match": ",", "name": "punctuation.other.comma.go" }, { "match": "\\.(?!\\.\\.)", "name": "punctuation.other.period.go" }, { "match": ":(?!=)", "name": "punctuation.other.colon.go" } ] }, "imports": { "patterns": [ { "match": "((?!\\s+\")[^\\s]*)?\\s*((\")([^\"]*)(\"))", "captures": { "1": { "name": "entity.alias.import.go" }, "2": { "name": "string.quoted.double.go" }, "3": { "name": "punctuation.definition.string.begin.go" }, "4": { "name": "entity.name.import.go" }, "5": { "name": "punctuation.definition.string.end.go" } } }, { "begin": "\\(", "beginCaptures": { "0": { "name": "punctuation.definition.imports.begin.bracket.round.go" } }, "end": "\\)", "endCaptures": { "0": { "name": "punctuation.definition.imports.end.bracket.round.go" } }, "patterns": [ { "include": "#comments" }, { "include": "#imports" } ] } ] }, "keywords": { "patterns": [ { "comment": "Flow control keywords", "match": "\\b(break|case|continue|default|defer|else|fallthrough|for|go|goto|if|range|return|select|switch)\\b", "name": "keyword.control.go" }, { "match": "\\bchan\\b", "name": "keyword.channel.go" }, { "match": "\\bconst\\b", "name": "keyword.const.go" }, { "match": "\\bfunc\\b", "name": "keyword.function.go" }, { "match": "\\binterface\\b", "name": "keyword.interface.go" }, { "match": "\\bmap\\b", "name": "keyword.map.go" }, { "match": "\\bstruct\\b", "name": "keyword.struct.go" } ] }, "operators": { "comment": "Note that the order here is very important!", "patterns": [ { "match": "(\\*|&)(?=\\w)", "name": "keyword.operator.address.go" }, { "match": "<\\-", "name": "keyword.operator.channel.go" }, { "match": "\\-\\-", "name": "keyword.operator.decrement.go" }, { "match": "\\+\\+", "name": "keyword.operator.increment.go" }, { "match": "(==|!=|<=|>=|<(?!<)|>(?!>))", "name": "keyword.operator.comparison.go" }, { "match": "(&&|\\|\\||!)", "name": "keyword.operator.logical.go" }, { "match": "(=|\\+=|\\-=|\\|=|\\^=|\\*=|/=|:=|%=|<<=|>>=|&\\^=|&=)", "name": "keyword.operator.assignment.go" }, { "match": "(\\+|\\-|\\*|/|%)", "name": "keyword.operator.arithmetic.go" }, { "match": "(&(?!\\^)|\\||\\^|&\\^|<<|>>)", "name": "keyword.operator.arithmetic.bitwise.go" }, { "match": "\\.\\.\\.", "name": "keyword.operator.ellipsis.go" } ] }, "runes": { "patterns": [ { "begin": "'", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.go" } }, "end": "'", "endCaptures": { "0": { "name": "punctuation.definition.string.end.go" } }, "name": "string.quoted.rune.go", "patterns": [ { "match": "\\G(\\\\([0-7]{3}|[abfnrtv\\\\'\"]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})|.)(?=')", "name": "constant.other.rune.go" }, { "match": "[^']+", "name": "invalid.illegal.unknown-rune.go" } ] } ] }, "storage_types": { "patterns": [ { "match": "\\bbool\\b", "name": "storage.type.boolean.go" }, { "match": "\\bbyte\\b", "name": "storage.type.byte.go" }, { "match": "\\berror\\b", "name": "storage.type.error.go" }, { "match": "\\b(complex(64|128)|float(32|64)|u?int(8|16|32|64)?)\\b", "name": "storage.type.numeric.go" }, { "match": "\\brune\\b", "name": "storage.type.rune.go" }, { "match": "\\bstring\\b", "name": "storage.type.string.go" }, { "match": "\\buintptr\\b", "name": "storage.type.uintptr.go" } ] }, "string_escaped_char": { "patterns": [ { "match": "\\\\([0-7]{3}|[abfnrtv\\\\'\"]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})", "name": "constant.character.escape.go" }, { "match": "\\\\[^0-7xuUabfnrtv\\'\"]", "name": "invalid.illegal.unknown-escape.go" } ] }, "string_placeholder": { "patterns": [ { "match": "%(\\[\\d+\\])?([\\+#\\-0\\x20]{,2}((\\d+|\\*)?(\\.?(\\d+|\\*|(\\[\\d+\\])\\*?)?(\\[\\d+\\])?)?))?[vT%tbcdoqxXUbeEfFgGspw]", "name": "constant.other.placeholder.go" } ] }, "variables": { "patterns": [ { "match": "(\\w+(?:,\\s*\\w+)*)(\\s+\\*?\\w+(?:\\.\\w+)?\\s*)?(?=\\s*=)", "captures": { "1": { "patterns": [ { "match": "\\d\\w*", "name": "invalid.illegal.identifier.go" }, { "match": "\\w+", "name": "variable.other.assignment.go" }, { "include": "#delimiters" } ] }, "2": { "patterns": [ { "include": "$self" } ] } } }, { "match": "(\\w+(?:,\\s*\\w+)*)(\\s+(\\[(\\d*|\\.\\.\\.)\\])*\\*?(<-)?\\w+(?:\\.\\w+)?\\s*[^=].*)", "captures": { "1": { "patterns": [ { "match": "\\d\\w*", "name": "invalid.illegal.identifier.go" }, { "match": "\\w+", "name": "variable.other.declaration.go" }, { "include": "#delimiters" } ] }, "2": { "patterns": [ { "include": "$self" } ] } } }, { "begin": "\\(", "beginCaptures": { "0": { "name": "punctuation.definition.variables.begin.bracket.round.go" } }, "end": "\\)", "endCaptures": { "0": { "name": "punctuation.definition.variables.end.bracket.round.go" } }, "patterns": [ { "include": "$self" }, { "include": "#variables" } ] } ] }, "numeric_literals": { "match": "(?<!\\w)\\.?\\d(?:(?:[0-9a-zA-Z_\\.])|(?<=[eEpP])[+-])*", "captures": { "0": { "patterns": [ { "begin": "(?=.)", "end": "(?:\\n|$)", "patterns": [ { "match": "(?:(?:(?:(?:(?:\\G(?=[0-9.])(?!0[xXbBoO])([0-9](?:[0-9]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)((?:(?<=[0-9])\\.|\\.(?=[0-9])))([0-9](?:[0-9]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)?(?:(?<!_)([eE])(\\+?)(\\-?)((?:[0-9](?:[0-9]|(?:(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)))?(i(?!\\w))?(?:\\n|$)|\\G(?=[0-9.])(?!0[xXbBoO])([0-9](?:[0-9]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)(?<!_)([eE])(\\+?)(\\-?)((?:[0-9](?:[0-9]|(?:(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*))(i(?!\\w))?(?:\\n|$))|\\G((?:(?<=[0-9])\\.|\\.(?=[0-9])))([0-9](?:[0-9]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)(?:(?<!_)([eE])(\\+?)(\\-?)((?:[0-9](?:[0-9]|(?:(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)))?(i(?!\\w))?(?:\\n|$))|(\\G0[xX])_?([0-9a-fA-F](?:[0-9a-fA-F]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)((?:(?<=[0-9a-fA-F])\\.|\\.(?=[0-9a-fA-F])))([0-9a-fA-F](?:[0-9a-fA-F]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)?(?<!_)([pP])(\\+?)(\\-?)((?:[0-9](?:[0-9]|(?:(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*))(i(?!\\w))?(?:\\n|$))|(\\G0[xX])_?([0-9a-fA-F](?:[0-9a-fA-F]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)(?<!_)([pP])(\\+?)(\\-?)((?:[0-9](?:[0-9]|(?:(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*))(i(?!\\w))?(?:\\n|$))|(\\G0[xX])((?:(?<=[0-9a-fA-F])\\.|\\.(?=[0-9a-fA-F])))([0-9a-fA-F](?:[0-9a-fA-F]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)(?<!_)([pP])(\\+?)(\\-?)((?:[0-9](?:[0-9]|(?:(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*))(i(?!\\w))?(?:\\n|$))", "captures": { "1": { "name": "constant.numeric.decimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "2": { "name": "punctuation.separator.constant.numeric.go" }, "3": { "name": "constant.numeric.decimal.point.go" }, "4": { "name": "constant.numeric.decimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "5": { "name": "punctuation.separator.constant.numeric.go" }, "6": { "name": "keyword.other.unit.exponent.decimal.go" }, "7": { "name": "keyword.operator.plus.exponent.decimal.go" }, "8": { "name": "keyword.operator.minus.exponent.decimal.go" }, "9": { "name": "constant.numeric.exponent.decimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "10": { "name": "keyword.other.unit.imaginary.go" }, "11": { "name": "constant.numeric.decimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "12": { "name": "punctuation.separator.constant.numeric.go" }, "13": { "name": "keyword.other.unit.exponent.decimal.go" }, "14": { "name": "keyword.operator.plus.exponent.decimal.go" }, "15": { "name": "keyword.operator.minus.exponent.decimal.go" }, "16": { "name": "constant.numeric.exponent.decimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "17": { "name": "keyword.other.unit.imaginary.go" }, "18": { "name": "constant.numeric.decimal.point.go" }, "19": { "name": "constant.numeric.decimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "20": { "name": "punctuation.separator.constant.numeric.go" }, "21": { "name": "keyword.other.unit.exponent.decimal.go" }, "22": { "name": "keyword.operator.plus.exponent.decimal.go" }, "23": { "name": "keyword.operator.minus.exponent.decimal.go" }, "24": { "name": "constant.numeric.exponent.decimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "25": { "name": "keyword.other.unit.imaginary.go" }, "26": { "name": "keyword.other.unit.hexadecimal.go" }, "27": { "name": "constant.numeric.hexadecimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "28": { "name": "punctuation.separator.constant.numeric.go" }, "29": { "name": "constant.numeric.hexadecimal.go" }, "30": { "name": "constant.numeric.hexadecimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "31": { "name": "punctuation.separator.constant.numeric.go" }, "32": { "name": "keyword.other.unit.exponent.hexadecimal.go" }, "33": { "name": "keyword.operator.plus.exponent.hexadecimal.go" }, "34": { "name": "keyword.operator.minus.exponent.hexadecimal.go" }, "35": { "name": "constant.numeric.exponent.hexadecimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "36": { "name": "keyword.other.unit.imaginary.go" }, "37": { "name": "keyword.other.unit.hexadecimal.go" }, "38": { "name": "constant.numeric.hexadecimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "39": { "name": "punctuation.separator.constant.numeric.go" }, "40": { "name": "keyword.other.unit.exponent.hexadecimal.go" }, "41": { "name": "keyword.operator.plus.exponent.hexadecimal.go" }, "42": { "name": "keyword.operator.minus.exponent.hexadecimal.go" }, "43": { "name": "constant.numeric.exponent.hexadecimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "44": { "name": "keyword.other.unit.imaginary.go" }, "45": { "name": "keyword.other.unit.hexadecimal.go" }, "46": { "name": "constant.numeric.hexadecimal.go" }, "47": { "name": "constant.numeric.hexadecimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "48": { "name": "punctuation.separator.constant.numeric.go" }, "49": { "name": "keyword.other.unit.exponent.hexadecimal.go" }, "50": { "name": "keyword.operator.plus.exponent.hexadecimal.go" }, "51": { "name": "keyword.operator.minus.exponent.hexadecimal.go" }, "52": { "name": "constant.numeric.exponent.hexadecimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "53": { "name": "keyword.other.unit.imaginary.go" } } }, { "match": "(?:(?:(?:\\G(?=[0-9.])(?!0[xXbBoO])([0-9](?:[0-9]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)(i(?!\\w))?(?:\\n|$)|(\\G0[bB])_?([01](?:[01]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)(i(?!\\w))?(?:\\n|$))|(\\G0[oO]?)_?((?:[0-7]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))+)(i(?!\\w))?(?:\\n|$))|(\\G0[xX])_?([0-9a-fA-F](?:[0-9a-fA-F]|((?<=[0-9a-fA-F])_(?=[0-9a-fA-F])))*)(i(?!\\w))?(?:\\n|$))", "captures": { "1": { "name": "constant.numeric.decimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "2": { "name": "punctuation.separator.constant.numeric.go" }, "3": { "name": "keyword.other.unit.imaginary.go" }, "4": { "name": "keyword.other.unit.binary.go" }, "5": { "name": "constant.numeric.binary.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "6": { "name": "punctuation.separator.constant.numeric.go" }, "7": { "name": "keyword.other.unit.imaginary.go" }, "8": { "name": "keyword.other.unit.octal.go" }, "9": { "name": "constant.numeric.octal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "10": { "name": "punctuation.separator.constant.numeric.go" }, "11": { "name": "keyword.other.unit.imaginary.go" }, "12": { "name": "keyword.other.unit.hexadecimal.go" }, "13": { "name": "constant.numeric.hexadecimal.go", "patterns": [ { "match": "(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])", "name": "punctuation.separator.constant.numeric.go" } ] }, "14": { "name": "punctuation.separator.constant.numeric.go" }, "15": { "name": "keyword.other.unit.imaginary.go" } } }, { "match": "(?:(?:[0-9a-zA-Z_\\.])|(?<=[eEpP])[+-])+", "name": "invalid.illegal.constant.numeric.go" } ] } ] } } } } }
extensions/go/syntaxes/go.tmLanguage.json
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00020939057867508382, 0.00017421325901523232, 0.00016524434613529593, 0.00017389332060702145, 0.000003887213097186759 ]
{ "id": 8, "code_window": [ "\n", "\t\treturn {\n", "\t\t\tget id() { return data.id; },\n", "\t\t\tget selector() { return data.selector; },\n", "\t\t\t// get selected() { return that._kernelData.get(handle)?.selected ?? false; },\n", "\t\t\t// onDidChangeSelection: emitter.event,\n", "\t\t\tget label() {\n", "\t\t\t\treturn data.label;\n", "\t\t\t},\n", "\t\t\tset label(value) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 75 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent'; import { IListContextMenuEvent, IListEvent, IListMouseEvent } from 'vs/base/browser/ui/list/list'; import { IListOptions, IListStyles } from 'vs/base/browser/ui/list/listWidget'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar'; import { Emitter, Event } from 'vs/base/common/event'; import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ScrollEvent } from 'vs/base/common/scrollable'; import { URI } from 'vs/base/common/uri'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { FontInfo } from 'vs/editor/common/config/fontInfo'; import { IPosition } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { FindMatch, IReadonlyTextBuffer, ITextModel } from 'vs/editor/common/model'; import { ContextKeyExpr, RawContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { OutputRenderer } from 'vs/workbench/contrib/notebook/browser/view/output/outputRenderer'; import { RunStateRenderer, TimerRenderer } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer'; import { CellViewModel, IModelDecorationsChangeAccessor, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel'; import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel'; import { CellKind, NotebookCellMetadata, NotebookDocumentMetadata, INotebookKernel, ICellRange, IOrderedMimeType, INotebookRendererInfo, ICellOutput, IOutputItemDto, cellRangesToIndexes, reduceRanges } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { Webview } from 'vs/workbench/contrib/webview/browser/webview'; import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel'; import { IMenu } from 'vs/platform/actions/common/actions'; import { EditorOptions, IEditorPane } from 'vs/workbench/common/editor'; import { IResourceEditorInput } from 'vs/platform/editor/common/editor'; import { IConstructorSignature1 } from 'vs/platform/instantiation/common/instantiation'; import { CellEditorStatusBar } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellWidgets'; //#region Context Keys export const KEYBINDING_CONTEXT_NOTEBOOK_FIND_WIDGET_FOCUSED = new RawContextKey<boolean>('notebookFindWidgetFocused', false); // Is Notebook export const NOTEBOOK_IS_ACTIVE_EDITOR = ContextKeyExpr.equals('activeEditor', 'workbench.editor.notebook'); // Editor keys export const NOTEBOOK_EDITOR_FOCUSED = new RawContextKey<boolean>('notebookEditorFocused', false); export const NOTEBOOK_EDITOR_OPEN = new RawContextKey<boolean>('notebookEditorOpen', false); export const NOTEBOOK_CELL_LIST_FOCUSED = new RawContextKey<boolean>('notebookCellListFocused', false); export const NOTEBOOK_OUTPUT_FOCUSED = new RawContextKey<boolean>('notebookOutputFocused', false); export const NOTEBOOK_EDITOR_EDITABLE = new RawContextKey<boolean>('notebookEditable', true); export const NOTEBOOK_HAS_RUNNING_CELL = new RawContextKey<boolean>('notebookHasRunningCell', false); // Diff Editor Keys export const IN_NOTEBOOK_TEXT_DIFF_EDITOR = new RawContextKey<boolean>('isInNotebookTextDiffEditor', false); // Cell keys export const NOTEBOOK_VIEW_TYPE = new RawContextKey<string>('notebookViewType', undefined); export const NOTEBOOK_CELL_TYPE = new RawContextKey<string>('notebookCellType', undefined); // code, markdown export const NOTEBOOK_CELL_EDITABLE = new RawContextKey<boolean>('notebookCellEditable', false); // bool export const NOTEBOOK_CELL_FOCUSED = new RawContextKey<boolean>('notebookCellFocused', false); // bool export const NOTEBOOK_CELL_EDITOR_FOCUSED = new RawContextKey<boolean>('notebookCellEditorFocused', false); // bool export const NOTEBOOK_CELL_MARKDOWN_EDIT_MODE = new RawContextKey<boolean>('notebookCellMarkdownEditMode', false); // bool export const NOTEBOOK_CELL_LINE_NUMBERS = new RawContextKey<'on' | 'off' | 'inherit'>('notebookCellLineNumbers', 'inherit'); // off, none, inherit export type NotebookCellExecutionStateContext = 'idle' | 'pending' | 'executing' | 'succeeded' | 'failed'; export const NOTEBOOK_CELL_EXECUTION_STATE = new RawContextKey<NotebookCellExecutionStateContext>('notebookCellExecutionState', undefined); export const NOTEBOOK_CELL_HAS_OUTPUTS = new RawContextKey<boolean>('notebookCellHasOutputs', false); // bool export const NOTEBOOK_CELL_INPUT_COLLAPSED = new RawContextKey<boolean>('notebookCellInputIsCollapsed', false); // bool export const NOTEBOOK_CELL_OUTPUT_COLLAPSED = new RawContextKey<boolean>('notebookCellOutputIsCollapsed', false); // bool // Kernels export const NOTEBOOK_HAS_MULTIPLE_KERNELS = new RawContextKey<boolean>('notebookHasMultipleKernels', false); export const NOTEBOOK_KERNEL_COUNT = new RawContextKey<number>('notebookKernelCount', 0); export const NOTEBOOK_INTERRUPTIBLE_KERNEL = new RawContextKey<boolean>('notebookInterruptibleKernel', false); //#endregion //#region Shared commands export const EXPAND_CELL_INPUT_COMMAND_ID = 'notebook.cell.expandCellInput'; export const EXECUTE_CELL_COMMAND_ID = 'notebook.cell.execute'; //#endregion //#region Output related types export const enum RenderOutputType { Mainframe, Html, Extension } export interface IRenderMainframeOutput { type: RenderOutputType.Mainframe; supportAppend?: boolean; initHeight?: number; } export interface IRenderPlainHtmlOutput { type: RenderOutputType.Html; source: IDisplayOutputViewModel; htmlContent: string; } export interface IRenderOutputViaExtension { type: RenderOutputType.Extension; source: IDisplayOutputViewModel; mimeType: string; renderer: INotebookRendererInfo; } export type IInsetRenderOutput = IRenderPlainHtmlOutput | IRenderOutputViaExtension; export type IRenderOutput = IRenderMainframeOutput | IInsetRenderOutput; export interface ICellOutputViewModel { cellViewModel: IGenericCellViewModel; /** * When rendering an output, `model` should always be used as we convert legacy `text/error` output to `display_data` output under the hood. */ model: ICellOutput; resolveMimeTypes(textModel: NotebookTextModel, kernelProvides: readonly string[] | undefined): [readonly IOrderedMimeType[], number]; pickedMimeType: number; supportAppend(): boolean; toRawJSON(): any; } export interface IDisplayOutputViewModel extends ICellOutputViewModel { resolveMimeTypes(textModel: NotebookTextModel, kernelProvides: readonly string[] | undefined): [readonly IOrderedMimeType[], number]; pickedMimeType: number; } //#endregion //#region Shared types between the Notebook Editor and Notebook Diff Editor, they are mostly used for output rendering export interface IGenericCellViewModel { id: string; handle: number; uri: URI; metadata: NotebookCellMetadata | undefined; outputIsHovered: boolean; outputIsFocused: boolean; outputsViewModels: ICellOutputViewModel[]; getOutputOffset(index: number): number; updateOutputHeight(index: number, height: number, source?: string): void; } export interface IDisplayOutputLayoutUpdateRequest { readonly cell: IGenericCellViewModel; output: IDisplayOutputViewModel; cellTop: number; outputOffset: number; forceDisplay: boolean; } export interface ICommonCellInfo { cellId: string; cellHandle: number; cellUri: URI; } export interface INotebookCellOutputLayoutInfo { width: number; height: number; fontInfo: FontInfo; } export interface IFocusNotebookCellOptions { readonly skipReveal?: boolean; } export interface ICommonNotebookEditor { getCellOutputLayoutInfo(cell: IGenericCellViewModel): INotebookCellOutputLayoutInfo; triggerScroll(event: IMouseWheelEvent): void; getCellByInfo(cellInfo: ICommonCellInfo): IGenericCellViewModel; getCellById(cellId: string): IGenericCellViewModel | undefined; toggleNotebookCellSelection(cell: IGenericCellViewModel): void; focusNotebookCell(cell: IGenericCellViewModel, focus: 'editor' | 'container' | 'output', options?: IFocusNotebookCellOptions): void; focusNextNotebookCell(cell: IGenericCellViewModel, focus: 'editor' | 'container' | 'output'): void; updateOutputHeight(cellInfo: ICommonCellInfo, output: IDisplayOutputViewModel, height: number, isInit: boolean, source?: string): void; updateMarkdownCellHeight(cellId: string, height: number, isInit: boolean): void; setMarkdownCellEditState(cellId: string, editState: CellEditState): void; markdownCellDragStart(cellId: string, position: { clientY: number }): void; markdownCellDrag(cellId: string, position: { clientY: number }): void; markdownCellDrop(cellId: string, position: { clientY: number, ctrlKey: boolean, altKey: boolean }): void; markdownCellDragEnd(cellId: string): void; } //#endregion export interface NotebookLayoutInfo { width: number; height: number; fontInfo: FontInfo; } export interface NotebookLayoutChangeEvent { width?: boolean; height?: boolean; fontInfo?: boolean; } export enum CodeCellLayoutState { Uninitialized, Estimated, FromCache, Measured } export interface CodeCellLayoutInfo { readonly fontInfo: FontInfo | null; readonly editorHeight: number; readonly editorWidth: number; readonly totalHeight: number; readonly outputContainerOffset: number; readonly outputTotalHeight: number; readonly outputShowMoreContainerHeight: number; readonly outputShowMoreContainerOffset: number; readonly indicatorHeight: number; readonly bottomToolbarOffset: number; readonly layoutState: CodeCellLayoutState; } export interface CodeCellLayoutChangeEvent { source?: string; editorHeight?: boolean; outputHeight?: boolean; outputShowMoreContainerHeight?: number; totalHeight?: boolean; outerWidth?: number; font?: FontInfo; } export interface MarkdownCellLayoutInfo { readonly fontInfo: FontInfo | null; readonly editorWidth: number; readonly editorHeight: number; readonly bottomToolbarOffset: number; readonly totalHeight: number; } export interface MarkdownCellLayoutChangeEvent { font?: FontInfo; outerWidth?: number; totalHeight?: number; } export interface ICellViewModel extends IGenericCellViewModel { readonly model: NotebookCellTextModel; readonly id: string; readonly textBuffer: IReadonlyTextBuffer; readonly layoutInfo: { totalHeight: number; }; readonly onDidChangeLayout: Event<{ totalHeight?: boolean | number; outerWidth?: number; }>; dragging: boolean; handle: number; uri: URI; language: string; cellKind: CellKind; editState: CellEditState; lineNumbers: 'on' | 'off' | 'inherit'; focusMode: CellFocusMode; outputIsHovered: boolean; getText(): string; getTextLength(): number; getHeight(lineHeight: number): number; metadata: NotebookCellMetadata | undefined; textModel: ITextModel | undefined; hasModel(): this is IEditableCellViewModel; resolveTextModel(): Promise<ITextModel>; getEvaluatedMetadata(documentMetadata: NotebookDocumentMetadata | undefined): NotebookCellMetadata; getSelectionsStartPosition(): IPosition[] | undefined; getCellDecorations(): INotebookCellDecorationOptions[]; } export interface IEditableCellViewModel extends ICellViewModel { textModel: ITextModel; } export interface INotebookEditorMouseEvent { readonly event: MouseEvent; readonly target: CellViewModel; } export interface INotebookEditorContribution { /** * Dispose this contribution. */ dispose(): void; /** * Store view state. */ saveViewState?(): unknown; /** * Restore view state. */ restoreViewState?(state: unknown): void; } export interface INotebookCellDecorationOptions { className?: string; gutterClassName?: string; outputClassName?: string; topClassName?: string; } export interface INotebookDeltaDecoration { handle: number; options: INotebookCellDecorationOptions; } export class NotebookEditorOptions extends EditorOptions { readonly cellOptions?: IResourceEditorInput; readonly cellSelections?: ICellRange[]; constructor(options: Partial<NotebookEditorOptions>) { super(); this.overwrite(options); this.cellOptions = options.cellOptions; this.cellSelections = options.cellSelections; } with(options: Partial<NotebookEditorOptions>): NotebookEditorOptions { return new NotebookEditorOptions({ ...this, ...options }); } } export type INotebookEditorContributionCtor = IConstructorSignature1<INotebookEditor, INotebookEditorContribution>; export interface INotebookEditorContributionDescription { id: string; ctor: INotebookEditorContributionCtor; } export interface INotebookEditorCreationOptions { readonly isEmbedded?: boolean; readonly contributions?: INotebookEditorContributionDescription[]; } export interface IActiveNotebookEditor extends INotebookEditor { viewModel: NotebookViewModel; getFocus(): ICellRange; } export const NOTEBOOK_EDITOR_ID = 'workbench.editor.notebook'; export const NOTEBOOK_DIFF_EDITOR_ID = 'workbench.editor.notebookTextDiffEditor'; export interface INotebookEditor extends ICommonNotebookEditor { // from the old IEditor readonly onDidChangeVisibleRanges: Event<void>; readonly onDidChangeSelection: Event<void>; getSelections(): ICellRange[]; visibleRanges: ICellRange[]; textModel?: NotebookTextModel; getId(): string; hasFocus(): boolean; isEmbedded: boolean; cursorNavigationMode: boolean; /** * Notebook view model attached to the current editor */ viewModel: NotebookViewModel | undefined; hasModel(): this is IActiveNotebookEditor; /** * An event emitted when the model of this editor has changed. * @event */ readonly onDidChangeModel: Event<NotebookTextModel | undefined>; readonly onDidFocusEditorWidget: Event<void>; readonly activeKernel: INotebookKernel | undefined; readonly availableKernelCount: number; readonly onDidScroll: Event<void>; readonly onDidChangeAvailableKernels: Event<void>; readonly onDidChangeKernel: Event<void>; readonly onDidChangeActiveCell: Event<void>; isDisposed: boolean; dispose(): void; getId(): string; getDomNode(): HTMLElement; getOverflowContainerDomNode(): HTMLElement; getInnerWebview(): Webview | undefined; getSelectionViewModels(): ICellViewModel[]; /** * Focus the notebook editor cell list */ focus(): void; hasFocus(): boolean; hasWebviewFocus(): boolean; hasOutputTextSelection(): boolean; setOptions(options: NotebookEditorOptions | undefined): Promise<void>; /** * Select & focus cell */ focusElement(cell: ICellViewModel): void; /** * Layout info for the notebook editor */ getLayoutInfo(): NotebookLayoutInfo; getVisibleRangesPlusViewportAboveBelow(): ICellRange[]; /** * Fetch the output renderers for notebook outputs. */ getOutputRenderer(): OutputRenderer; /** * Fetch the contributed kernels for this notebook */ beginComputeContributedKernels(): Promise<INotebookKernel[]>; /** * Insert a new cell around `cell` */ insertNotebookCell(cell: ICellViewModel | undefined, type: CellKind, direction?: 'above' | 'below', initialText?: string, ui?: boolean): CellViewModel | null; /** * Split a given cell into multiple cells of the same type using the selection start positions. */ splitNotebookCell(cell: ICellViewModel): Promise<CellViewModel[] | null>; /** * Delete a cell from the notebook */ deleteNotebookCell(cell: ICellViewModel): Promise<boolean>; /** * Move a cell up one spot */ moveCellUp(cell: ICellViewModel): Promise<ICellViewModel | null>; /** * Move a cell down one spot */ moveCellDown(cell: ICellViewModel): Promise<ICellViewModel | null>; /** * Move a cell to a specific position */ moveCellsToIdx(index: number, length: number, toIdx: number): Promise<ICellViewModel | null>; /** * Focus the container of a cell (the monaco editor inside is not focused). */ focusNotebookCell(cell: ICellViewModel, focus: 'editor' | 'container' | 'output'): void; focusNextNotebookCell(cell: ICellViewModel, focus: 'editor' | 'container' | 'output'): void; /** * Execute the given notebook cell */ executeNotebookCell(cell: ICellViewModel): Promise<void>; /** * Cancel the cell execution */ cancelNotebookCellExecution(cell: ICellViewModel): void; /** * Executes all notebook cells in order */ executeNotebook(): Promise<void>; /** * Cancel the notebook execution */ cancelNotebookExecution(): void; /** * Get current active cell */ getActiveCell(): ICellViewModel | undefined; /** * Layout the cell with a new height */ layoutNotebookCell(cell: ICellViewModel, height: number): Promise<void>; createMarkdownPreview(cell: ICellViewModel): Promise<void>; unhideMarkdownPreviews(cells: readonly ICellViewModel[]): Promise<void>; hideMarkdownPreviews(cells: readonly ICellViewModel[]): Promise<void>; /** * Render the output in webview layer */ createOutput(cell: ICellViewModel, output: IInsetRenderOutput, offset: number): Promise<void>; /** * Remove the output from the webview layer */ removeInset(output: IDisplayOutputViewModel): void; /** * Hide the inset in the webview layer without removing it */ hideInset(output: IDisplayOutputViewModel): void; /** * Send message to the webview for outputs. */ postMessage(forRendererId: string | undefined, message: any): void; /** * Remove class name on the notebook editor root DOM node. */ addClassName(className: string): void; /** * Remove class name on the notebook editor root DOM node. */ removeClassName(className: string): void; deltaCellOutputContainerClassNames(cellId: string, added: string[], removed: string[]): void; /** * Trigger the editor to scroll from scroll event programmatically */ triggerScroll(event: IMouseWheelEvent): void; /** * The range will be revealed with as little scrolling as possible. */ revealCellRangeInView(range: ICellRange): void; /** * Reveal cell into viewport. */ revealInView(cell: ICellViewModel): void; /** * Reveal cell into the top of viewport. */ revealInViewAtTop(cell: ICellViewModel): void; /** * Reveal cell into viewport center. */ revealInCenter(cell: ICellViewModel): void; /** * Reveal cell into viewport center if cell is currently out of the viewport. */ revealInCenterIfOutsideViewport(cell: ICellViewModel): void; /** * Reveal a line in notebook cell into viewport with minimal scrolling. */ revealLineInViewAsync(cell: ICellViewModel, line: number): Promise<void>; /** * Reveal a line in notebook cell into viewport center. */ revealLineInCenterAsync(cell: ICellViewModel, line: number): Promise<void>; /** * Reveal a line in notebook cell into viewport center. */ revealLineInCenterIfOutsideViewportAsync(cell: ICellViewModel, line: number): Promise<void>; /** * Reveal a range in notebook cell into viewport with minimal scrolling. */ revealRangeInViewAsync(cell: ICellViewModel, range: Range): Promise<void>; /** * Reveal a range in notebook cell into viewport center. */ revealRangeInCenterAsync(cell: ICellViewModel, range: Range): Promise<void>; /** * Reveal a range in notebook cell into viewport center. */ revealRangeInCenterIfOutsideViewportAsync(cell: ICellViewModel, range: Range): Promise<void>; /** * Get the view index of a cell */ getViewIndex(cell: ICellViewModel): number; /** * Get the view height of a cell (from the list view) */ getViewHeight(cell: ICellViewModel): number; /** * @param startIndex Inclusive * @param endIndex Exclusive */ getCellRangeFromViewRange(startIndex: number, endIndex: number): ICellRange | undefined; /** * @param startIndex Inclusive * @param endIndex Exclusive */ getCellsFromViewRange(startIndex: number, endIndex: number): ReadonlyArray<ICellViewModel>; /** * Set hidden areas on cell text models. */ setHiddenAreas(_ranges: ICellRange[]): boolean; setCellEditorSelection(cell: ICellViewModel, selection: Range): void; deltaCellDecorations(oldDecorations: string[], newDecorations: INotebookDeltaDecoration[]): string[]; /** * Change the decorations on cells. * The notebook is virtualized and this method should be called to create/delete editor decorations safely. */ changeModelDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T): T | null; setEditorDecorations(key: string, range: ICellRange): void; removeEditorDecorations(key: string): void; /** * An event emitted on a "mouseup". * @event */ onMouseUp(listener: (e: INotebookEditorMouseEvent) => void): IDisposable; /** * An event emitted on a "mousedown". * @event */ onMouseDown(listener: (e: INotebookEditorMouseEvent) => void): IDisposable; /** * Get a contribution of this editor. * @id Unique identifier of the contribution. * @return The contribution or null if contribution not found. */ getContribution<T extends INotebookEditorContribution>(id: string): T; getCellByInfo(cellInfo: ICommonCellInfo): ICellViewModel; getCellById(cellId: string): ICellViewModel | undefined; updateOutputHeight(cellInfo: ICommonCellInfo, output: IDisplayOutputViewModel, height: number, isInit: boolean, source?: string): void; } export interface INotebookCellList { isDisposed: boolean; viewModel: NotebookViewModel | null; readonly contextKeyService: IContextKeyService; element(index: number): ICellViewModel | undefined; elementAt(position: number): ICellViewModel | undefined; elementHeight(element: ICellViewModel): number; onWillScroll: Event<ScrollEvent>; onDidScroll: Event<ScrollEvent>; onDidChangeFocus: Event<IListEvent<ICellViewModel>>; onDidChangeContentHeight: Event<number>; onDidChangeVisibleRanges: Event<void>; visibleRanges: ICellRange[]; scrollTop: number; scrollHeight: number; scrollLeft: number; length: number; rowsContainer: HTMLElement; readonly onDidRemoveOutputs: Event<readonly ICellOutputViewModel[]>; readonly onDidHideOutputs: Event<readonly ICellOutputViewModel[]>; readonly onDidRemoveCellsFromView: Event<readonly ICellViewModel[]>; readonly onMouseUp: Event<IListMouseEvent<CellViewModel>>; readonly onMouseDown: Event<IListMouseEvent<CellViewModel>>; readonly onContextMenu: Event<IListContextMenuEvent<CellViewModel>>; detachViewModel(): void; attachViewModel(viewModel: NotebookViewModel): void; clear(): void; getViewIndex(cell: ICellViewModel): number | undefined; getViewIndex2(modelIndex: number): number | undefined; getModelIndex(cell: CellViewModel): number | undefined; getModelIndex2(viewIndex: number): number | undefined; getVisibleRangesPlusViewportAboveBelow(): ICellRange[]; focusElement(element: ICellViewModel): void; selectElements(elements: ICellViewModel[]): void; getFocusedElements(): ICellViewModel[]; getSelectedElements(): ICellViewModel[]; revealElementsInView(range: ICellRange): void; revealElementInView(element: ICellViewModel): void; revealElementInViewAtTop(element: ICellViewModel): void; revealElementInCenterIfOutsideViewport(element: ICellViewModel): void; revealElementInCenter(element: ICellViewModel): void; revealElementInCenterIfOutsideViewportAsync(element: ICellViewModel): Promise<void>; revealElementLineInViewAsync(element: ICellViewModel, line: number): Promise<void>; revealElementLineInCenterAsync(element: ICellViewModel, line: number): Promise<void>; revealElementLineInCenterIfOutsideViewportAsync(element: ICellViewModel, line: number): Promise<void>; revealElementRangeInViewAsync(element: ICellViewModel, range: Range): Promise<void>; revealElementRangeInCenterAsync(element: ICellViewModel, range: Range): Promise<void>; revealElementRangeInCenterIfOutsideViewportAsync(element: ICellViewModel, range: Range): Promise<void>; setHiddenAreas(_ranges: ICellRange[], triggerViewUpdate: boolean): boolean; domElementOfElement(element: ICellViewModel): HTMLElement | null; focusView(): void; getAbsoluteTopOfElement(element: ICellViewModel): number; triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent): void; updateElementHeight2(element: ICellViewModel, size: number): void; domFocus(): void; setCellSelection(element: ICellViewModel, range: Range): void; style(styles: IListStyles): void; getRenderHeight(): number; updateOptions(options: IListOptions<ICellViewModel>): void; layout(height?: number, width?: number): void; dispose(): void; } export interface BaseCellRenderTemplate { rootContainer: HTMLElement; editorPart: HTMLElement; collapsedPart: HTMLElement; expandButton: HTMLElement; contextKeyService: IContextKeyService; container: HTMLElement; cellContainer: HTMLElement; decorationContainer: HTMLElement; toolbar: ToolBar; deleteToolbar: ToolBar; betweenCellToolbar: ToolBar; focusIndicatorLeft: HTMLElement; focusIndicatorRight: HTMLElement; disposables: DisposableStore; elementDisposables: DisposableStore; bottomCellContainer: HTMLElement; currentRenderedCell?: ICellViewModel; statusBar: CellEditorStatusBar; titleMenu: IMenu; toJSON: () => object; } export interface MarkdownCellRenderTemplate extends BaseCellRenderTemplate { editorContainer: HTMLElement; foldingIndicator: HTMLElement; focusIndicatorBottom: HTMLElement; currentEditor?: ICodeEditor; readonly useRenderer: boolean; } export interface CodeCellRenderTemplate extends BaseCellRenderTemplate { cellRunState: RunStateRenderer; runToolbar: ToolBar; runButtonContainer: HTMLElement; executionOrderLabel: HTMLElement; outputContainer: HTMLElement; outputShowMoreContainer: HTMLElement; focusSinkElement: HTMLElement; editor: ICodeEditor; progressBar: ProgressBar; timer: TimerRenderer; focusIndicatorRight: HTMLElement; focusIndicatorBottom: HTMLElement; dragHandle: HTMLElement; } export function isCodeCellRenderTemplate(templateData: BaseCellRenderTemplate): templateData is CodeCellRenderTemplate { return !!(templateData as CodeCellRenderTemplate).runToolbar; } export interface IOutputTransformContribution { getType(): RenderOutputType; getMimetypes(): string[]; /** * Dispose this contribution. */ dispose(): void; /** * Returns contents to place in the webview inset, or the {@link IRenderNoOutput}. * This call is allowed to have side effects, such as placing output * directly into the container element. */ render(output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement, notebookUri: URI | undefined): IRenderOutput; } export interface CellFindMatch { cell: CellViewModel; matches: FindMatch[]; } export enum CellRevealType { Line, Range } export enum CellRevealPosition { Top, Center, Bottom } export enum CellEditState { /** * Default state. * For markdown cell, it's Markdown preview. * For code cell, the browser focus should be on the container instead of the editor */ Preview, /** * Eding mode. Source for markdown or code is rendered in editors and the state will be persistent. */ Editing } export enum CellFocusMode { Container, Editor } export enum CursorAtBoundary { None, Top, Bottom, Both } export interface CellViewModelStateChangeEvent { readonly metadataChanged?: boolean; readonly runStateChanged?: boolean; readonly selectionChanged?: boolean; readonly focusModeChanged?: boolean; readonly editStateChanged?: boolean; readonly languageChanged?: boolean; readonly foldingStateChanged?: boolean; readonly contentChanged?: boolean; readonly outputIsHoveredChanged?: boolean; readonly outputIsFocusedChanged?: boolean; readonly cellIsHoveredChanged?: boolean; readonly cellLineNumberChanged?: boolean; } export function cellRangesEqual(a: ICellRange[], b: ICellRange[]) { a = reduceCellRanges(a); b = reduceCellRanges(b); if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (a[i].start !== b[i].start || a[i].end !== b[i].end) { return false; } } return true; } /** * @param _ranges */ export function reduceCellRanges(_ranges: ICellRange[]): ICellRange[] { if (!_ranges.length) { return []; } const ranges = _ranges.sort((a, b) => a.start - b.start); const result: ICellRange[] = []; let currentRangeStart = ranges[0].start; let currentRangeEnd = ranges[0].end + 1; for (let i = 0, len = ranges.length; i < len; i++) { const range = ranges[i]; if (range.start > currentRangeEnd) { result.push({ start: currentRangeStart, end: currentRangeEnd - 1 }); currentRangeStart = range.start; currentRangeEnd = range.end + 1; } else if (range.end + 1 > currentRangeEnd) { currentRangeEnd = range.end + 1; } } result.push({ start: currentRangeStart, end: currentRangeEnd - 1 }); return result; } export function getVisibleCells(cells: CellViewModel[], hiddenRanges: ICellRange[]) { if (!hiddenRanges.length) { return cells; } let start = 0; let hiddenRangeIndex = 0; const result: CellViewModel[] = []; while (start < cells.length && hiddenRangeIndex < hiddenRanges.length) { if (start < hiddenRanges[hiddenRangeIndex].start) { result.push(...cells.slice(start, hiddenRanges[hiddenRangeIndex].start)); } start = hiddenRanges[hiddenRangeIndex].end + 1; hiddenRangeIndex++; } if (start < cells.length) { result.push(...cells.slice(start)); } return result; } export function getNotebookEditorFromEditorPane(editorPane?: IEditorPane): INotebookEditor | undefined { return editorPane?.getId() === NOTEBOOK_EDITOR_ID ? editorPane.getControl() as INotebookEditor | undefined : undefined; } let EDITOR_TOP_PADDING = 12; const editorTopPaddingChangeEmitter = new Emitter<void>(); export const EditorTopPaddingChangeEvent = editorTopPaddingChangeEmitter.event; export function updateEditorTopPadding(top: number) { EDITOR_TOP_PADDING = top; editorTopPaddingChangeEmitter.fire(); } export function getEditorTopPadding() { return EDITOR_TOP_PADDING; } /** * ranges: model selections * this will convert model selections to view indexes first, and then include the hidden ranges in the list view */ export function expandCellRangesWithHiddenCells(editor: INotebookEditor, viewModel: NotebookViewModel, ranges: ICellRange[]) { // assuming ranges are sorted and no overlap const indexes = cellRangesToIndexes(ranges); let modelRanges: ICellRange[] = []; indexes.forEach(index => { const viewCell = viewModel.viewCells[index]; if (!viewCell) { return; } const viewIndex = editor.getViewIndex(viewCell); if (viewIndex < 0) { return; } const nextViewIndex = viewIndex + 1; const range = editor.getCellRangeFromViewRange(viewIndex, nextViewIndex); if (range) { modelRanges.push(range); } }); return reduceRanges(modelRanges); } /** * Return a set of ranges for the cells matching the given predicate */ export function getRanges(cells: ICellViewModel[], included: (cell: ICellViewModel) => boolean): ICellRange[] { const ranges: ICellRange[] = []; let currentRange: ICellRange | undefined; cells.forEach((cell, idx) => { if (included(cell)) { if (!currentRange) { currentRange = { start: idx, end: idx + 1 }; ranges.push(currentRange); } else { currentRange.end = idx + 1; } } else { currentRange = undefined; } }); return ranges; }
src/vs/workbench/contrib/notebook/browser/notebookBrowser.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00570319127291441, 0.000244965311139822, 0.00016260548727586865, 0.00017329701222479343, 0.0005582720623351634 ]
{ "id": 8, "code_window": [ "\n", "\t\treturn {\n", "\t\t\tget id() { return data.id; },\n", "\t\t\tget selector() { return data.selector; },\n", "\t\t\t// get selected() { return that._kernelData.get(handle)?.selected ?? false; },\n", "\t\t\t// onDidChangeSelection: emitter.event,\n", "\t\t\tget label() {\n", "\t\t\t\treturn data.label;\n", "\t\t\t},\n", "\t\t\tset label(value) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 75 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyCode } from 'vs/base/common/keyCodes'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { ICodeEditor, IEditorMouseEvent, IMouseTarget } from 'vs/editor/browser/editorBrowser'; import { Disposable } from 'vs/base/common/lifecycle'; import { ICursorSelectionChangedEvent } from 'vs/editor/common/controller/cursorEvents'; import { Event, Emitter } from 'vs/base/common/event'; import * as platform from 'vs/base/common/platform'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; function hasModifier(e: { ctrlKey: boolean; shiftKey: boolean; altKey: boolean; metaKey: boolean }, modifier: 'ctrlKey' | 'shiftKey' | 'altKey' | 'metaKey'): boolean { return !!e[modifier]; } /** * An event that encapsulates the various trigger modifiers logic needed for go to definition. */ export class ClickLinkMouseEvent { public readonly target: IMouseTarget; public readonly hasTriggerModifier: boolean; public readonly hasSideBySideModifier: boolean; public readonly isNoneOrSingleMouseDown: boolean; constructor(source: IEditorMouseEvent, opts: ClickLinkOptions) { this.target = source.target; this.hasTriggerModifier = hasModifier(source.event, opts.triggerModifier); this.hasSideBySideModifier = hasModifier(source.event, opts.triggerSideBySideModifier); this.isNoneOrSingleMouseDown = (source.event.detail <= 1); } } /** * An event that encapsulates the various trigger modifiers logic needed for go to definition. */ export class ClickLinkKeyboardEvent { public readonly keyCodeIsTriggerKey: boolean; public readonly keyCodeIsSideBySideKey: boolean; public readonly hasTriggerModifier: boolean; constructor(source: IKeyboardEvent, opts: ClickLinkOptions) { this.keyCodeIsTriggerKey = (source.keyCode === opts.triggerKey); this.keyCodeIsSideBySideKey = (source.keyCode === opts.triggerSideBySideKey); this.hasTriggerModifier = hasModifier(source, opts.triggerModifier); } } export type TriggerModifier = 'ctrlKey' | 'shiftKey' | 'altKey' | 'metaKey'; export class ClickLinkOptions { public readonly triggerKey: KeyCode; public readonly triggerModifier: TriggerModifier; public readonly triggerSideBySideKey: KeyCode; public readonly triggerSideBySideModifier: TriggerModifier; constructor( triggerKey: KeyCode, triggerModifier: TriggerModifier, triggerSideBySideKey: KeyCode, triggerSideBySideModifier: TriggerModifier ) { this.triggerKey = triggerKey; this.triggerModifier = triggerModifier; this.triggerSideBySideKey = triggerSideBySideKey; this.triggerSideBySideModifier = triggerSideBySideModifier; } public equals(other: ClickLinkOptions): boolean { return ( this.triggerKey === other.triggerKey && this.triggerModifier === other.triggerModifier && this.triggerSideBySideKey === other.triggerSideBySideKey && this.triggerSideBySideModifier === other.triggerSideBySideModifier ); } } function createOptions(multiCursorModifier: 'altKey' | 'ctrlKey' | 'metaKey'): ClickLinkOptions { if (multiCursorModifier === 'altKey') { if (platform.isMacintosh) { return new ClickLinkOptions(KeyCode.Meta, 'metaKey', KeyCode.Alt, 'altKey'); } return new ClickLinkOptions(KeyCode.Ctrl, 'ctrlKey', KeyCode.Alt, 'altKey'); } if (platform.isMacintosh) { return new ClickLinkOptions(KeyCode.Alt, 'altKey', KeyCode.Meta, 'metaKey'); } return new ClickLinkOptions(KeyCode.Alt, 'altKey', KeyCode.Ctrl, 'ctrlKey'); } export class ClickLinkGesture extends Disposable { private readonly _onMouseMoveOrRelevantKeyDown: Emitter<[ClickLinkMouseEvent, ClickLinkKeyboardEvent | null]> = this._register(new Emitter<[ClickLinkMouseEvent, ClickLinkKeyboardEvent | null]>()); public readonly onMouseMoveOrRelevantKeyDown: Event<[ClickLinkMouseEvent, ClickLinkKeyboardEvent | null]> = this._onMouseMoveOrRelevantKeyDown.event; private readonly _onExecute: Emitter<ClickLinkMouseEvent> = this._register(new Emitter<ClickLinkMouseEvent>()); public readonly onExecute: Event<ClickLinkMouseEvent> = this._onExecute.event; private readonly _onCancel: Emitter<void> = this._register(new Emitter<void>()); public readonly onCancel: Event<void> = this._onCancel.event; private readonly _editor: ICodeEditor; private _opts: ClickLinkOptions; private _lastMouseMoveEvent: ClickLinkMouseEvent | null; private _hasTriggerKeyOnMouseDown: boolean; private _lineNumberOnMouseDown: number; constructor(editor: ICodeEditor) { super(); this._editor = editor; this._opts = createOptions(this._editor.getOption(EditorOption.multiCursorModifier)); this._lastMouseMoveEvent = null; this._hasTriggerKeyOnMouseDown = false; this._lineNumberOnMouseDown = 0; this._register(this._editor.onDidChangeConfiguration((e) => { if (e.hasChanged(EditorOption.multiCursorModifier)) { const newOpts = createOptions(this._editor.getOption(EditorOption.multiCursorModifier)); if (this._opts.equals(newOpts)) { return; } this._opts = newOpts; this._lastMouseMoveEvent = null; this._hasTriggerKeyOnMouseDown = false; this._lineNumberOnMouseDown = 0; this._onCancel.fire(); } })); this._register(this._editor.onMouseMove((e: IEditorMouseEvent) => this._onEditorMouseMove(new ClickLinkMouseEvent(e, this._opts)))); this._register(this._editor.onMouseDown((e: IEditorMouseEvent) => this._onEditorMouseDown(new ClickLinkMouseEvent(e, this._opts)))); this._register(this._editor.onMouseUp((e: IEditorMouseEvent) => this._onEditorMouseUp(new ClickLinkMouseEvent(e, this._opts)))); this._register(this._editor.onKeyDown((e: IKeyboardEvent) => this._onEditorKeyDown(new ClickLinkKeyboardEvent(e, this._opts)))); this._register(this._editor.onKeyUp((e: IKeyboardEvent) => this._onEditorKeyUp(new ClickLinkKeyboardEvent(e, this._opts)))); this._register(this._editor.onMouseDrag(() => this._resetHandler())); this._register(this._editor.onDidChangeCursorSelection((e) => this._onDidChangeCursorSelection(e))); this._register(this._editor.onDidChangeModel((e) => this._resetHandler())); this._register(this._editor.onDidChangeModelContent(() => this._resetHandler())); this._register(this._editor.onDidScrollChange((e) => { if (e.scrollTopChanged || e.scrollLeftChanged) { this._resetHandler(); } })); } private _onDidChangeCursorSelection(e: ICursorSelectionChangedEvent): void { 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) } } private _onEditorMouseMove(mouseEvent: ClickLinkMouseEvent): void { this._lastMouseMoveEvent = mouseEvent; this._onMouseMoveOrRelevantKeyDown.fire([mouseEvent, null]); } private _onEditorMouseDown(mouseEvent: ClickLinkMouseEvent): void { // We need to record if we had the trigger key on mouse down because someone might select something in the editor // holding the mouse down and then while mouse is down start to press Ctrl/Cmd to start a copy operation and then // release the mouse button without wanting to do the navigation. // With this flag we prevent goto definition if the mouse was down before the trigger key was pressed. this._hasTriggerKeyOnMouseDown = mouseEvent.hasTriggerModifier; this._lineNumberOnMouseDown = mouseEvent.target.position ? mouseEvent.target.position.lineNumber : 0; } private _onEditorMouseUp(mouseEvent: ClickLinkMouseEvent): void { const currentLineNumber = mouseEvent.target.position ? mouseEvent.target.position.lineNumber : 0; if (this._hasTriggerKeyOnMouseDown && this._lineNumberOnMouseDown && this._lineNumberOnMouseDown === currentLineNumber) { this._onExecute.fire(mouseEvent); } } private _onEditorKeyDown(e: ClickLinkKeyboardEvent): void { 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 } } private _onEditorKeyUp(e: ClickLinkKeyboardEvent): void { if (e.keyCodeIsTriggerKey) { this._onCancel.fire(); } } private _resetHandler(): void { this._lastMouseMoveEvent = null; this._hasTriggerKeyOnMouseDown = false; this._onCancel.fire(); } }
src/vs/editor/contrib/gotoSymbol/link/clickLinkGesture.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.0005642566829919815, 0.0001905899989651516, 0.00016427127411589026, 0.00017001548258122057, 0.00008387603156734258 ]
{ "id": 8, "code_window": [ "\n", "\t\treturn {\n", "\t\t\tget id() { return data.id; },\n", "\t\t\tget selector() { return data.selector; },\n", "\t\t\t// get selected() { return that._kernelData.get(handle)?.selected ?? false; },\n", "\t\t\t// onDidChangeSelection: emitter.event,\n", "\t\t\tget label() {\n", "\t\t\t\treturn data.label;\n", "\t\t\t},\n", "\t\t\tset label(value) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 75 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./overlayWidgets'; import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode'; import { IOverlayWidget, OverlayWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { PartFingerprint, PartFingerprints, ViewPart } from 'vs/editor/browser/view/viewPart'; import { RenderingContext, RestrictedRenderingContext } from 'vs/editor/common/view/renderingContext'; import { ViewContext } from 'vs/editor/common/view/viewContext'; import * as viewEvents from 'vs/editor/common/view/viewEvents'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; interface IWidgetData { widget: IOverlayWidget; preference: OverlayWidgetPositionPreference | null; domNode: FastDomNode<HTMLElement>; } interface IWidgetMap { [key: string]: IWidgetData; } export class ViewOverlayWidgets extends ViewPart { private _widgets: IWidgetMap; private readonly _domNode: FastDomNode<HTMLElement>; private _verticalScrollbarWidth: number; private _minimapWidth: number; private _horizontalScrollbarHeight: number; private _editorHeight: number; private _editorWidth: number; constructor(context: ViewContext) { super(context); const options = this._context.configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); this._widgets = {}; this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth; this._minimapWidth = layoutInfo.minimap.minimapWidth; this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight; this._editorHeight = layoutInfo.height; this._editorWidth = layoutInfo.width; this._domNode = createFastDomNode(document.createElement('div')); PartFingerprints.write(this._domNode, PartFingerprint.OverlayWidgets); this._domNode.setClassName('overlayWidgets'); } public override dispose(): void { super.dispose(); this._widgets = {}; } public getDomNode(): FastDomNode<HTMLElement> { return this._domNode; } // ---- begin view event handlers public override onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean { const options = this._context.configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth; this._minimapWidth = layoutInfo.minimap.minimapWidth; this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight; this._editorHeight = layoutInfo.height; this._editorWidth = layoutInfo.width; return true; } // ---- end view event handlers public addWidget(widget: IOverlayWidget): void { const domNode = 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(); } public setWidgetPosition(widget: IOverlayWidget, preference: OverlayWidgetPositionPreference | null): boolean { const widgetData = this._widgets[widget.getId()]; if (widgetData.preference === preference) { return false; } widgetData.preference = preference; this.setShouldRender(); return true; } public removeWidget(widget: IOverlayWidget): void { const widgetId = widget.getId(); if (this._widgets.hasOwnProperty(widgetId)) { const widgetData = this._widgets[widgetId]; const domNode = widgetData.domNode.domNode; delete this._widgets[widgetId]; domNode.parentNode!.removeChild(domNode); this.setShouldRender(); } } private _renderWidget(widgetData: IWidgetData): void { const domNode = widgetData.domNode; if (widgetData.preference === null) { domNode.unsetTop(); return; } if (widgetData.preference === OverlayWidgetPositionPreference.TOP_RIGHT_CORNER) { domNode.setTop(0); domNode.setRight((2 * this._verticalScrollbarWidth) + this._minimapWidth); } else if (widgetData.preference === OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER) { const widgetHeight = domNode.domNode.clientHeight; domNode.setTop((this._editorHeight - widgetHeight - 2 * this._horizontalScrollbarHeight)); domNode.setRight((2 * this._verticalScrollbarWidth) + this._minimapWidth); } else if (widgetData.preference === OverlayWidgetPositionPreference.TOP_CENTER) { domNode.setTop(0); domNode.domNode.style.right = '50%'; } } public prepareRender(ctx: RenderingContext): void { // Nothing to read } public render(ctx: RestrictedRenderingContext): void { this._domNode.setWidth(this._editorWidth); const keys = Object.keys(this._widgets); for (let i = 0, len = keys.length; i < len; i++) { const widgetId = keys[i]; this._renderWidget(this._widgets[widgetId]); } } }
src/vs/editor/browser/viewParts/overlayWidgets/overlayWidgets.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017608019697945565, 0.0001699050044408068, 0.00016177455836441368, 0.00017017706704791635, 0.000004133921720494982 ]
{ "id": 8, "code_window": [ "\n", "\t\treturn {\n", "\t\t\tget id() { return data.id; },\n", "\t\t\tget selector() { return data.selector; },\n", "\t\t\t// get selected() { return that._kernelData.get(handle)?.selected ?? false; },\n", "\t\t\t// onDidChangeSelection: emitter.event,\n", "\t\t\tget label() {\n", "\t\t\t\treturn data.label;\n", "\t\t\t},\n", "\t\t\tset label(value) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 75 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import * as arrays from './util/arrays'; import { Disposable } from './util/dispose'; const resolveExtensionResource = (extension: vscode.Extension<any>, resourcePath: string): vscode.Uri => { return vscode.Uri.joinPath(extension.extensionUri, resourcePath); }; const resolveExtensionResources = (extension: vscode.Extension<any>, resourcePaths: unknown): vscode.Uri[] => { const result: vscode.Uri[] = []; if (Array.isArray(resourcePaths)) { for (const resource of resourcePaths) { try { result.push(resolveExtensionResource(extension, resource)); } catch (e) { // noop } } } return result; }; export interface MarkdownContributions { readonly previewScripts: ReadonlyArray<vscode.Uri>; readonly previewStyles: ReadonlyArray<vscode.Uri>; readonly previewResourceRoots: ReadonlyArray<vscode.Uri>; readonly markdownItPlugins: Map<string, Thenable<(md: any) => any>>; } export namespace MarkdownContributions { export const Empty: MarkdownContributions = { previewScripts: [], previewStyles: [], previewResourceRoots: [], markdownItPlugins: new Map() }; export function merge(a: MarkdownContributions, b: MarkdownContributions): MarkdownContributions { return { previewScripts: [...a.previewScripts, ...b.previewScripts], previewStyles: [...a.previewStyles, ...b.previewStyles], previewResourceRoots: [...a.previewResourceRoots, ...b.previewResourceRoots], markdownItPlugins: new Map([...a.markdownItPlugins.entries(), ...b.markdownItPlugins.entries()]), }; } function uriEqual(a: vscode.Uri, b: vscode.Uri): boolean { return a.toString() === b.toString(); } export function equal(a: MarkdownContributions, b: MarkdownContributions): boolean { return arrays.equals(a.previewScripts, b.previewScripts, uriEqual) && arrays.equals(a.previewStyles, b.previewStyles, uriEqual) && arrays.equals(a.previewResourceRoots, b.previewResourceRoots, uriEqual) && arrays.equals(Array.from(a.markdownItPlugins.keys()), Array.from(b.markdownItPlugins.keys())); } export function fromExtension( extension: vscode.Extension<any> ): MarkdownContributions { const contributions = extension.packageJSON && extension.packageJSON.contributes; if (!contributions) { return MarkdownContributions.Empty; } const previewStyles = getContributedStyles(contributions, extension); const previewScripts = getContributedScripts(contributions, extension); const previewResourceRoots = previewStyles.length || previewScripts.length ? [extension.extensionUri] : []; const markdownItPlugins = getContributedMarkdownItPlugins(contributions, extension); return { previewScripts, previewStyles, previewResourceRoots, markdownItPlugins }; } function getContributedMarkdownItPlugins( contributes: any, extension: vscode.Extension<any> ): Map<string, Thenable<(md: any) => any>> { const map = new Map<string, Thenable<(md: any) => any>>(); if (contributes['markdown.markdownItPlugins']) { map.set(extension.id, extension.activate().then(() => { if (extension.exports && extension.exports.extendMarkdownIt) { return (md: any) => extension.exports.extendMarkdownIt(md); } return (md: any) => md; })); } return map; } function getContributedScripts( contributes: any, extension: vscode.Extension<any> ) { return resolveExtensionResources(extension, contributes['markdown.previewScripts']); } function getContributedStyles( contributes: any, extension: vscode.Extension<any> ) { return resolveExtensionResources(extension, contributes['markdown.previewStyles']); } } export interface MarkdownContributionProvider { readonly extensionUri: vscode.Uri; readonly contributions: MarkdownContributions; readonly onContributionsChanged: vscode.Event<this>; dispose(): void; } class VSCodeExtensionMarkdownContributionProvider extends Disposable implements MarkdownContributionProvider { private _contributions?: MarkdownContributions; public constructor( private readonly _extensionContext: vscode.ExtensionContext, ) { super(); vscode.extensions.onDidChange(() => { const currentContributions = this.getCurrentContributions(); const existingContributions = this._contributions || MarkdownContributions.Empty; if (!MarkdownContributions.equal(existingContributions, currentContributions)) { this._contributions = currentContributions; this._onContributionsChanged.fire(this); } }, undefined, this._disposables); } public get extensionUri() { return this._extensionContext.extensionUri; } private readonly _onContributionsChanged = this._register(new vscode.EventEmitter<this>()); public readonly onContributionsChanged = this._onContributionsChanged.event; public get contributions(): MarkdownContributions { if (!this._contributions) { this._contributions = this.getCurrentContributions(); } return this._contributions; } private getCurrentContributions(): MarkdownContributions { return vscode.extensions.all .map(MarkdownContributions.fromExtension) .reduce(MarkdownContributions.merge, MarkdownContributions.Empty); } } export function getMarkdownExtensionContributions(context: vscode.ExtensionContext): MarkdownContributionProvider { return new VSCodeExtensionMarkdownContributionProvider(context); }
extensions/markdown-language-features/src/markdownExtensions.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.0001783714396879077, 0.0001730415824567899, 0.00016383404727093875, 0.00017473433399572968, 0.000004481293672142783 ]
{ "id": 9, "code_window": [ "\t\t\t\tthis._proxy.$removeKernel(handle);\n", "\t\t\t}\n", "\t\t};\n", "\t}\n", "\n", "\t$acceptSelection(handle: number, value: boolean): void {\n", "\t\tconst obj = this._kernelData.get(handle);\n", "\t\tif (obj) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t$acceptSelection(handle: number, uri: UriComponents, value: boolean): void {\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 130 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent'; import { IListContextMenuEvent, IListEvent, IListMouseEvent } from 'vs/base/browser/ui/list/list'; import { IListOptions, IListStyles } from 'vs/base/browser/ui/list/listWidget'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar'; import { Emitter, Event } from 'vs/base/common/event'; import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ScrollEvent } from 'vs/base/common/scrollable'; import { URI } from 'vs/base/common/uri'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { FontInfo } from 'vs/editor/common/config/fontInfo'; import { IPosition } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { FindMatch, IReadonlyTextBuffer, ITextModel } from 'vs/editor/common/model'; import { ContextKeyExpr, RawContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { OutputRenderer } from 'vs/workbench/contrib/notebook/browser/view/output/outputRenderer'; import { RunStateRenderer, TimerRenderer } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer'; import { CellViewModel, IModelDecorationsChangeAccessor, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel'; import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel'; import { CellKind, NotebookCellMetadata, NotebookDocumentMetadata, INotebookKernel, ICellRange, IOrderedMimeType, INotebookRendererInfo, ICellOutput, IOutputItemDto, cellRangesToIndexes, reduceRanges } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { Webview } from 'vs/workbench/contrib/webview/browser/webview'; import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel'; import { IMenu } from 'vs/platform/actions/common/actions'; import { EditorOptions, IEditorPane } from 'vs/workbench/common/editor'; import { IResourceEditorInput } from 'vs/platform/editor/common/editor'; import { IConstructorSignature1 } from 'vs/platform/instantiation/common/instantiation'; import { CellEditorStatusBar } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellWidgets'; //#region Context Keys export const KEYBINDING_CONTEXT_NOTEBOOK_FIND_WIDGET_FOCUSED = new RawContextKey<boolean>('notebookFindWidgetFocused', false); // Is Notebook export const NOTEBOOK_IS_ACTIVE_EDITOR = ContextKeyExpr.equals('activeEditor', 'workbench.editor.notebook'); // Editor keys export const NOTEBOOK_EDITOR_FOCUSED = new RawContextKey<boolean>('notebookEditorFocused', false); export const NOTEBOOK_EDITOR_OPEN = new RawContextKey<boolean>('notebookEditorOpen', false); export const NOTEBOOK_CELL_LIST_FOCUSED = new RawContextKey<boolean>('notebookCellListFocused', false); export const NOTEBOOK_OUTPUT_FOCUSED = new RawContextKey<boolean>('notebookOutputFocused', false); export const NOTEBOOK_EDITOR_EDITABLE = new RawContextKey<boolean>('notebookEditable', true); export const NOTEBOOK_HAS_RUNNING_CELL = new RawContextKey<boolean>('notebookHasRunningCell', false); // Diff Editor Keys export const IN_NOTEBOOK_TEXT_DIFF_EDITOR = new RawContextKey<boolean>('isInNotebookTextDiffEditor', false); // Cell keys export const NOTEBOOK_VIEW_TYPE = new RawContextKey<string>('notebookViewType', undefined); export const NOTEBOOK_CELL_TYPE = new RawContextKey<string>('notebookCellType', undefined); // code, markdown export const NOTEBOOK_CELL_EDITABLE = new RawContextKey<boolean>('notebookCellEditable', false); // bool export const NOTEBOOK_CELL_FOCUSED = new RawContextKey<boolean>('notebookCellFocused', false); // bool export const NOTEBOOK_CELL_EDITOR_FOCUSED = new RawContextKey<boolean>('notebookCellEditorFocused', false); // bool export const NOTEBOOK_CELL_MARKDOWN_EDIT_MODE = new RawContextKey<boolean>('notebookCellMarkdownEditMode', false); // bool export const NOTEBOOK_CELL_LINE_NUMBERS = new RawContextKey<'on' | 'off' | 'inherit'>('notebookCellLineNumbers', 'inherit'); // off, none, inherit export type NotebookCellExecutionStateContext = 'idle' | 'pending' | 'executing' | 'succeeded' | 'failed'; export const NOTEBOOK_CELL_EXECUTION_STATE = new RawContextKey<NotebookCellExecutionStateContext>('notebookCellExecutionState', undefined); export const NOTEBOOK_CELL_HAS_OUTPUTS = new RawContextKey<boolean>('notebookCellHasOutputs', false); // bool export const NOTEBOOK_CELL_INPUT_COLLAPSED = new RawContextKey<boolean>('notebookCellInputIsCollapsed', false); // bool export const NOTEBOOK_CELL_OUTPUT_COLLAPSED = new RawContextKey<boolean>('notebookCellOutputIsCollapsed', false); // bool // Kernels export const NOTEBOOK_HAS_MULTIPLE_KERNELS = new RawContextKey<boolean>('notebookHasMultipleKernels', false); export const NOTEBOOK_KERNEL_COUNT = new RawContextKey<number>('notebookKernelCount', 0); export const NOTEBOOK_INTERRUPTIBLE_KERNEL = new RawContextKey<boolean>('notebookInterruptibleKernel', false); //#endregion //#region Shared commands export const EXPAND_CELL_INPUT_COMMAND_ID = 'notebook.cell.expandCellInput'; export const EXECUTE_CELL_COMMAND_ID = 'notebook.cell.execute'; //#endregion //#region Output related types export const enum RenderOutputType { Mainframe, Html, Extension } export interface IRenderMainframeOutput { type: RenderOutputType.Mainframe; supportAppend?: boolean; initHeight?: number; } export interface IRenderPlainHtmlOutput { type: RenderOutputType.Html; source: IDisplayOutputViewModel; htmlContent: string; } export interface IRenderOutputViaExtension { type: RenderOutputType.Extension; source: IDisplayOutputViewModel; mimeType: string; renderer: INotebookRendererInfo; } export type IInsetRenderOutput = IRenderPlainHtmlOutput | IRenderOutputViaExtension; export type IRenderOutput = IRenderMainframeOutput | IInsetRenderOutput; export interface ICellOutputViewModel { cellViewModel: IGenericCellViewModel; /** * When rendering an output, `model` should always be used as we convert legacy `text/error` output to `display_data` output under the hood. */ model: ICellOutput; resolveMimeTypes(textModel: NotebookTextModel, kernelProvides: readonly string[] | undefined): [readonly IOrderedMimeType[], number]; pickedMimeType: number; supportAppend(): boolean; toRawJSON(): any; } export interface IDisplayOutputViewModel extends ICellOutputViewModel { resolveMimeTypes(textModel: NotebookTextModel, kernelProvides: readonly string[] | undefined): [readonly IOrderedMimeType[], number]; pickedMimeType: number; } //#endregion //#region Shared types between the Notebook Editor and Notebook Diff Editor, they are mostly used for output rendering export interface IGenericCellViewModel { id: string; handle: number; uri: URI; metadata: NotebookCellMetadata | undefined; outputIsHovered: boolean; outputIsFocused: boolean; outputsViewModels: ICellOutputViewModel[]; getOutputOffset(index: number): number; updateOutputHeight(index: number, height: number, source?: string): void; } export interface IDisplayOutputLayoutUpdateRequest { readonly cell: IGenericCellViewModel; output: IDisplayOutputViewModel; cellTop: number; outputOffset: number; forceDisplay: boolean; } export interface ICommonCellInfo { cellId: string; cellHandle: number; cellUri: URI; } export interface INotebookCellOutputLayoutInfo { width: number; height: number; fontInfo: FontInfo; } export interface IFocusNotebookCellOptions { readonly skipReveal?: boolean; } export interface ICommonNotebookEditor { getCellOutputLayoutInfo(cell: IGenericCellViewModel): INotebookCellOutputLayoutInfo; triggerScroll(event: IMouseWheelEvent): void; getCellByInfo(cellInfo: ICommonCellInfo): IGenericCellViewModel; getCellById(cellId: string): IGenericCellViewModel | undefined; toggleNotebookCellSelection(cell: IGenericCellViewModel): void; focusNotebookCell(cell: IGenericCellViewModel, focus: 'editor' | 'container' | 'output', options?: IFocusNotebookCellOptions): void; focusNextNotebookCell(cell: IGenericCellViewModel, focus: 'editor' | 'container' | 'output'): void; updateOutputHeight(cellInfo: ICommonCellInfo, output: IDisplayOutputViewModel, height: number, isInit: boolean, source?: string): void; updateMarkdownCellHeight(cellId: string, height: number, isInit: boolean): void; setMarkdownCellEditState(cellId: string, editState: CellEditState): void; markdownCellDragStart(cellId: string, position: { clientY: number }): void; markdownCellDrag(cellId: string, position: { clientY: number }): void; markdownCellDrop(cellId: string, position: { clientY: number, ctrlKey: boolean, altKey: boolean }): void; markdownCellDragEnd(cellId: string): void; } //#endregion export interface NotebookLayoutInfo { width: number; height: number; fontInfo: FontInfo; } export interface NotebookLayoutChangeEvent { width?: boolean; height?: boolean; fontInfo?: boolean; } export enum CodeCellLayoutState { Uninitialized, Estimated, FromCache, Measured } export interface CodeCellLayoutInfo { readonly fontInfo: FontInfo | null; readonly editorHeight: number; readonly editorWidth: number; readonly totalHeight: number; readonly outputContainerOffset: number; readonly outputTotalHeight: number; readonly outputShowMoreContainerHeight: number; readonly outputShowMoreContainerOffset: number; readonly indicatorHeight: number; readonly bottomToolbarOffset: number; readonly layoutState: CodeCellLayoutState; } export interface CodeCellLayoutChangeEvent { source?: string; editorHeight?: boolean; outputHeight?: boolean; outputShowMoreContainerHeight?: number; totalHeight?: boolean; outerWidth?: number; font?: FontInfo; } export interface MarkdownCellLayoutInfo { readonly fontInfo: FontInfo | null; readonly editorWidth: number; readonly editorHeight: number; readonly bottomToolbarOffset: number; readonly totalHeight: number; } export interface MarkdownCellLayoutChangeEvent { font?: FontInfo; outerWidth?: number; totalHeight?: number; } export interface ICellViewModel extends IGenericCellViewModel { readonly model: NotebookCellTextModel; readonly id: string; readonly textBuffer: IReadonlyTextBuffer; readonly layoutInfo: { totalHeight: number; }; readonly onDidChangeLayout: Event<{ totalHeight?: boolean | number; outerWidth?: number; }>; dragging: boolean; handle: number; uri: URI; language: string; cellKind: CellKind; editState: CellEditState; lineNumbers: 'on' | 'off' | 'inherit'; focusMode: CellFocusMode; outputIsHovered: boolean; getText(): string; getTextLength(): number; getHeight(lineHeight: number): number; metadata: NotebookCellMetadata | undefined; textModel: ITextModel | undefined; hasModel(): this is IEditableCellViewModel; resolveTextModel(): Promise<ITextModel>; getEvaluatedMetadata(documentMetadata: NotebookDocumentMetadata | undefined): NotebookCellMetadata; getSelectionsStartPosition(): IPosition[] | undefined; getCellDecorations(): INotebookCellDecorationOptions[]; } export interface IEditableCellViewModel extends ICellViewModel { textModel: ITextModel; } export interface INotebookEditorMouseEvent { readonly event: MouseEvent; readonly target: CellViewModel; } export interface INotebookEditorContribution { /** * Dispose this contribution. */ dispose(): void; /** * Store view state. */ saveViewState?(): unknown; /** * Restore view state. */ restoreViewState?(state: unknown): void; } export interface INotebookCellDecorationOptions { className?: string; gutterClassName?: string; outputClassName?: string; topClassName?: string; } export interface INotebookDeltaDecoration { handle: number; options: INotebookCellDecorationOptions; } export class NotebookEditorOptions extends EditorOptions { readonly cellOptions?: IResourceEditorInput; readonly cellSelections?: ICellRange[]; constructor(options: Partial<NotebookEditorOptions>) { super(); this.overwrite(options); this.cellOptions = options.cellOptions; this.cellSelections = options.cellSelections; } with(options: Partial<NotebookEditorOptions>): NotebookEditorOptions { return new NotebookEditorOptions({ ...this, ...options }); } } export type INotebookEditorContributionCtor = IConstructorSignature1<INotebookEditor, INotebookEditorContribution>; export interface INotebookEditorContributionDescription { id: string; ctor: INotebookEditorContributionCtor; } export interface INotebookEditorCreationOptions { readonly isEmbedded?: boolean; readonly contributions?: INotebookEditorContributionDescription[]; } export interface IActiveNotebookEditor extends INotebookEditor { viewModel: NotebookViewModel; getFocus(): ICellRange; } export const NOTEBOOK_EDITOR_ID = 'workbench.editor.notebook'; export const NOTEBOOK_DIFF_EDITOR_ID = 'workbench.editor.notebookTextDiffEditor'; export interface INotebookEditor extends ICommonNotebookEditor { // from the old IEditor readonly onDidChangeVisibleRanges: Event<void>; readonly onDidChangeSelection: Event<void>; getSelections(): ICellRange[]; visibleRanges: ICellRange[]; textModel?: NotebookTextModel; getId(): string; hasFocus(): boolean; isEmbedded: boolean; cursorNavigationMode: boolean; /** * Notebook view model attached to the current editor */ viewModel: NotebookViewModel | undefined; hasModel(): this is IActiveNotebookEditor; /** * An event emitted when the model of this editor has changed. * @event */ readonly onDidChangeModel: Event<NotebookTextModel | undefined>; readonly onDidFocusEditorWidget: Event<void>; readonly activeKernel: INotebookKernel | undefined; readonly availableKernelCount: number; readonly onDidScroll: Event<void>; readonly onDidChangeAvailableKernels: Event<void>; readonly onDidChangeKernel: Event<void>; readonly onDidChangeActiveCell: Event<void>; isDisposed: boolean; dispose(): void; getId(): string; getDomNode(): HTMLElement; getOverflowContainerDomNode(): HTMLElement; getInnerWebview(): Webview | undefined; getSelectionViewModels(): ICellViewModel[]; /** * Focus the notebook editor cell list */ focus(): void; hasFocus(): boolean; hasWebviewFocus(): boolean; hasOutputTextSelection(): boolean; setOptions(options: NotebookEditorOptions | undefined): Promise<void>; /** * Select & focus cell */ focusElement(cell: ICellViewModel): void; /** * Layout info for the notebook editor */ getLayoutInfo(): NotebookLayoutInfo; getVisibleRangesPlusViewportAboveBelow(): ICellRange[]; /** * Fetch the output renderers for notebook outputs. */ getOutputRenderer(): OutputRenderer; /** * Fetch the contributed kernels for this notebook */ beginComputeContributedKernels(): Promise<INotebookKernel[]>; /** * Insert a new cell around `cell` */ insertNotebookCell(cell: ICellViewModel | undefined, type: CellKind, direction?: 'above' | 'below', initialText?: string, ui?: boolean): CellViewModel | null; /** * Split a given cell into multiple cells of the same type using the selection start positions. */ splitNotebookCell(cell: ICellViewModel): Promise<CellViewModel[] | null>; /** * Delete a cell from the notebook */ deleteNotebookCell(cell: ICellViewModel): Promise<boolean>; /** * Move a cell up one spot */ moveCellUp(cell: ICellViewModel): Promise<ICellViewModel | null>; /** * Move a cell down one spot */ moveCellDown(cell: ICellViewModel): Promise<ICellViewModel | null>; /** * Move a cell to a specific position */ moveCellsToIdx(index: number, length: number, toIdx: number): Promise<ICellViewModel | null>; /** * Focus the container of a cell (the monaco editor inside is not focused). */ focusNotebookCell(cell: ICellViewModel, focus: 'editor' | 'container' | 'output'): void; focusNextNotebookCell(cell: ICellViewModel, focus: 'editor' | 'container' | 'output'): void; /** * Execute the given notebook cell */ executeNotebookCell(cell: ICellViewModel): Promise<void>; /** * Cancel the cell execution */ cancelNotebookCellExecution(cell: ICellViewModel): void; /** * Executes all notebook cells in order */ executeNotebook(): Promise<void>; /** * Cancel the notebook execution */ cancelNotebookExecution(): void; /** * Get current active cell */ getActiveCell(): ICellViewModel | undefined; /** * Layout the cell with a new height */ layoutNotebookCell(cell: ICellViewModel, height: number): Promise<void>; createMarkdownPreview(cell: ICellViewModel): Promise<void>; unhideMarkdownPreviews(cells: readonly ICellViewModel[]): Promise<void>; hideMarkdownPreviews(cells: readonly ICellViewModel[]): Promise<void>; /** * Render the output in webview layer */ createOutput(cell: ICellViewModel, output: IInsetRenderOutput, offset: number): Promise<void>; /** * Remove the output from the webview layer */ removeInset(output: IDisplayOutputViewModel): void; /** * Hide the inset in the webview layer without removing it */ hideInset(output: IDisplayOutputViewModel): void; /** * Send message to the webview for outputs. */ postMessage(forRendererId: string | undefined, message: any): void; /** * Remove class name on the notebook editor root DOM node. */ addClassName(className: string): void; /** * Remove class name on the notebook editor root DOM node. */ removeClassName(className: string): void; deltaCellOutputContainerClassNames(cellId: string, added: string[], removed: string[]): void; /** * Trigger the editor to scroll from scroll event programmatically */ triggerScroll(event: IMouseWheelEvent): void; /** * The range will be revealed with as little scrolling as possible. */ revealCellRangeInView(range: ICellRange): void; /** * Reveal cell into viewport. */ revealInView(cell: ICellViewModel): void; /** * Reveal cell into the top of viewport. */ revealInViewAtTop(cell: ICellViewModel): void; /** * Reveal cell into viewport center. */ revealInCenter(cell: ICellViewModel): void; /** * Reveal cell into viewport center if cell is currently out of the viewport. */ revealInCenterIfOutsideViewport(cell: ICellViewModel): void; /** * Reveal a line in notebook cell into viewport with minimal scrolling. */ revealLineInViewAsync(cell: ICellViewModel, line: number): Promise<void>; /** * Reveal a line in notebook cell into viewport center. */ revealLineInCenterAsync(cell: ICellViewModel, line: number): Promise<void>; /** * Reveal a line in notebook cell into viewport center. */ revealLineInCenterIfOutsideViewportAsync(cell: ICellViewModel, line: number): Promise<void>; /** * Reveal a range in notebook cell into viewport with minimal scrolling. */ revealRangeInViewAsync(cell: ICellViewModel, range: Range): Promise<void>; /** * Reveal a range in notebook cell into viewport center. */ revealRangeInCenterAsync(cell: ICellViewModel, range: Range): Promise<void>; /** * Reveal a range in notebook cell into viewport center. */ revealRangeInCenterIfOutsideViewportAsync(cell: ICellViewModel, range: Range): Promise<void>; /** * Get the view index of a cell */ getViewIndex(cell: ICellViewModel): number; /** * Get the view height of a cell (from the list view) */ getViewHeight(cell: ICellViewModel): number; /** * @param startIndex Inclusive * @param endIndex Exclusive */ getCellRangeFromViewRange(startIndex: number, endIndex: number): ICellRange | undefined; /** * @param startIndex Inclusive * @param endIndex Exclusive */ getCellsFromViewRange(startIndex: number, endIndex: number): ReadonlyArray<ICellViewModel>; /** * Set hidden areas on cell text models. */ setHiddenAreas(_ranges: ICellRange[]): boolean; setCellEditorSelection(cell: ICellViewModel, selection: Range): void; deltaCellDecorations(oldDecorations: string[], newDecorations: INotebookDeltaDecoration[]): string[]; /** * Change the decorations on cells. * The notebook is virtualized and this method should be called to create/delete editor decorations safely. */ changeModelDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T): T | null; setEditorDecorations(key: string, range: ICellRange): void; removeEditorDecorations(key: string): void; /** * An event emitted on a "mouseup". * @event */ onMouseUp(listener: (e: INotebookEditorMouseEvent) => void): IDisposable; /** * An event emitted on a "mousedown". * @event */ onMouseDown(listener: (e: INotebookEditorMouseEvent) => void): IDisposable; /** * Get a contribution of this editor. * @id Unique identifier of the contribution. * @return The contribution or null if contribution not found. */ getContribution<T extends INotebookEditorContribution>(id: string): T; getCellByInfo(cellInfo: ICommonCellInfo): ICellViewModel; getCellById(cellId: string): ICellViewModel | undefined; updateOutputHeight(cellInfo: ICommonCellInfo, output: IDisplayOutputViewModel, height: number, isInit: boolean, source?: string): void; } export interface INotebookCellList { isDisposed: boolean; viewModel: NotebookViewModel | null; readonly contextKeyService: IContextKeyService; element(index: number): ICellViewModel | undefined; elementAt(position: number): ICellViewModel | undefined; elementHeight(element: ICellViewModel): number; onWillScroll: Event<ScrollEvent>; onDidScroll: Event<ScrollEvent>; onDidChangeFocus: Event<IListEvent<ICellViewModel>>; onDidChangeContentHeight: Event<number>; onDidChangeVisibleRanges: Event<void>; visibleRanges: ICellRange[]; scrollTop: number; scrollHeight: number; scrollLeft: number; length: number; rowsContainer: HTMLElement; readonly onDidRemoveOutputs: Event<readonly ICellOutputViewModel[]>; readonly onDidHideOutputs: Event<readonly ICellOutputViewModel[]>; readonly onDidRemoveCellsFromView: Event<readonly ICellViewModel[]>; readonly onMouseUp: Event<IListMouseEvent<CellViewModel>>; readonly onMouseDown: Event<IListMouseEvent<CellViewModel>>; readonly onContextMenu: Event<IListContextMenuEvent<CellViewModel>>; detachViewModel(): void; attachViewModel(viewModel: NotebookViewModel): void; clear(): void; getViewIndex(cell: ICellViewModel): number | undefined; getViewIndex2(modelIndex: number): number | undefined; getModelIndex(cell: CellViewModel): number | undefined; getModelIndex2(viewIndex: number): number | undefined; getVisibleRangesPlusViewportAboveBelow(): ICellRange[]; focusElement(element: ICellViewModel): void; selectElements(elements: ICellViewModel[]): void; getFocusedElements(): ICellViewModel[]; getSelectedElements(): ICellViewModel[]; revealElementsInView(range: ICellRange): void; revealElementInView(element: ICellViewModel): void; revealElementInViewAtTop(element: ICellViewModel): void; revealElementInCenterIfOutsideViewport(element: ICellViewModel): void; revealElementInCenter(element: ICellViewModel): void; revealElementInCenterIfOutsideViewportAsync(element: ICellViewModel): Promise<void>; revealElementLineInViewAsync(element: ICellViewModel, line: number): Promise<void>; revealElementLineInCenterAsync(element: ICellViewModel, line: number): Promise<void>; revealElementLineInCenterIfOutsideViewportAsync(element: ICellViewModel, line: number): Promise<void>; revealElementRangeInViewAsync(element: ICellViewModel, range: Range): Promise<void>; revealElementRangeInCenterAsync(element: ICellViewModel, range: Range): Promise<void>; revealElementRangeInCenterIfOutsideViewportAsync(element: ICellViewModel, range: Range): Promise<void>; setHiddenAreas(_ranges: ICellRange[], triggerViewUpdate: boolean): boolean; domElementOfElement(element: ICellViewModel): HTMLElement | null; focusView(): void; getAbsoluteTopOfElement(element: ICellViewModel): number; triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent): void; updateElementHeight2(element: ICellViewModel, size: number): void; domFocus(): void; setCellSelection(element: ICellViewModel, range: Range): void; style(styles: IListStyles): void; getRenderHeight(): number; updateOptions(options: IListOptions<ICellViewModel>): void; layout(height?: number, width?: number): void; dispose(): void; } export interface BaseCellRenderTemplate { rootContainer: HTMLElement; editorPart: HTMLElement; collapsedPart: HTMLElement; expandButton: HTMLElement; contextKeyService: IContextKeyService; container: HTMLElement; cellContainer: HTMLElement; decorationContainer: HTMLElement; toolbar: ToolBar; deleteToolbar: ToolBar; betweenCellToolbar: ToolBar; focusIndicatorLeft: HTMLElement; focusIndicatorRight: HTMLElement; disposables: DisposableStore; elementDisposables: DisposableStore; bottomCellContainer: HTMLElement; currentRenderedCell?: ICellViewModel; statusBar: CellEditorStatusBar; titleMenu: IMenu; toJSON: () => object; } export interface MarkdownCellRenderTemplate extends BaseCellRenderTemplate { editorContainer: HTMLElement; foldingIndicator: HTMLElement; focusIndicatorBottom: HTMLElement; currentEditor?: ICodeEditor; readonly useRenderer: boolean; } export interface CodeCellRenderTemplate extends BaseCellRenderTemplate { cellRunState: RunStateRenderer; runToolbar: ToolBar; runButtonContainer: HTMLElement; executionOrderLabel: HTMLElement; outputContainer: HTMLElement; outputShowMoreContainer: HTMLElement; focusSinkElement: HTMLElement; editor: ICodeEditor; progressBar: ProgressBar; timer: TimerRenderer; focusIndicatorRight: HTMLElement; focusIndicatorBottom: HTMLElement; dragHandle: HTMLElement; } export function isCodeCellRenderTemplate(templateData: BaseCellRenderTemplate): templateData is CodeCellRenderTemplate { return !!(templateData as CodeCellRenderTemplate).runToolbar; } export interface IOutputTransformContribution { getType(): RenderOutputType; getMimetypes(): string[]; /** * Dispose this contribution. */ dispose(): void; /** * Returns contents to place in the webview inset, or the {@link IRenderNoOutput}. * This call is allowed to have side effects, such as placing output * directly into the container element. */ render(output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement, notebookUri: URI | undefined): IRenderOutput; } export interface CellFindMatch { cell: CellViewModel; matches: FindMatch[]; } export enum CellRevealType { Line, Range } export enum CellRevealPosition { Top, Center, Bottom } export enum CellEditState { /** * Default state. * For markdown cell, it's Markdown preview. * For code cell, the browser focus should be on the container instead of the editor */ Preview, /** * Eding mode. Source for markdown or code is rendered in editors and the state will be persistent. */ Editing } export enum CellFocusMode { Container, Editor } export enum CursorAtBoundary { None, Top, Bottom, Both } export interface CellViewModelStateChangeEvent { readonly metadataChanged?: boolean; readonly runStateChanged?: boolean; readonly selectionChanged?: boolean; readonly focusModeChanged?: boolean; readonly editStateChanged?: boolean; readonly languageChanged?: boolean; readonly foldingStateChanged?: boolean; readonly contentChanged?: boolean; readonly outputIsHoveredChanged?: boolean; readonly outputIsFocusedChanged?: boolean; readonly cellIsHoveredChanged?: boolean; readonly cellLineNumberChanged?: boolean; } export function cellRangesEqual(a: ICellRange[], b: ICellRange[]) { a = reduceCellRanges(a); b = reduceCellRanges(b); if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (a[i].start !== b[i].start || a[i].end !== b[i].end) { return false; } } return true; } /** * @param _ranges */ export function reduceCellRanges(_ranges: ICellRange[]): ICellRange[] { if (!_ranges.length) { return []; } const ranges = _ranges.sort((a, b) => a.start - b.start); const result: ICellRange[] = []; let currentRangeStart = ranges[0].start; let currentRangeEnd = ranges[0].end + 1; for (let i = 0, len = ranges.length; i < len; i++) { const range = ranges[i]; if (range.start > currentRangeEnd) { result.push({ start: currentRangeStart, end: currentRangeEnd - 1 }); currentRangeStart = range.start; currentRangeEnd = range.end + 1; } else if (range.end + 1 > currentRangeEnd) { currentRangeEnd = range.end + 1; } } result.push({ start: currentRangeStart, end: currentRangeEnd - 1 }); return result; } export function getVisibleCells(cells: CellViewModel[], hiddenRanges: ICellRange[]) { if (!hiddenRanges.length) { return cells; } let start = 0; let hiddenRangeIndex = 0; const result: CellViewModel[] = []; while (start < cells.length && hiddenRangeIndex < hiddenRanges.length) { if (start < hiddenRanges[hiddenRangeIndex].start) { result.push(...cells.slice(start, hiddenRanges[hiddenRangeIndex].start)); } start = hiddenRanges[hiddenRangeIndex].end + 1; hiddenRangeIndex++; } if (start < cells.length) { result.push(...cells.slice(start)); } return result; } export function getNotebookEditorFromEditorPane(editorPane?: IEditorPane): INotebookEditor | undefined { return editorPane?.getId() === NOTEBOOK_EDITOR_ID ? editorPane.getControl() as INotebookEditor | undefined : undefined; } let EDITOR_TOP_PADDING = 12; const editorTopPaddingChangeEmitter = new Emitter<void>(); export const EditorTopPaddingChangeEvent = editorTopPaddingChangeEmitter.event; export function updateEditorTopPadding(top: number) { EDITOR_TOP_PADDING = top; editorTopPaddingChangeEmitter.fire(); } export function getEditorTopPadding() { return EDITOR_TOP_PADDING; } /** * ranges: model selections * this will convert model selections to view indexes first, and then include the hidden ranges in the list view */ export function expandCellRangesWithHiddenCells(editor: INotebookEditor, viewModel: NotebookViewModel, ranges: ICellRange[]) { // assuming ranges are sorted and no overlap const indexes = cellRangesToIndexes(ranges); let modelRanges: ICellRange[] = []; indexes.forEach(index => { const viewCell = viewModel.viewCells[index]; if (!viewCell) { return; } const viewIndex = editor.getViewIndex(viewCell); if (viewIndex < 0) { return; } const nextViewIndex = viewIndex + 1; const range = editor.getCellRangeFromViewRange(viewIndex, nextViewIndex); if (range) { modelRanges.push(range); } }); return reduceRanges(modelRanges); } /** * Return a set of ranges for the cells matching the given predicate */ export function getRanges(cells: ICellViewModel[], included: (cell: ICellViewModel) => boolean): ICellRange[] { const ranges: ICellRange[] = []; let currentRange: ICellRange | undefined; cells.forEach((cell, idx) => { if (included(cell)) { if (!currentRange) { currentRange = { start: idx, end: idx + 1 }; ranges.push(currentRange); } else { currentRange.end = idx + 1; } } else { currentRange = undefined; } }); return ranges; }
src/vs/workbench/contrib/notebook/browser/notebookBrowser.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00307262409478426, 0.00023461213277187198, 0.0001642935094423592, 0.0001727946801111102, 0.00031469386885873973 ]
{ "id": 9, "code_window": [ "\t\t\t\tthis._proxy.$removeKernel(handle);\n", "\t\t\t}\n", "\t\t};\n", "\t}\n", "\n", "\t$acceptSelection(handle: number, value: boolean): void {\n", "\t\tconst obj = this._kernelData.get(handle);\n", "\t\tif (obj) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t$acceptSelection(handle: number, uri: UriComponents, value: boolean): void {\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 130 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { WebviewOverlay } from 'vs/workbench/contrib/webview/browser/webview'; export const IWebviewViewService = createDecorator<IWebviewViewService>('webviewViewService'); export interface WebviewView { title?: string; description?: string; readonly webview: WebviewOverlay; readonly onDidChangeVisibility: Event<boolean>; readonly onDispose: Event<void>; dispose(): void; show(preserveFocus: boolean): void; } export interface IWebviewViewResolver { resolve(webviewView: WebviewView, cancellation: CancellationToken): Promise<void>; } export interface IWebviewViewService { readonly _serviceBrand: undefined; readonly onNewResolverRegistered: Event<{ readonly viewType: string }>; register(type: string, resolver: IWebviewViewResolver): IDisposable; resolve(viewType: string, webview: WebviewView, cancellation: CancellationToken): Promise<void>; } export class WebviewViewService extends Disposable implements IWebviewViewService { readonly _serviceBrand: undefined; private readonly _resolvers = new Map<string, IWebviewViewResolver>(); private readonly _awaitingRevival = new Map<string, { webview: WebviewView, resolve: () => void }>(); private readonly _onNewResolverRegistered = this._register(new Emitter<{ readonly viewType: string }>()); public readonly onNewResolverRegistered = this._onNewResolverRegistered.event; register(viewType: string, resolver: IWebviewViewResolver): IDisposable { if (this._resolvers.has(viewType)) { throw new Error(`View resolver already registered for ${viewType}`); } this._resolvers.set(viewType, resolver); this._onNewResolverRegistered.fire({ viewType: viewType }); const pending = this._awaitingRevival.get(viewType); if (pending) { resolver.resolve(pending.webview, CancellationToken.None).then(() => { this._awaitingRevival.delete(viewType); pending.resolve(); }); } return toDisposable(() => { this._resolvers.delete(viewType); }); } resolve(viewType: string, webview: WebviewView, cancellation: CancellationToken): Promise<void> { const resolver = this._resolvers.get(viewType); if (!resolver) { if (this._awaitingRevival.has(viewType)) { throw new Error('View already awaiting revival'); } let resolve: () => void; const p = new Promise<void>(r => resolve = r); this._awaitingRevival.set(viewType, { webview, resolve: resolve! }); return p; } return resolver.resolve(webview, cancellation); } }
src/vs/workbench/contrib/webviewView/browser/webviewViewService.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017875453340820968, 0.00017279063467867672, 0.00016708587645553052, 0.00017284360365010798, 0.000003311600721644936 ]
{ "id": 9, "code_window": [ "\t\t\t\tthis._proxy.$removeKernel(handle);\n", "\t\t\t}\n", "\t\t};\n", "\t}\n", "\n", "\t$acceptSelection(handle: number, value: boolean): void {\n", "\t\tconst obj = this._kernelData.get(handle);\n", "\t\tif (obj) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t$acceptSelection(handle: number, uri: UriComponents, value: boolean): void {\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 130 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as strings from 'vs/base/common/strings'; import * as stringBuilder from 'vs/editor/common/core/stringBuilder'; import { Range } from 'vs/editor/common/core/range'; import { LanguageIdentifier } from 'vs/editor/common/modes'; import { CharacterPair } from 'vs/editor/common/modes/languageConfiguration'; interface InternalBracket { open: string[]; close: string[]; } export class RichEditBracket { _richEditBracketBrand: void; readonly languageIdentifier: LanguageIdentifier; readonly index: number; readonly open: string[]; readonly close: string[]; readonly forwardRegex: RegExp; readonly reversedRegex: RegExp; private readonly _openSet: Set<string>; private readonly _closeSet: Set<string>; constructor(languageIdentifier: LanguageIdentifier, index: number, open: string[], close: string[], forwardRegex: RegExp, reversedRegex: RegExp) { this.languageIdentifier = languageIdentifier; this.index = index; this.open = open; this.close = close; this.forwardRegex = forwardRegex; this.reversedRegex = reversedRegex; this._openSet = RichEditBracket._toSet(this.open); this._closeSet = RichEditBracket._toSet(this.close); } public isOpen(text: string) { return this._openSet.has(text); } public isClose(text: string) { return this._closeSet.has(text); } private static _toSet(arr: string[]): Set<string> { const result = new Set<string>(); for (const element of arr) { result.add(element); } return result; } } function groupFuzzyBrackets(brackets: CharacterPair[]): InternalBracket[] { const N = brackets.length; brackets = brackets.map(b => [b[0].toLowerCase(), b[1].toLowerCase()]); const group: number[] = []; for (let i = 0; i < N; i++) { group[i] = i; } const areOverlapping = (a: CharacterPair, b: CharacterPair) => { const [aOpen, aClose] = a; const [bOpen, bClose] = b; return (aOpen === bOpen || aOpen === bClose || aClose === bOpen || aClose === bClose); }; const mergeGroups = (g1: number, g2: number) => { const newG = Math.min(g1, g2); const oldG = Math.max(g1, g2); for (let i = 0; i < N; i++) { if (group[i] === oldG) { group[i] = newG; } } }; // group together brackets that have the same open or the same close sequence for (let i = 0; i < N; i++) { const a = brackets[i]; for (let j = i + 1; j < N; j++) { const b = brackets[j]; if (areOverlapping(a, b)) { mergeGroups(group[i], group[j]); } } } const result: InternalBracket[] = []; for (let g = 0; g < N; g++) { let currentOpen: string[] = []; let currentClose: string[] = []; for (let i = 0; i < N; i++) { if (group[i] === g) { const [open, close] = brackets[i]; currentOpen.push(open); currentClose.push(close); } } if (currentOpen.length > 0) { result.push({ open: currentOpen, close: currentClose }); } } return result; } export class RichEditBrackets { _richEditBracketsBrand: void; public readonly brackets: RichEditBracket[]; public readonly forwardRegex: RegExp; public readonly reversedRegex: RegExp; public readonly maxBracketLength: number; public readonly textIsBracket: { [text: string]: RichEditBracket; }; public readonly textIsOpenBracket: { [text: string]: boolean; }; constructor(languageIdentifier: LanguageIdentifier, _brackets: CharacterPair[]) { const brackets = groupFuzzyBrackets(_brackets); this.brackets = brackets.map((b, index) => { return new RichEditBracket( languageIdentifier, index, b.open, b.close, getRegexForBracketPair(b.open, b.close, brackets, index), getReversedRegexForBracketPair(b.open, b.close, brackets, index) ); }); this.forwardRegex = getRegexForBrackets(this.brackets); this.reversedRegex = getReversedRegexForBrackets(this.brackets); this.textIsBracket = {}; this.textIsOpenBracket = {}; this.maxBracketLength = 0; for (const bracket of this.brackets) { for (const open of bracket.open) { this.textIsBracket[open] = bracket; this.textIsOpenBracket[open] = true; this.maxBracketLength = Math.max(this.maxBracketLength, open.length); } for (const close of bracket.close) { this.textIsBracket[close] = bracket; this.textIsOpenBracket[close] = false; this.maxBracketLength = Math.max(this.maxBracketLength, close.length); } } } } function collectSuperstrings(str: string, brackets: InternalBracket[], currentIndex: number, dest: string[]): void { for (let i = 0, len = brackets.length; i < len; i++) { if (i === currentIndex) { continue; } const bracket = brackets[i]; for (const open of bracket.open) { if (open.indexOf(str) >= 0) { dest.push(open); } } for (const close of bracket.close) { if (close.indexOf(str) >= 0) { dest.push(close); } } } } function lengthcmp(a: string, b: string) { return a.length - b.length; } function unique(arr: string[]): string[] { if (arr.length <= 1) { return arr; } const result: string[] = []; const seen = new Set<string>(); for (const element of arr) { if (seen.has(element)) { continue; } result.push(element); seen.add(element); } return result; } function getRegexForBracketPair(open: string[], close: string[], brackets: InternalBracket[], currentIndex: number): RegExp { // search in all brackets for other brackets that are a superstring of these brackets let pieces: string[] = []; pieces = pieces.concat(open); pieces = pieces.concat(close); for (let i = 0, len = pieces.length; i < len; i++) { collectSuperstrings(pieces[i], brackets, currentIndex, pieces); } pieces = unique(pieces); pieces.sort(lengthcmp); pieces.reverse(); return createBracketOrRegExp(pieces); } function getReversedRegexForBracketPair(open: string[], close: string[], brackets: InternalBracket[], currentIndex: number): RegExp { // search in all brackets for other brackets that are a superstring of these brackets let pieces: string[] = []; pieces = pieces.concat(open); pieces = pieces.concat(close); for (let i = 0, len = pieces.length; i < len; i++) { collectSuperstrings(pieces[i], brackets, currentIndex, pieces); } pieces = unique(pieces); pieces.sort(lengthcmp); pieces.reverse(); return createBracketOrRegExp(pieces.map(toReversedString)); } function getRegexForBrackets(brackets: RichEditBracket[]): RegExp { let pieces: string[] = []; for (const bracket of brackets) { for (const open of bracket.open) { pieces.push(open); } for (const close of bracket.close) { pieces.push(close); } } pieces = unique(pieces); return createBracketOrRegExp(pieces); } function getReversedRegexForBrackets(brackets: RichEditBracket[]): RegExp { let pieces: string[] = []; for (const bracket of brackets) { for (const open of bracket.open) { pieces.push(open); } for (const close of bracket.close) { pieces.push(close); } } pieces = unique(pieces); return createBracketOrRegExp(pieces.map(toReversedString)); } function prepareBracketForRegExp(str: string): string { // This bracket pair uses letters like e.g. "begin" - "end" const insertWordBoundaries = (/^[\w ]+$/.test(str)); str = strings.escapeRegExpCharacters(str); return (insertWordBoundaries ? `\\b${str}\\b` : str); } function createBracketOrRegExp(pieces: string[]): RegExp { let regexStr = `(${pieces.map(prepareBracketForRegExp).join(')|(')})`; return strings.createRegExp(regexStr, true); } const toReversedString = (function () { function reverse(str: string): string { if (stringBuilder.hasTextDecoder) { // create a Uint16Array and then use a TextDecoder to create a string const arr = new Uint16Array(str.length); let offset = 0; for (let i = str.length - 1; i >= 0; i--) { arr[offset++] = str.charCodeAt(i); } return stringBuilder.getPlatformTextDecoder().decode(arr); } else { let result: string[] = [], resultLen = 0; for (let i = str.length - 1; i >= 0; i--) { result[resultLen++] = str.charAt(i); } return result.join(''); } } let lastInput: string | null = null; let lastOutput: string | null = null; return function toReversedString(str: string): string { if (lastInput !== str) { lastInput = str; lastOutput = reverse(lastInput); } return lastOutput!; }; })(); export class BracketsUtils { private static _findPrevBracketInText(reversedBracketRegex: RegExp, lineNumber: number, reversedText: string, offset: number): Range | null { let m = reversedText.match(reversedBracketRegex); if (!m) { return null; } let matchOffset = reversedText.length - (m.index || 0); let matchLength = m[0].length; let absoluteMatchOffset = offset + matchOffset; return new Range(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1); } public static findPrevBracketInRange(reversedBracketRegex: RegExp, lineNumber: number, lineText: string, startOffset: number, endOffset: number): Range | null { // Because JS does not support backwards regex search, we search forwards in a reversed string with a reversed regex ;) const reversedLineText = toReversedString(lineText); const reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset); return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedSubstr, startOffset); } public static findNextBracketInText(bracketRegex: RegExp, lineNumber: number, text: string, offset: number): Range | null { let m = text.match(bracketRegex); if (!m) { return null; } let matchOffset = m.index || 0; let matchLength = m[0].length; if (matchLength === 0) { return null; } let absoluteMatchOffset = offset + matchOffset; return new Range(lineNumber, absoluteMatchOffset + 1, lineNumber, absoluteMatchOffset + 1 + matchLength); } public static findNextBracketInRange(bracketRegex: RegExp, lineNumber: number, lineText: string, startOffset: number, endOffset: number): Range | null { const substr = lineText.substring(startOffset, endOffset); return this.findNextBracketInText(bracketRegex, lineNumber, substr, startOffset); } }
src/vs/editor/common/modes/supports/richEditBrackets.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00038171594496816397, 0.0001871336280601099, 0.00016592926112934947, 0.00017323068459518254, 0.000042506257159402594 ]
{ "id": 9, "code_window": [ "\t\t\t\tthis._proxy.$removeKernel(handle);\n", "\t\t\t}\n", "\t\t};\n", "\t}\n", "\n", "\t$acceptSelection(handle: number, value: boolean): void {\n", "\t\tconst obj = this._kernelData.get(handle);\n", "\t\tif (obj) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t$acceptSelection(handle: number, uri: UriComponents, value: boolean): void {\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 130 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IssueReporterData } from 'vs/platform/issue/common/issue'; export const IWorkbenchIssueService = createDecorator<IWorkbenchIssueService>('workbenchIssueService'); export interface IWorkbenchIssueService { readonly _serviceBrand: undefined; openReporter(dataOverrides?: Partial<IssueReporterData>): Promise<void>; openProcessExplorer(): Promise<void>; }
src/vs/workbench/services/issue/common/issue.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.0001767282810760662, 0.00017280952306464314, 0.00016889075050130486, 0.00017280952306464314, 0.0000039187652873806655 ]
{ "id": 10, "code_window": [ "\t\tconst obj = this._kernelData.get(handle);\n", "\t\tif (obj) {\n", "\t\t\tobj.selected = value;\n", "\t\t\tobj.onDidChangeSelection.fire(value);\n", "\t\t}\n", "\t}\n", "\n", "\t$executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void {\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tobj.onDidChangeSelection.fire({\n", "\t\t\t\tselected: value,\n", "\t\t\t\turi: URI.revive(uri)\n", "\t\t\t});\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 133 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ICellRange, INotebookTextModel } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { NotebookSelector } from 'vs/workbench/contrib/notebook/common/notebookSelector'; export interface INotebookKernel2ChangeEvent { label?: true; description?: true; detail?: true; isPreferred?: true; supportedLanguages?: true; hasExecutionOrder?: true; } export interface INotebookKernel2 { readonly id: string; readonly selector: NotebookSelector readonly extensionId: ExtensionIdentifier; readonly onDidChange: Event<INotebookKernel2ChangeEvent>; label: string; description?: string; detail?: string; isPreferred?: boolean; supportedLanguages: string[]; implementsExecutionOrder: boolean; implementsInterrupt: boolean; localResourceRoot: URI; preloadUris: URI[]; preloadProvides: string[]; setSelected(value: boolean): void; executeCells(uri: URI, ranges: ICellRange[]): void; cancelCells(uri: URI, ranges: ICellRange[]): void } export const INotebookKernelService = createDecorator<INotebookKernelService>('INotebookKernelService'); export interface INotebookKernelService { _serviceBrand: undefined; onDidAddKernel: Event<INotebookKernel2>; onDidRemoveKernel: Event<INotebookKernel2>; addKernel(kernel: INotebookKernel2): IDisposable; selectKernels(notebook: INotebookTextModel): INotebookKernel2[]; }
src/vs/workbench/contrib/notebook/common/notebookKernelService.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.004474569112062454, 0.0016580010997131467, 0.00017490769096184522, 0.0009369998588226736, 0.00166518974583596 ]
{ "id": 10, "code_window": [ "\t\tconst obj = this._kernelData.get(handle);\n", "\t\tif (obj) {\n", "\t\t\tobj.selected = value;\n", "\t\t\tobj.onDidChangeSelection.fire(value);\n", "\t\t}\n", "\t}\n", "\n", "\t$executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void {\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tobj.onDidChangeSelection.fire({\n", "\t\t\t\tselected: value,\n", "\t\t\t\turi: URI.revive(uri)\n", "\t\t\t});\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 133 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { Color, RGBA } from 'vs/base/common/color'; import { activeContrastBorder, editorBackground, editorForeground, registerColor, editorWarningForeground, editorInfoForeground, editorWarningBorder, editorInfoBorder, contrastBorder, editorFindMatchHighlight } from 'vs/platform/theme/common/colorRegistry'; import { registerThemingParticipant } from 'vs/platform/theme/common/themeService'; /** * Definition of the editor colors */ export const editorLineHighlight = registerColor('editor.lineHighlightBackground', { dark: null, light: null, hc: null }, nls.localize('lineHighlight', 'Background color for the highlight of line at the cursor position.')); export const editorLineHighlightBorder = registerColor('editor.lineHighlightBorder', { dark: '#282828', light: '#eeeeee', hc: '#f38518' }, nls.localize('lineHighlightBorderBox', 'Background color for the border around the line at the cursor position.')); export const editorRangeHighlight = registerColor('editor.rangeHighlightBackground', { dark: '#ffffff0b', light: '#fdff0033', hc: null }, nls.localize('rangeHighlight', 'Background color of highlighted ranges, like by quick open and find features. The color must not be opaque so as not to hide underlying decorations.'), true); export const editorRangeHighlightBorder = registerColor('editor.rangeHighlightBorder', { dark: null, light: null, hc: activeContrastBorder }, nls.localize('rangeHighlightBorder', 'Background color of the border around highlighted ranges.'), true); export const editorSymbolHighlight = registerColor('editor.symbolHighlightBackground', { dark: editorFindMatchHighlight, light: editorFindMatchHighlight, hc: null }, nls.localize('symbolHighlight', 'Background color of highlighted symbol, like for go to definition or go next/previous symbol. The color must not be opaque so as not to hide underlying decorations.'), true); export const editorSymbolHighlightBorder = registerColor('editor.symbolHighlightBorder', { dark: null, light: null, hc: activeContrastBorder }, nls.localize('symbolHighlightBorder', 'Background color of the border around highlighted symbols.'), true); export const editorCursorForeground = registerColor('editorCursor.foreground', { dark: '#AEAFAD', light: Color.black, hc: Color.white }, nls.localize('caret', 'Color of the editor cursor.')); export const editorCursorBackground = registerColor('editorCursor.background', null, nls.localize('editorCursorBackground', 'The background color of the editor cursor. Allows customizing the color of a character overlapped by a block cursor.')); export const editorWhitespaces = registerColor('editorWhitespace.foreground', { dark: '#e3e4e229', light: '#33333333', hc: '#e3e4e229' }, nls.localize('editorWhitespaces', 'Color of whitespace characters in the editor.')); export const editorIndentGuides = registerColor('editorIndentGuide.background', { dark: editorWhitespaces, light: editorWhitespaces, hc: editorWhitespaces }, nls.localize('editorIndentGuides', 'Color of the editor indentation guides.')); export const editorActiveIndentGuides = registerColor('editorIndentGuide.activeBackground', { dark: editorWhitespaces, light: editorWhitespaces, hc: editorWhitespaces }, nls.localize('editorActiveIndentGuide', 'Color of the active editor indentation guides.')); export const editorLineNumbers = registerColor('editorLineNumber.foreground', { dark: '#858585', light: '#237893', hc: Color.white }, nls.localize('editorLineNumbers', 'Color of editor line numbers.')); const deprecatedEditorActiveLineNumber = registerColor('editorActiveLineNumber.foreground', { dark: '#c6c6c6', light: '#0B216F', hc: activeContrastBorder }, nls.localize('editorActiveLineNumber', 'Color of editor active line number'), false, nls.localize('deprecatedEditorActiveLineNumber', 'Id is deprecated. Use \'editorLineNumber.activeForeground\' instead.')); export const editorActiveLineNumber = registerColor('editorLineNumber.activeForeground', { dark: deprecatedEditorActiveLineNumber, light: deprecatedEditorActiveLineNumber, hc: deprecatedEditorActiveLineNumber }, nls.localize('editorActiveLineNumber', 'Color of editor active line number')); export const editorRuler = registerColor('editorRuler.foreground', { dark: '#5A5A5A', light: Color.lightgrey, hc: Color.white }, nls.localize('editorRuler', 'Color of the editor rulers.')); export const editorCodeLensForeground = registerColor('editorCodeLens.foreground', { dark: '#999999', light: '#999999', hc: '#999999' }, nls.localize('editorCodeLensForeground', 'Foreground color of editor CodeLens')); export const editorBracketMatchBackground = registerColor('editorBracketMatch.background', { dark: '#0064001a', light: '#0064001a', hc: '#0064001a' }, nls.localize('editorBracketMatchBackground', 'Background color behind matching brackets')); export const editorBracketMatchBorder = registerColor('editorBracketMatch.border', { dark: '#888', light: '#B9B9B9', hc: contrastBorder }, nls.localize('editorBracketMatchBorder', 'Color for matching brackets boxes')); export const editorOverviewRulerBorder = registerColor('editorOverviewRuler.border', { dark: '#7f7f7f4d', light: '#7f7f7f4d', hc: '#7f7f7f4d' }, nls.localize('editorOverviewRulerBorder', 'Color of the overview ruler border.')); export const editorOverviewRulerBackground = registerColor('editorOverviewRuler.background', null, nls.localize('editorOverviewRulerBackground', 'Background color of the editor overview ruler. Only used when the minimap is enabled and placed on the right side of the editor.')); export const editorGutter = registerColor('editorGutter.background', { dark: editorBackground, light: editorBackground, hc: editorBackground }, nls.localize('editorGutter', 'Background color of the editor gutter. The gutter contains the glyph margins and the line numbers.')); export const editorUnnecessaryCodeBorder = registerColor('editorUnnecessaryCode.border', { dark: null, light: null, hc: Color.fromHex('#fff').transparent(0.8) }, nls.localize('unnecessaryCodeBorder', 'Border color of unnecessary (unused) source code in the editor.')); export const editorUnnecessaryCodeOpacity = registerColor('editorUnnecessaryCode.opacity', { dark: Color.fromHex('#000a'), light: Color.fromHex('#0007'), hc: null }, nls.localize('unnecessaryCodeOpacity', 'Opacity of unnecessary (unused) source code in the editor. For example, "#000000c0" will render the code with 75% opacity. For high contrast themes, use the \'editorUnnecessaryCode.border\' theme color to underline unnecessary code instead of fading it out.')); const rulerRangeDefault = new Color(new RGBA(0, 122, 204, 0.6)); export const overviewRulerRangeHighlight = registerColor('editorOverviewRuler.rangeHighlightForeground', { dark: rulerRangeDefault, light: rulerRangeDefault, hc: rulerRangeDefault }, nls.localize('overviewRulerRangeHighlight', 'Overview ruler marker color for range highlights. The color must not be opaque so as not to hide underlying decorations.'), true); export const overviewRulerError = registerColor('editorOverviewRuler.errorForeground', { dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hc: new Color(new RGBA(255, 50, 50, 1)) }, nls.localize('overviewRuleError', 'Overview ruler marker color for errors.')); export const overviewRulerWarning = registerColor('editorOverviewRuler.warningForeground', { dark: editorWarningForeground, light: editorWarningForeground, hc: editorWarningBorder }, nls.localize('overviewRuleWarning', 'Overview ruler marker color for warnings.')); export const overviewRulerInfo = registerColor('editorOverviewRuler.infoForeground', { dark: editorInfoForeground, light: editorInfoForeground, hc: editorInfoBorder }, nls.localize('overviewRuleInfo', 'Overview ruler marker color for infos.')); // contains all color rules that used to defined in editor/browser/widget/editor.css registerThemingParticipant((theme, collector) => { const background = theme.getColor(editorBackground); if (background) { collector.addRule(`.monaco-editor, .monaco-editor-background, .monaco-editor .inputarea.ime-input { background-color: ${background}; }`); } const foreground = theme.getColor(editorForeground); if (foreground) { collector.addRule(`.monaco-editor, .monaco-editor .inputarea.ime-input { color: ${foreground}; }`); } const gutter = theme.getColor(editorGutter); if (gutter) { collector.addRule(`.monaco-editor .margin { background-color: ${gutter}; }`); } const rangeHighlight = theme.getColor(editorRangeHighlight); if (rangeHighlight) { collector.addRule(`.monaco-editor .rangeHighlight { background-color: ${rangeHighlight}; }`); } const rangeHighlightBorder = theme.getColor(editorRangeHighlightBorder); if (rangeHighlightBorder) { collector.addRule(`.monaco-editor .rangeHighlight { border: 1px ${theme.type === 'hc' ? 'dotted' : 'solid'} ${rangeHighlightBorder}; }`); } const symbolHighlight = theme.getColor(editorSymbolHighlight); if (symbolHighlight) { collector.addRule(`.monaco-editor .symbolHighlight { background-color: ${symbolHighlight}; }`); } const symbolHighlightBorder = theme.getColor(editorSymbolHighlightBorder); if (symbolHighlightBorder) { collector.addRule(`.monaco-editor .symbolHighlight { border: 1px ${theme.type === 'hc' ? 'dotted' : 'solid'} ${symbolHighlightBorder}; }`); } const invisibles = theme.getColor(editorWhitespaces); if (invisibles) { collector.addRule(`.monaco-editor .mtkw { color: ${invisibles} !important; }`); collector.addRule(`.monaco-editor .mtkz { color: ${invisibles} !important; }`); } });
src/vs/editor/common/view/editorColorRegistry.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00018058554269373417, 0.00017412556917406619, 0.0001663509610807523, 0.0001752152165863663, 0.000004314971192798112 ]
{ "id": 10, "code_window": [ "\t\tconst obj = this._kernelData.get(handle);\n", "\t\tif (obj) {\n", "\t\t\tobj.selected = value;\n", "\t\t\tobj.onDidChangeSelection.fire(value);\n", "\t\t}\n", "\t}\n", "\n", "\t$executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void {\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tobj.onDidChangeSelection.fire({\n", "\t\t\t\tselected: value,\n", "\t\t\t\turi: URI.revive(uri)\n", "\t\t\t});\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 133 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'mocha'; import * as assert from 'assert'; import { Selection } from 'vscode'; import { withRandomFileEditor, closeAllEditors } from './testUtils'; import { incrementDecrement as incrementDecrementImpl } from '../incrementDecrement'; function incrementDecrement(delta: number): Thenable<boolean> { const result = incrementDecrementImpl(delta); assert.ok(result); return result!; } suite('Tests for Increment/Decrement Emmet Commands', () => { teardown(closeAllEditors); const contents = ` hello 123.43 there hello 999.9 there hello 100 there `; test('incrementNumberByOne', function (): any { return withRandomFileEditor(contents, 'txt', async (editor, doc) => { editor.selections = [new Selection(1, 7, 1, 10), new Selection(2, 7, 2, 10)]; await incrementDecrement(1); assert.strictEqual(doc.getText(), contents.replace('123', '124').replace('999', '1000')); return Promise.resolve(); }); }); test('incrementNumberByTen', function (): any { return withRandomFileEditor(contents, 'txt', async (editor, doc) => { editor.selections = [new Selection(1, 7, 1, 10), new Selection(2, 7, 2, 10)]; await incrementDecrement(10); assert.strictEqual(doc.getText(), contents.replace('123', '133').replace('999', '1009')); return Promise.resolve(); }); }); test('incrementNumberByOneTenth', function (): any { return withRandomFileEditor(contents, 'txt', async (editor, doc) => { editor.selections = [new Selection(1, 7, 1, 13), new Selection(2, 7, 2, 12)]; await incrementDecrement(0.1); assert.strictEqual(doc.getText(), contents.replace('123.43', '123.53').replace('999.9', '1000')); return Promise.resolve(); }); }); test('decrementNumberByOne', function (): any { return withRandomFileEditor(contents, 'txt', async (editor, doc) => { editor.selections = [new Selection(1, 7, 1, 10), new Selection(3, 7, 3, 10)]; await incrementDecrement(-1); assert.strictEqual(doc.getText(), contents.replace('123', '122').replace('100', '99')); return Promise.resolve(); }); }); test('decrementNumberByTen', function (): any { return withRandomFileEditor(contents, 'txt', async (editor, doc) => { editor.selections = [new Selection(1, 7, 1, 10), new Selection(3, 7, 3, 10)]; await incrementDecrement(-10); assert.strictEqual(doc.getText(), contents.replace('123', '113').replace('100', '90')); return Promise.resolve(); }); }); test('decrementNumberByOneTenth', function (): any { return withRandomFileEditor(contents, 'txt', async (editor, doc) => { editor.selections = [new Selection(1, 7, 1, 13), new Selection(3, 7, 3, 10)]; await incrementDecrement(-0.1); assert.strictEqual(doc.getText(), contents.replace('123.43', '123.33').replace('100', '99.9')); return Promise.resolve(); }); }); });
extensions/emmet/src/test/incrementDecrement.test.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00019366912601981312, 0.00017610711802262813, 0.0001713045930955559, 0.00017388169362675399, 0.000006528619906021049 ]
{ "id": 10, "code_window": [ "\t\tconst obj = this._kernelData.get(handle);\n", "\t\tif (obj) {\n", "\t\t\tobj.selected = value;\n", "\t\t\tobj.onDidChangeSelection.fire(value);\n", "\t\t}\n", "\t}\n", "\n", "\t$executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void {\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tobj.onDidChangeSelection.fire({\n", "\t\t\t\tselected: value,\n", "\t\t\t\turi: URI.revive(uri)\n", "\t\t\t});\n" ], "file_path": "src/vs/workbench/api/common/extHostNotebookKernels.ts", "type": "replace", "edit_start_line_idx": 133 }
{ "$schema": "vscode://schemas/color-theme", "name": "Dark (Visual Studio)", "colors": { "editor.background": "#1E1E1E", "editor.foreground": "#D4D4D4", "editor.inactiveSelectionBackground": "#3A3D41", "editorIndentGuide.background": "#404040", "editorIndentGuide.activeBackground": "#707070", "editor.selectionHighlightBackground": "#ADD6FF26", "list.dropBackground": "#383B3D", "activityBarBadge.background": "#007ACC", "sideBarTitle.foreground": "#BBBBBB", "input.placeholderForeground": "#A6A6A6", "menu.background": "#252526", "menu.foreground": "#CCCCCC", "statusBarItem.remoteForeground": "#FFF", "statusBarItem.remoteBackground": "#16825D", "ports.iconRunningProcessforeground": "#369432", "sideBarSectionHeader.background": "#0000", "sideBarSectionHeader.border": "#ccc3", "tab.lastPinnedBorder": "#ccc3" }, "tokenColors": [ { "scope": [ "meta.embedded", "source.groovy.embedded" ], "settings": { "foreground": "#D4D4D4" } }, { "scope": "emphasis", "settings": { "fontStyle": "italic" } }, { "scope": "strong", "settings": { "fontStyle": "bold" } }, { "scope": "header", "settings": { "foreground": "#000080" } }, { "scope": "comment", "settings": { "foreground": "#6A9955" } }, { "scope": "constant.language", "settings": { "foreground": "#569cd6" } }, { "scope": [ "constant.numeric", "variable.other.enummember", "keyword.operator.plus.exponent", "keyword.operator.minus.exponent" ], "settings": { "foreground": "#b5cea8" } }, { "scope": "constant.regexp", "settings": { "foreground": "#646695" } }, { "scope": "entity.name.tag", "settings": { "foreground": "#569cd6" } }, { "scope": "entity.name.tag.css", "settings": { "foreground": "#d7ba7d" } }, { "scope": "entity.other.attribute-name", "settings": { "foreground": "#9cdcfe" } }, { "scope": [ "entity.other.attribute-name.class.css", "entity.other.attribute-name.class.mixin.css", "entity.other.attribute-name.id.css", "entity.other.attribute-name.parent-selector.css", "entity.other.attribute-name.pseudo-class.css", "entity.other.attribute-name.pseudo-element.css", "source.css.less entity.other.attribute-name.id", "entity.other.attribute-name.scss" ], "settings": { "foreground": "#d7ba7d" } }, { "scope": "invalid", "settings": { "foreground": "#f44747" } }, { "scope": "markup.underline", "settings": { "fontStyle": "underline" } }, { "scope": "markup.bold", "settings": { "fontStyle": "bold", "foreground": "#569cd6" } }, { "scope": "markup.heading", "settings": { "fontStyle": "bold", "foreground": "#569cd6" } }, { "scope": "markup.italic", "settings": { "fontStyle": "italic" } }, { "scope": "markup.inserted", "settings": { "foreground": "#b5cea8" } }, { "scope": "markup.deleted", "settings": { "foreground": "#ce9178" } }, { "scope": "markup.changed", "settings": { "foreground": "#569cd6" } }, { "scope": "punctuation.definition.quote.begin.markdown", "settings": { "foreground": "#6A9955" } }, { "scope": "punctuation.definition.list.begin.markdown", "settings": { "foreground": "#6796e6" } }, { "scope": "markup.inline.raw", "settings": { "foreground": "#ce9178" } }, { "name": "brackets of XML/HTML tags", "scope": "punctuation.definition.tag", "settings": { "foreground": "#808080" } }, { "scope": [ "meta.preprocessor", "entity.name.function.preprocessor" ], "settings": { "foreground": "#569cd6" } }, { "scope": "meta.preprocessor.string", "settings": { "foreground": "#ce9178" } }, { "scope": "meta.preprocessor.numeric", "settings": { "foreground": "#b5cea8" } }, { "scope": "meta.structure.dictionary.key.python", "settings": { "foreground": "#9cdcfe" } }, { "scope": "meta.diff.header", "settings": { "foreground": "#569cd6" } }, { "scope": "storage", "settings": { "foreground": "#569cd6" } }, { "scope": "storage.type", "settings": { "foreground": "#569cd6" } }, { "scope": [ "storage.modifier", "keyword.operator.noexcept" ], "settings": { "foreground": "#569cd6" } }, { "scope": [ "string", "meta.embedded.assembly" ], "settings": { "foreground": "#ce9178" } }, { "scope": "string.tag", "settings": { "foreground": "#ce9178" } }, { "scope": "string.value", "settings": { "foreground": "#ce9178" } }, { "scope": "string.regexp", "settings": { "foreground": "#d16969" } }, { "name": "String interpolation", "scope": [ "punctuation.definition.template-expression.begin", "punctuation.definition.template-expression.end", "punctuation.section.embedded" ], "settings": { "foreground": "#569cd6" } }, { "name": "Reset JavaScript string interpolation expression", "scope": [ "meta.template.expression" ], "settings": { "foreground": "#d4d4d4" } }, { "scope": [ "support.type.vendored.property-name", "support.type.property-name", "variable.css", "variable.scss", "variable.other.less", "source.coffee.embedded" ], "settings": { "foreground": "#9cdcfe" } }, { "scope": "keyword", "settings": { "foreground": "#569cd6" } }, { "scope": "keyword.control", "settings": { "foreground": "#569cd6" } }, { "scope": "keyword.operator", "settings": { "foreground": "#d4d4d4" } }, { "scope": [ "keyword.operator.new", "keyword.operator.expression", "keyword.operator.cast", "keyword.operator.sizeof", "keyword.operator.alignof", "keyword.operator.typeid", "keyword.operator.alignas", "keyword.operator.instanceof", "keyword.operator.logical.python", "keyword.operator.wordlike" ], "settings": { "foreground": "#569cd6" } }, { "scope": "keyword.other.unit", "settings": { "foreground": "#b5cea8" } }, { "scope": [ "punctuation.section.embedded.begin.php", "punctuation.section.embedded.end.php" ], "settings": { "foreground": "#569cd6" } }, { "scope": "support.function.git-rebase", "settings": { "foreground": "#9cdcfe" } }, { "scope": "constant.sha.git-rebase", "settings": { "foreground": "#b5cea8" } }, { "name": "coloring of the Java import and package identifiers", "scope": [ "storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java" ], "settings": { "foreground": "#d4d4d4" } }, { "name": "this.self", "scope": "variable.language", "settings": { "foreground": "#569cd6" } } ], "semanticHighlighting": true, "semanticTokenColors": { "newOperator": "#d4d4d4", "stringLiteral": "#ce9178", "customLiteral": "#D4D4D4", "numberLiteral": "#b5cea8", } }
extensions/theme-defaults/themes/dark_vs.json
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017919429228641093, 0.0001744451728882268, 0.0001720476138871163, 0.00017441713134758174, 0.000001300085500588466 ]
{ "id": 11, "code_window": [ "\t * @event\n", "\t */\n", "\treadonly onDidChangeModel: Event<NotebookTextModel | undefined>;\n", "\treadonly onDidFocusEditorWidget: Event<void>;\n", "\treadonly activeKernel: INotebookKernel | undefined;\n", "\treadonly availableKernelCount: number;\n", "\treadonly onDidScroll: Event<void>;\n", "\treadonly onDidChangeAvailableKernels: Event<void>;\n", "\treadonly onDidChangeKernel: Event<void>;\n", "\treadonly onDidChangeActiveCell: Event<void>;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tactiveKernel: INotebookKernel | undefined;\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookBrowser.ts", "type": "replace", "edit_start_line_idx": 367 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { flatten } from 'vs/base/common/arrays'; import { Emitter, Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers'; import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookKernel2, INotebookKernel2ChangeEvent, INotebookKernelService } from 'vs/workbench/contrib/notebook/common/notebookKernelService'; import { NotebookSelector } from 'vs/workbench/contrib/notebook/common/notebookSelector'; import { ExtHostContext, ExtHostNotebookKernelsShape, IExtHostContext, INotebookKernelDto2, MainContext, MainThreadNotebookKernelsShape } from '../common/extHost.protocol'; abstract class MainThreadKernel implements INotebookKernel2 { private readonly _onDidChange = new Emitter<INotebookKernel2ChangeEvent>(); private readonly preloads: { uri: URI, provides: string[] }[]; readonly onDidChange: Event<INotebookKernel2ChangeEvent> = this._onDidChange.event; readonly id: string; readonly selector: NotebookSelector; readonly extensionId: ExtensionIdentifier; implementsInterrupt: boolean; label: string; description?: string; detail?: string; isPreferred?: boolean; supportedLanguages: string[]; implementsExecutionOrder: boolean; localResourceRoot: URI; public get preloadUris() { return this.preloads.map(p => p.uri); } public get preloadProvides() { return flatten(this.preloads.map(p => p.provides)); } constructor(data: INotebookKernelDto2) { this.id = data.id; this.selector = data.selector; this.extensionId = data.extensionId; this.implementsInterrupt = data.supportsInterrupt ?? false; this.label = data.label; this.description = data.description; this.isPreferred = data.isPreferred; this.supportedLanguages = data.supportedLanguages; this.implementsExecutionOrder = data.hasExecutionOrder ?? false; this.localResourceRoot = URI.revive(data.extensionLocation); this.preloads = data.preloads?.map(u => ({ uri: URI.revive(u.uri), provides: u.provides })) ?? []; } update(data: Partial<INotebookKernelDto2>) { const event: INotebookKernel2ChangeEvent = Object.create(null); if (data.label !== undefined) { this.label = data.label; event.label = true; } if (data.description !== undefined) { this.description = data.description; event.description = true; } if (data.isPreferred !== undefined) { this.isPreferred = data.isPreferred; event.isPreferred = true; } if (data.supportedLanguages !== undefined) { this.supportedLanguages = data.supportedLanguages; event.supportedLanguages = true; } if (data.hasExecutionOrder !== undefined) { this.implementsExecutionOrder = data.hasExecutionOrder; event.hasExecutionOrder = true; } this._onDidChange.fire(event); } abstract setSelected(value: boolean): void; abstract executeCells(uri: URI, ranges: ICellRange[]): void; abstract cancelCells(uri: URI, ranges: ICellRange[]): void; } @extHostNamedCustomer(MainContext.MainThreadNotebookKernels) export class MainThreadNotebookKernels implements MainThreadNotebookKernelsShape { private readonly _kernels = new Map<number, [kernel: MainThreadKernel, registraion: IDisposable]>(); private readonly _proxy: ExtHostNotebookKernelsShape; constructor( extHostContext: IExtHostContext, @INotebookKernelService private readonly _notebookKernelService: INotebookKernelService, ) { this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostNotebookKernels); } dispose(): void { for (let [, registration] of this._kernels.values()) { registration.dispose(); } } $addKernel(handle: number, data: INotebookKernelDto2): void { const that = this; const kernel = new class extends MainThreadKernel { setSelected(value: boolean): void { that._proxy.$acceptSelection(handle, value); } executeCells(uri: URI, ranges: ICellRange[]): void { that._proxy.$executeCells(handle, uri, ranges); } cancelCells(uri: URI, ranges: ICellRange[]): void { that._proxy.$cancelCells(handle, uri, ranges); } }(data); const disposable = this._notebookKernelService.addKernel(kernel); this._kernels.set(handle, [kernel, disposable]); } $updateKernel(handle: number, data: Partial<INotebookKernelDto2>): void { const tuple = this._kernels.get(handle); if (tuple) { tuple[0].update(data); } } $removeKernel(handle: number): void { const tuple = this._kernels.get(handle); if (tuple) { tuple[1].dispose(); this._kernels.delete(handle); } } }
src/vs/workbench/api/browser/mainThreadNotebookKernels.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.01718241721391678, 0.0027298657223582268, 0.00016713113291189075, 0.0006144268554635346, 0.005257687531411648 ]
{ "id": 11, "code_window": [ "\t * @event\n", "\t */\n", "\treadonly onDidChangeModel: Event<NotebookTextModel | undefined>;\n", "\treadonly onDidFocusEditorWidget: Event<void>;\n", "\treadonly activeKernel: INotebookKernel | undefined;\n", "\treadonly availableKernelCount: number;\n", "\treadonly onDidScroll: Event<void>;\n", "\treadonly onDidChangeAvailableKernels: Event<void>;\n", "\treadonly onDidChangeKernel: Event<void>;\n", "\treadonly onDidChangeActiveCell: Event<void>;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tactiveKernel: INotebookKernel | undefined;\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookBrowser.ts", "type": "replace", "edit_start_line_idx": 367 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IGrammarContributions, ILanguageIdentifierResolver, EmmetEditorAction } from 'vs/workbench/contrib/emmet/browser/emmetActions'; import { withTestCodeEditor } from 'vs/editor/test/browser/testCodeEditor'; import * as assert from 'assert'; import { LanguageId, LanguageIdentifier } from 'vs/editor/common/modes'; // // To run the emmet tests only change .vscode/launch.json // { // "name": "Stacks Tests", // "type": "node", // "request": "launch", // "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha", // "stopOnEntry": false, // "args": [ // "--timeout", // "999999", // "--colors", // "-g", // "Stacks" <<<--- Emmet // ], // Select the 'Stacks Tests' launch config and F5 // class MockGrammarContributions implements IGrammarContributions { private scopeName: string; constructor(scopeName: string) { this.scopeName = scopeName; } public getGrammar(mode: string): string { return this.scopeName; } } suite('Emmet', () => { test('Get language mode and parent mode for emmet', () => { withTestCodeEditor([], {}, (editor) => { function testIsEnabled(mode: string, scopeName: string, expectedLanguage?: string, expectedParentLanguage?: string) { const customLanguageId: LanguageId = 73; const languageIdentifier = new LanguageIdentifier(mode, customLanguageId); const languageIdentifierResolver: ILanguageIdentifierResolver = { getLanguageIdentifier: (languageId: LanguageId) => { if (languageId === customLanguageId) { return languageIdentifier; } throw new Error('Unexpected'); } }; const model = editor.getModel(); if (!model) { assert.fail('Editor model not found'); } model.setMode(languageIdentifier); let langOutput = EmmetEditorAction.getLanguage(languageIdentifierResolver, editor, new MockGrammarContributions(scopeName)); if (!langOutput) { assert.fail('langOutput not found'); } assert.strictEqual(langOutput.language, expectedLanguage); assert.strictEqual(langOutput.parentMode, expectedParentLanguage); } // syntaxes mapped using the scope name of the grammar testIsEnabled('markdown', 'text.html.markdown', 'markdown', 'html'); testIsEnabled('handlebars', 'text.html.handlebars', 'handlebars', 'html'); testIsEnabled('nunjucks', 'text.html.nunjucks', 'nunjucks', 'html'); testIsEnabled('laravel-blade', 'text.html.php.laravel-blade', 'laravel-blade', 'html'); // languages that have different Language Id and scopeName // testIsEnabled('razor', 'text.html.cshtml', 'razor', 'html'); // testIsEnabled('HTML (Eex)', 'text.html.elixir', 'boo', 'html'); }); }); });
src/vs/workbench/contrib/emmet/test/browser/emmetAction.test.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017670754459686577, 0.00017351203132420778, 0.00017101180856116116, 0.00017363086226396263, 0.0000017316519915766548 ]
{ "id": 11, "code_window": [ "\t * @event\n", "\t */\n", "\treadonly onDidChangeModel: Event<NotebookTextModel | undefined>;\n", "\treadonly onDidFocusEditorWidget: Event<void>;\n", "\treadonly activeKernel: INotebookKernel | undefined;\n", "\treadonly availableKernelCount: number;\n", "\treadonly onDidScroll: Event<void>;\n", "\treadonly onDidChangeAvailableKernels: Event<void>;\n", "\treadonly onDidChangeKernel: Event<void>;\n", "\treadonly onDidChangeActiveCell: Event<void>;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tactiveKernel: INotebookKernel | undefined;\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookBrowser.ts", "type": "replace", "edit_start_line_idx": 367 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { TrackedRangeStickiness } from 'vs/editor/common/model'; import { FoldingRegion, FoldingRegions } from 'vs/editor/contrib/folding/foldingRanges'; import { IFoldingRangeData, sanitizeRanges } from 'vs/editor/contrib/folding/syntaxRangeProvider'; import { CellViewModel, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel'; import { CellKind, cellRangesToIndexes, ICellRange } from 'vs/workbench/contrib/notebook/common/notebookCommon'; type RegionFilter = (r: FoldingRegion) => boolean; type RegionFilterWithLevel = (r: FoldingRegion, level: number) => boolean; export class FoldingModel { private _viewModel: NotebookViewModel | null = null; private readonly _viewModelStore = new DisposableStore(); private _regions: FoldingRegions; get regions() { return this._regions; } private readonly _onDidFoldingRegionChanges = new Emitter<void>(); readonly onDidFoldingRegionChanged: Event<void> = this._onDidFoldingRegionChanges.event; private _foldingRangeDecorationIds: string[] = []; constructor() { this._regions = new FoldingRegions(new Uint32Array(0), new Uint32Array(0)); } dispose() { this._onDidFoldingRegionChanges.dispose(); this._viewModelStore.dispose(); } detachViewModel() { this._viewModelStore.clear(); this._viewModel = null; } attachViewModel(model: NotebookViewModel) { this._viewModel = model; this._viewModelStore.add(this._viewModel.onDidChangeViewCells(() => { this.recompute(); })); this._viewModelStore.add(this._viewModel.onDidChangeSelection(() => { if (!this._viewModel) { return; } const indexes = cellRangesToIndexes(this._viewModel.getSelections()); let changed = false; indexes.forEach(index => { let regionIndex = this.regions.findRange(index + 1); while (regionIndex !== -1) { if (this._regions.isCollapsed(regionIndex) && index > this._regions.getStartLineNumber(regionIndex) - 1) { this._regions.setCollapsed(regionIndex, false); changed = true; } regionIndex = this._regions.getParentIndex(regionIndex); } }); if (changed) { this._onDidFoldingRegionChanges.fire(); } })); this.recompute(); } getRegionAtLine(lineNumber: number): FoldingRegion | null { if (this._regions) { let index = this._regions.findRange(lineNumber); if (index >= 0) { return this._regions.toRegion(index); } } return null; } getRegionsInside(region: FoldingRegion | null, filter?: RegionFilter | RegionFilterWithLevel): FoldingRegion[] { let result: FoldingRegion[] = []; let index = region ? region.regionIndex + 1 : 0; let endLineNumber = region ? region.endLineNumber : Number.MAX_VALUE; if (filter && filter.length === 2) { const levelStack: FoldingRegion[] = []; for (let i = index, len = this._regions.length; i < len; i++) { let current = this._regions.toRegion(i); if (this._regions.getStartLineNumber(i) < endLineNumber) { while (levelStack.length > 0 && !current.containedBy(levelStack[levelStack.length - 1])) { levelStack.pop(); } levelStack.push(current); if (filter(current, levelStack.length)) { result.push(current); } } else { break; } } } else { for (let i = index, len = this._regions.length; i < len; i++) { let current = this._regions.toRegion(i); if (this._regions.getStartLineNumber(i) < endLineNumber) { if (!filter || (filter as RegionFilter)(current)) { result.push(current); } } else { break; } } } return result; } getAllRegionsAtLine(lineNumber: number, filter?: (r: FoldingRegion, level: number) => boolean): FoldingRegion[] { let result: FoldingRegion[] = []; if (this._regions) { let index = this._regions.findRange(lineNumber); let level = 1; while (index >= 0) { let current = this._regions.toRegion(index); if (!filter || filter(current, level)) { result.push(current); } level++; index = current.parentIndex; } } return result; } setCollapsed(index: number, newState: boolean) { this._regions.setCollapsed(index, newState); } recompute() { if (!this._viewModel) { return; } const viewModel = this._viewModel; const cells = viewModel.viewCells; const stack: { index: number, level: number, endIndex: number }[] = []; for (let i = 0; i < cells.length; i++) { const cell = cells[i]; if (cell.cellKind === CellKind.Code) { continue; } const content = cell.getText(); const matches = content.match(/^[ \t]*(\#+)/gm); let min = 7; if (matches && matches.length) { for (let j = 0; j < matches.length; j++) { min = Math.min(min, matches[j].length); } } if (min < 7) { // header 1 to 6 stack.push({ index: i, level: min, endIndex: 0 }); } } // calcualte folding ranges const rawFoldingRanges: IFoldingRangeData[] = stack.map((entry, startIndex) => { let end: number | undefined = undefined; for (let i = startIndex + 1; i < stack.length; ++i) { if (stack[i].level <= entry.level) { end = stack[i].index - 1; break; } } const endIndex = end !== undefined ? end : cells.length - 1; // one based return { start: entry.index + 1, end: endIndex + 1, rank: 1 }; }).filter(range => range.start !== range.end); const newRegions = sanitizeRanges(rawFoldingRanges, 5000); // restore collased state let i = 0; const nextCollapsed = () => { while (i < this._regions.length) { const isCollapsed = this._regions.isCollapsed(i); i++; if (isCollapsed) { return i - 1; } } return -1; }; let k = 0; let collapsedIndex = nextCollapsed(); while (collapsedIndex !== -1 && k < newRegions.length) { // get the latest range const decRange = viewModel.getTrackedRange(this._foldingRangeDecorationIds[collapsedIndex]); if (decRange) { const collasedStartIndex = decRange.start; while (k < newRegions.length) { const startIndex = newRegions.getStartLineNumber(k) - 1; if (collasedStartIndex >= startIndex) { newRegions.setCollapsed(k, collasedStartIndex === startIndex); k++; } else { break; } } } collapsedIndex = nextCollapsed(); } while (k < newRegions.length) { newRegions.setCollapsed(k, false); k++; } const cellRanges: ICellRange[] = []; for (let i = 0; i < newRegions.length; i++) { const region = newRegions.toRegion(i); cellRanges.push({ start: region.startLineNumber - 1, end: region.endLineNumber - 1 }); } // remove old tracked ranges and add new ones // TODO@rebornix, implement delta this._foldingRangeDecorationIds.forEach(id => viewModel.setTrackedRange(id, null, TrackedRangeStickiness.GrowsOnlyWhenTypingAfter)); this._foldingRangeDecorationIds = cellRanges.map(region => viewModel.setTrackedRange(null, region, TrackedRangeStickiness.GrowsOnlyWhenTypingAfter)).filter(str => str !== null) as string[]; this._regions = newRegions; this._onDidFoldingRegionChanges.fire(); } getMemento(): ICellRange[] { const collapsedRanges: ICellRange[] = []; let i = 0; while (i < this._regions.length) { const isCollapsed = this._regions.isCollapsed(i); if (isCollapsed) { const region = this._regions.toRegion(i); collapsedRanges.push({ start: region.startLineNumber - 1, end: region.endLineNumber - 1 }); } i++; } return collapsedRanges; } public applyMemento(state: ICellRange[]): boolean { if (!this._viewModel) { return false; } let i = 0; let k = 0; while (k < state.length && i < this._regions.length) { // get the latest range const decRange = this._viewModel.getTrackedRange(this._foldingRangeDecorationIds[i]); if (decRange) { const collasedStartIndex = state[k].start; while (i < this._regions.length) { const startIndex = this._regions.getStartLineNumber(i) - 1; if (collasedStartIndex >= startIndex) { this._regions.setCollapsed(i, collasedStartIndex === startIndex); i++; } else { break; } } } k++; } while (i < this._regions.length) { this._regions.setCollapsed(i, false); i++; } return true; } } export enum CellFoldingState { None, Expanded, Collapsed } export interface EditorFoldingStateDelegate { getCellIndex(cell: CellViewModel): number; getFoldingState(index: number): CellFoldingState; } export function updateFoldingStateAtIndex(foldingModel: FoldingModel, index: number, collapsed: boolean) { const range = foldingModel.regions.findRange(index + 1); foldingModel.setCollapsed(range, collapsed); }
src/vs/workbench/contrib/notebook/browser/contrib/fold/foldingModel.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.001579422620125115, 0.00024984776973724365, 0.0001657924585742876, 0.00017329775437247008, 0.00026804357185028493 ]
{ "id": 11, "code_window": [ "\t * @event\n", "\t */\n", "\treadonly onDidChangeModel: Event<NotebookTextModel | undefined>;\n", "\treadonly onDidFocusEditorWidget: Event<void>;\n", "\treadonly activeKernel: INotebookKernel | undefined;\n", "\treadonly availableKernelCount: number;\n", "\treadonly onDidScroll: Event<void>;\n", "\treadonly onDidChangeAvailableKernels: Event<void>;\n", "\treadonly onDidChangeKernel: Event<void>;\n", "\treadonly onDidChangeActiveCell: Event<void>;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tactiveKernel: INotebookKernel | undefined;\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookBrowser.ts", "type": "replace", "edit_start_line_idx": 367 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { ITextModel, FindMatch } from 'vs/editor/common/model'; import { editorMatchesToTextSearchResults, addContextToEditorMatches } from 'vs/workbench/services/search/common/searchHelpers'; import { Range } from 'vs/editor/common/core/range'; import { ITextQuery, QueryType, ITextSearchContext } from 'vs/workbench/services/search/common/search'; suite('SearchHelpers', () => { suite('editorMatchesToTextSearchResults', () => { const mockTextModel: ITextModel = <ITextModel>{ getLineContent(lineNumber: number): string { return '' + lineNumber; } }; test('simple', () => { const results = editorMatchesToTextSearchResults([new FindMatch(new Range(6, 1, 6, 2), null)], mockTextModel); assert.strictEqual(results.length, 1); assert.strictEqual(results[0].preview.text, '6\n'); assert.deepEqual(results[0].preview.matches, [new Range(0, 0, 0, 1)]); assert.deepEqual(results[0].ranges, [new Range(5, 0, 5, 1)]); }); test('multiple', () => { const results = editorMatchesToTextSearchResults( [ new FindMatch(new Range(6, 1, 6, 2), null), new FindMatch(new Range(6, 4, 8, 2), null), new FindMatch(new Range(9, 1, 10, 3), null), ], mockTextModel); assert.strictEqual(results.length, 2); assert.deepEqual(results[0].preview.matches, [ new Range(0, 0, 0, 1), new Range(0, 3, 2, 1), ]); assert.deepEqual(results[0].ranges, [ new Range(5, 0, 5, 1), new Range(5, 3, 7, 1), ]); assert.strictEqual(results[0].preview.text, '6\n7\n8\n'); assert.deepEqual(results[1].preview.matches, [ new Range(0, 0, 1, 2), ]); assert.deepEqual(results[1].ranges, [ new Range(8, 0, 9, 2), ]); assert.strictEqual(results[1].preview.text, '9\n10\n'); }); }); suite('addContextToEditorMatches', () => { const MOCK_LINE_COUNT = 100; const mockTextModel: ITextModel = <ITextModel>{ getLineContent(lineNumber: number): string { if (lineNumber < 1 || lineNumber > MOCK_LINE_COUNT) { throw new Error(`invalid line count: ${lineNumber}`); } return '' + lineNumber; }, getLineCount(): number { return MOCK_LINE_COUNT; } }; function getQuery(beforeContext?: number, afterContext?: number): ITextQuery { return { folderQueries: [], type: QueryType.Text, contentPattern: { pattern: 'test' }, beforeContext, afterContext }; } test('no context', () => { const matches = [{ preview: { text: 'foo', matches: new Range(0, 0, 0, 10) }, ranges: new Range(0, 0, 0, 10) }]; assert.deepStrictEqual(addContextToEditorMatches(matches, mockTextModel, getQuery()), matches); }); test('simple', () => { const matches = [{ preview: { text: 'foo', matches: new Range(0, 0, 0, 10) }, ranges: new Range(1, 0, 1, 10) }]; assert.deepStrictEqual(addContextToEditorMatches(matches, mockTextModel, getQuery(1, 2)), [ <ITextSearchContext>{ text: '1', lineNumber: 0 }, ...matches, <ITextSearchContext>{ text: '3', lineNumber: 2 }, <ITextSearchContext>{ text: '4', lineNumber: 3 }, ]); }); test('multiple matches next to each other', () => { const matches = [ { preview: { text: 'foo', matches: new Range(0, 0, 0, 10) }, ranges: new Range(1, 0, 1, 10) }, { preview: { text: 'bar', matches: new Range(0, 0, 0, 10) }, ranges: new Range(2, 0, 2, 10) }]; assert.deepStrictEqual(addContextToEditorMatches(matches, mockTextModel, getQuery(1, 2)), [ <ITextSearchContext>{ text: '1', lineNumber: 0 }, ...matches, <ITextSearchContext>{ text: '4', lineNumber: 3 }, <ITextSearchContext>{ text: '5', lineNumber: 4 }, ]); }); test('boundaries', () => { const matches = [ { preview: { text: 'foo', matches: new Range(0, 0, 0, 10) }, ranges: new Range(0, 0, 0, 10) }, { preview: { text: 'bar', matches: new Range(0, 0, 0, 10) }, ranges: new Range(MOCK_LINE_COUNT - 1, 0, MOCK_LINE_COUNT - 1, 10) }]; assert.deepStrictEqual(addContextToEditorMatches(matches, mockTextModel, getQuery(1, 2)), [ matches[0], <ITextSearchContext>{ text: '2', lineNumber: 1 }, <ITextSearchContext>{ text: '3', lineNumber: 2 }, <ITextSearchContext>{ text: '' + (MOCK_LINE_COUNT - 1), lineNumber: MOCK_LINE_COUNT - 2 }, matches[1] ]); }); }); });
src/vs/workbench/services/search/test/common/searchHelpers.test.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.000174950051587075, 0.00017059294623322785, 0.00016527176194358617, 0.0001715227117529139, 0.0000027770774977398105 ]
{ "id": 12, "code_window": [ "\n", "\tget activeKernel() {\n", "\t\treturn this._kernelManger.activeKernel;\n", "\t}\n", "\n", "\tprivate _currentKernelTokenSource: CancellationTokenSource | undefined = undefined;\n", "\n", "\tget availableKernelCount() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tset activeKernel(value) {\n", "\t\tthis._kernelManger.activeKernel = value;\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "add", "edit_start_line_idx": 280 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter } from 'vs/base/common/event'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { ExtHostNotebookKernelsShape, IMainContext, INotebookKernelDto2, MainContext, MainThreadNotebookKernelsShape } from 'vs/workbench/api/common/extHost.protocol'; import * as vscode from 'vscode'; import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { URI, UriComponents } from 'vs/base/common/uri'; import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { NotebookCellRange } from 'vs/workbench/api/common/extHostTypeConverters'; import { isNonEmptyArray } from 'vs/base/common/arrays'; type ExecuteHandler = (executions: vscode.NotebookCellExecutionTask[]) => void; type InterruptHandler = (notebook: vscode.NotebookDocument) => void; export class ExtHostNotebookKernels implements ExtHostNotebookKernelsShape { private readonly _proxy: MainThreadNotebookKernelsShape; private readonly _kernelData = new Map<number, { id: string, executeHandler: ExecuteHandler, interruptHandler?: InterruptHandler, selected: boolean, onDidChangeSelection: Emitter<boolean> }>(); private _handlePool: number = 0; constructor( mainContext: IMainContext, private readonly _extHostNotebook: ExtHostNotebookController ) { this._proxy = mainContext.getProxy(MainContext.MainThreadNotebookKernels); } createKernel(extension: IExtensionDescription, options: vscode.NotebookKernelOptions): vscode.NotebookKernel2 { const handle = this._handlePool++; const that = this; let isDisposed = false; const commandDisposables = new DisposableStore(); const emitter = new Emitter<boolean>(); this._kernelData.set(handle, { id: options.id, executeHandler: options.executeHandler, selected: false, onDidChangeSelection: emitter }); const data: INotebookKernelDto2 = { id: options.id, selector: options.selector, extensionId: extension.identifier, extensionLocation: extension.extensionLocation, label: options.label, supportedLanguages: isNonEmptyArray(options.supportedLanguages) ? options.supportedLanguages : ['plaintext'], supportsInterrupt: Boolean(options.interruptHandler), hasExecutionOrder: options.hasExecutionOrder, }; this._proxy.$addKernel(handle, data); // update: all setters write directly into the dto object // and trigger an update. the actual update will only happen // once per event loop execution let tokenPool = 0; const _update = () => { if (isDisposed) { return; } const myToken = ++tokenPool; Promise.resolve().then(() => { if (myToken === tokenPool) { this._proxy.$updateKernel(handle, data); } }); }; return { get id() { return data.id; }, get selector() { return data.selector; }, // get selected() { return that._kernelData.get(handle)?.selected ?? false; }, // onDidChangeSelection: emitter.event, get label() { return data.label; }, set label(value) { data.label = value; _update(); }, get description() { return data.description ?? ''; }, set description(value) { data.description = value; _update(); }, get supportedLanguages() { return data.supportedLanguages; }, set supportedLanguages(value) { data.supportedLanguages = isNonEmptyArray(value) ? value : ['plaintext']; _update(); }, get hasExecutionOrder() { return data.hasExecutionOrder ?? false; }, set hasExecutionOrder(value) { data.hasExecutionOrder = value; _update(); }, get executeHandler() { return that._kernelData.get(handle)!.executeHandler; }, get interruptHandler() { return that._kernelData.get(handle)!.interruptHandler; }, set interruptHandler(value) { that._kernelData.get(handle)!.interruptHandler = value; data.supportsInterrupt = Boolean(value); _update(); }, createNotebookCellExecutionTask(cell) { //todo@jrieken return that._extHostNotebook.createNotebookCellExecution(cell.document.uri, cell.index, data.id)!; }, dispose: () => { isDisposed = true; this._kernelData.delete(handle); commandDisposables.dispose(); emitter.dispose(); this._proxy.$removeKernel(handle); } }; } $acceptSelection(handle: number, value: boolean): void { const obj = this._kernelData.get(handle); if (obj) { obj.selected = value; obj.onDidChangeSelection.fire(value); } } $executeCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void { const obj = this._kernelData.get(handle); if (!obj) { // extension can dispose kernels in the meantime return; } const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri)); if (!document) { throw new Error('MISSING notebook'); } const execs: vscode.NotebookCellExecutionTask[] = []; for (let range of ranges) { const cells = document.notebookDocument.getCells(NotebookCellRange.to(range)); for (let cell of cells) { const exec = this._extHostNotebook.createNotebookCellExecution(document.uri, cell.index, obj.id); if (exec) { execs.push(exec); } else { // todo@jrieken there should always be an exec-object console.warn('could NOT create notebook cell execution task for: ' + cell.document.uri); } } } try { obj.executeHandler(execs); } catch (err) { // console.error(err); } } $cancelCells(handle: number, uri: UriComponents, ranges: ICellRange[]): void { const obj = this._kernelData.get(handle); if (!obj) { // extension can dispose kernels in the meantime return; } const document = this._extHostNotebook.lookupNotebookDocument(URI.revive(uri)); if (!document) { throw new Error('MISSING notebook'); } if (obj.interruptHandler) { obj.interruptHandler(document.notebookDocument); } } }
src/vs/workbench/api/common/extHostNotebookKernels.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.003094754181802273, 0.0005656679859384894, 0.00016741183935664594, 0.0002671331458259374, 0.0007040395867079496 ]
{ "id": 12, "code_window": [ "\n", "\tget activeKernel() {\n", "\t\treturn this._kernelManger.activeKernel;\n", "\t}\n", "\n", "\tprivate _currentKernelTokenSource: CancellationTokenSource | undefined = undefined;\n", "\n", "\tget availableKernelCount() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tset activeKernel(value) {\n", "\t\tthis._kernelManger.activeKernel = value;\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "add", "edit_start_line_idx": 280 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /// <reference path="../../../../src/vs/vscode.d.ts" /> /// <reference types='@types/node'/>
extensions/vscode-custom-editor-tests/src/typings/ref.d.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017719314200803638, 0.00017719314200803638, 0.00017719314200803638, 0.00017719314200803638, 0 ]
{ "id": 12, "code_window": [ "\n", "\tget activeKernel() {\n", "\t\treturn this._kernelManger.activeKernel;\n", "\t}\n", "\n", "\tprivate _currentKernelTokenSource: CancellationTokenSource | undefined = undefined;\n", "\n", "\tget availableKernelCount() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tset activeKernel(value) {\n", "\t\tthis._kernelManger.activeKernel = value;\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "add", "edit_start_line_idx": 280 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { extname } from 'path'; import { Command } from '../commandManager'; import { MarkdownEngine } from '../markdownEngine'; import { TableOfContentsProvider } from '../tableOfContentsProvider'; import { isMarkdownFile } from '../util/file'; type UriComponents = { readonly scheme?: string; readonly path: string; readonly fragment?: string; readonly authority?: string; readonly query?: string; }; export interface OpenDocumentLinkArgs { readonly parts: UriComponents; readonly fragment: string; readonly fromResource: UriComponents; } enum OpenMarkdownLinks { beside = 'beside', currentGroup = 'currentGroup', } export class OpenDocumentLinkCommand implements Command { private static readonly id = '_markdown.openDocumentLink'; public readonly id = OpenDocumentLinkCommand.id; public static createCommandUri( fromResource: vscode.Uri, path: vscode.Uri, fragment: string, ): vscode.Uri { const toJson = (uri: vscode.Uri): UriComponents => { return { scheme: uri.scheme, authority: uri.authority, path: uri.path, fragment: uri.fragment, query: uri.query, }; }; return vscode.Uri.parse(`command:${OpenDocumentLinkCommand.id}?${encodeURIComponent(JSON.stringify(<OpenDocumentLinkArgs>{ parts: toJson(path), fragment, fromResource: toJson(fromResource), }))}`); } public constructor( private readonly engine: MarkdownEngine ) { } public async execute(args: OpenDocumentLinkArgs) { return OpenDocumentLinkCommand.execute(this.engine, args); } public static async execute(engine: MarkdownEngine, args: OpenDocumentLinkArgs): Promise<void> { const fromResource = vscode.Uri.parse('').with(args.fromResource); const targetResource = reviveUri(args.parts); const column = this.getViewColumn(fromResource); const didOpen = await this.tryOpen(engine, targetResource, args, column); if (didOpen) { return; } if (extname(targetResource.path) === '') { await this.tryOpen(engine, targetResource.with({ path: targetResource.path + '.md' }), args, column); return; } } private static async tryOpen(engine: MarkdownEngine, resource: vscode.Uri, args: OpenDocumentLinkArgs, column: vscode.ViewColumn): Promise<boolean> { const tryUpdateForActiveFile = async (): Promise<boolean> => { if (vscode.window.activeTextEditor && isMarkdownFile(vscode.window.activeTextEditor.document)) { if (vscode.window.activeTextEditor.document.uri.fsPath === resource.fsPath) { await this.tryRevealLine(engine, vscode.window.activeTextEditor, args.fragment); return true; } } return false; }; if (await tryUpdateForActiveFile()) { return true; } let stat: vscode.FileStat; try { stat = await vscode.workspace.fs.stat(resource); } catch { return false; } if (stat.type === vscode.FileType.Directory) { await vscode.commands.executeCommand('revealInExplorer', resource); return true; } try { await vscode.commands.executeCommand('vscode.open', resource, column); } catch { return false; } return tryUpdateForActiveFile(); } private static getViewColumn(resource: vscode.Uri): vscode.ViewColumn { const config = vscode.workspace.getConfiguration('markdown', resource); const openLinks = config.get<OpenMarkdownLinks>('links.openLocation', OpenMarkdownLinks.currentGroup); switch (openLinks) { case OpenMarkdownLinks.beside: return vscode.ViewColumn.Beside; case OpenMarkdownLinks.currentGroup: default: return vscode.ViewColumn.Active; } } private static async tryRevealLine(engine: MarkdownEngine, editor: vscode.TextEditor, fragment?: string) { if (fragment) { const toc = new TableOfContentsProvider(engine, editor.document); const entry = await toc.lookup(fragment); if (entry) { const lineStart = new vscode.Range(entry.line, 0, entry.line, 0); editor.selection = new vscode.Selection(lineStart.start, lineStart.end); return editor.revealRange(lineStart, vscode.TextEditorRevealType.AtTop); } const lineNumberFragment = fragment.match(/^L(\d+)$/i); if (lineNumberFragment) { const line = +lineNumberFragment[1] - 1; if (!isNaN(line)) { const lineStart = new vscode.Range(line, 0, line, 0); editor.selection = new vscode.Selection(lineStart.start, lineStart.end); return editor.revealRange(lineStart, vscode.TextEditorRevealType.AtTop); } } } } } function reviveUri(parts: any) { if (parts.scheme === 'file') { return vscode.Uri.file(parts.path); } return vscode.Uri.parse('').with(parts); } export async function resolveLinkToMarkdownFile(path: string): Promise<vscode.Uri | undefined> { try { const standardLink = await tryResolveLinkToMarkdownFile(path); if (standardLink) { return standardLink; } } catch { // Noop } // If no extension, try with `.md` extension if (extname(path) === '') { return tryResolveLinkToMarkdownFile(path + '.md'); } return undefined; } async function tryResolveLinkToMarkdownFile(path: string): Promise<vscode.Uri | undefined> { const resource = vscode.Uri.file(path); let document: vscode.TextDocument; try { document = await vscode.workspace.openTextDocument(resource); } catch { return undefined; } if (isMarkdownFile(document)) { return document.uri; } return undefined; }
extensions/markdown-language-features/src/commands/openDocumentLink.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017864053370431066, 0.00017492860206402838, 0.000167805643286556, 0.00017535733059048653, 0.0000025641625143180136 ]
{ "id": 12, "code_window": [ "\n", "\tget activeKernel() {\n", "\t\treturn this._kernelManger.activeKernel;\n", "\t}\n", "\n", "\tprivate _currentKernelTokenSource: CancellationTokenSource | undefined = undefined;\n", "\n", "\tget availableKernelCount() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tset activeKernel(value) {\n", "\t\tthis._kernelManger.activeKernel = value;\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "add", "edit_start_line_idx": 280 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IMarkerService, IMarker, MarkerSeverity } from 'vs/platform/markers/common/markers'; import { IDecorationsService, IDecorationsProvider, IDecorationData } from 'vs/workbench/services/decorations/browser/decorations'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { Event } from 'vs/base/common/event'; import { localize } from 'vs/nls'; import { Registry } from 'vs/platform/registry/common/platform'; import { listErrorForeground, listWarningForeground } from 'vs/platform/theme/common/colorRegistry'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry'; import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle'; class MarkersDecorationsProvider implements IDecorationsProvider { readonly label: string = localize('label', "Problems"); readonly onDidChange: Event<readonly URI[]>; constructor( private readonly _markerService: IMarkerService ) { this.onDidChange = _markerService.onMarkerChanged; } provideDecorations(resource: URI): IDecorationData | undefined { let markers = this._markerService.read({ resource, severities: MarkerSeverity.Error | MarkerSeverity.Warning }); let first: IMarker | undefined; for (const marker of markers) { if (!first || marker.severity > first.severity) { first = marker; } } if (!first) { return undefined; } return { weight: 100 * first.severity, bubble: true, tooltip: markers.length === 1 ? localize('tooltip.1', "1 problem in this file") : localize('tooltip.N', "{0} problems in this file", markers.length), letter: markers.length < 10 ? markers.length.toString() : '9+', color: first.severity === MarkerSeverity.Error ? listErrorForeground : listWarningForeground, }; } } class MarkersFileDecorations implements IWorkbenchContribution { private readonly _disposables: IDisposable[]; private _provider?: IDisposable; private _enabled?: boolean; constructor( @IMarkerService private readonly _markerService: IMarkerService, @IDecorationsService private readonly _decorationsService: IDecorationsService, @IConfigurationService private readonly _configurationService: IConfigurationService ) { // this._disposables = [ this._configurationService.onDidChangeConfiguration(this._updateEnablement, this), ]; this._updateEnablement(); } dispose(): void { dispose(this._provider); dispose(this._disposables); } private _updateEnablement(): void { let value = this._configurationService.getValue<{ decorations: { enabled: boolean } }>('problems'); if (value.decorations.enabled === this._enabled) { return; } this._enabled = value.decorations.enabled; if (this._enabled) { const provider = new MarkersDecorationsProvider(this._markerService); this._provider = this._decorationsService.registerDecorationsProvider(provider); } else if (this._provider) { this._enabled = value.decorations.enabled; this._provider.dispose(); } } } Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({ 'id': 'problems', 'order': 101, 'type': 'object', 'properties': { 'problems.decorations.enabled': { 'description': localize('markers.showOnFile', "Show Errors & Warnings on files and folder."), 'type': 'boolean', 'default': true } } }); // register file decorations Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench) .registerWorkbenchContribution(MarkersFileDecorations, LifecyclePhase.Restored);
src/vs/workbench/contrib/markers/browser/markersFileDecorations.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00019602858810685575, 0.0001745456684147939, 0.00016779427824076265, 0.0001733223325572908, 0.000007060976713546552 ]
{ "id": 13, "code_window": [ "\n", "\tlocalResourceRoot: URI;\n", "\tpreloadUris: URI[];\n", "\tpreloadProvides: string[];\n", "\n", "\tsetSelected(value: boolean): void;\n", "\texecuteCells(uri: URI, ranges: ICellRange[]): void;\n", "\tcancelCells(uri: URI, ranges: ICellRange[]): void\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tsetSelected(uri: URI, value: boolean): void;\n" ], "file_path": "src/vs/workbench/contrib/notebook/common/notebookKernelService.ts", "type": "replace", "edit_start_line_idx": 42 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ICellRange, INotebookTextModel } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { NotebookSelector } from 'vs/workbench/contrib/notebook/common/notebookSelector'; export interface INotebookKernel2ChangeEvent { label?: true; description?: true; detail?: true; isPreferred?: true; supportedLanguages?: true; hasExecutionOrder?: true; } export interface INotebookKernel2 { readonly id: string; readonly selector: NotebookSelector readonly extensionId: ExtensionIdentifier; readonly onDidChange: Event<INotebookKernel2ChangeEvent>; label: string; description?: string; detail?: string; isPreferred?: boolean; supportedLanguages: string[]; implementsExecutionOrder: boolean; implementsInterrupt: boolean; localResourceRoot: URI; preloadUris: URI[]; preloadProvides: string[]; setSelected(value: boolean): void; executeCells(uri: URI, ranges: ICellRange[]): void; cancelCells(uri: URI, ranges: ICellRange[]): void } export const INotebookKernelService = createDecorator<INotebookKernelService>('INotebookKernelService'); export interface INotebookKernelService { _serviceBrand: undefined; onDidAddKernel: Event<INotebookKernel2>; onDidRemoveKernel: Event<INotebookKernel2>; addKernel(kernel: INotebookKernel2): IDisposable; selectKernels(notebook: INotebookTextModel): INotebookKernel2[]; }
src/vs/workbench/contrib/notebook/common/notebookKernelService.ts
1
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.8729919195175171, 0.1468980461359024, 0.00016932483413256705, 0.000291099539026618, 0.3247298300266266 ]
{ "id": 13, "code_window": [ "\n", "\tlocalResourceRoot: URI;\n", "\tpreloadUris: URI[];\n", "\tpreloadProvides: string[];\n", "\n", "\tsetSelected(value: boolean): void;\n", "\texecuteCells(uri: URI, ranges: ICellRange[]): void;\n", "\tcancelCells(uri: URI, ranges: ICellRange[]): void\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tsetSelected(uri: URI, value: boolean): void;\n" ], "file_path": "src/vs/workbench/contrib/notebook/common/notebookKernelService.ts", "type": "replace", "edit_start_line_idx": 42 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /// <reference path='../../../../src/vs/vscode.d.ts'/> /// <reference path='../../../../src/vs/vscode.proposed.d.ts'/> /// <reference types='@types/node'/>
extensions/markdown-language-features/src/typings/ref.d.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017499527893960476, 0.00017499527893960476, 0.00017499527893960476, 0.00017499527893960476, 0 ]
{ "id": 13, "code_window": [ "\n", "\tlocalResourceRoot: URI;\n", "\tpreloadUris: URI[];\n", "\tpreloadProvides: string[];\n", "\n", "\tsetSelected(value: boolean): void;\n", "\texecuteCells(uri: URI, ranges: ICellRange[]): void;\n", "\tcancelCells(uri: URI, ranges: ICellRange[]): void\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tsetSelected(uri: URI, value: boolean): void;\n" ], "file_path": "src/vs/workbench/contrib/notebook/common/notebookKernelService.ts", "type": "replace", "edit_start_line_idx": 42 }
{ "extends": "../tsconfig.base.json", "compilerOptions": { "outDir": "./out", }, "include": [ "src/**/*" ] }
extensions/search-result/tsconfig.json
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017524123541079462, 0.00017524123541079462, 0.00017524123541079462, 0.00017524123541079462, 0 ]
{ "id": 13, "code_window": [ "\n", "\tlocalResourceRoot: URI;\n", "\tpreloadUris: URI[];\n", "\tpreloadProvides: string[];\n", "\n", "\tsetSelected(value: boolean): void;\n", "\texecuteCells(uri: URI, ranges: ICellRange[]): void;\n", "\tcancelCells(uri: URI, ranges: ICellRange[]): void\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tsetSelected(uri: URI, value: boolean): void;\n" ], "file_path": "src/vs/workbench/contrib/notebook/common/notebookKernelService.ts", "type": "replace", "edit_start_line_idx": 42 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as dom from 'vs/base/browser/dom'; import { IMarkdownString, MarkdownString, isEmptyMarkdownString, markedStringsEquals } from 'vs/base/common/htmlContent'; import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { Range } from 'vs/editor/common/core/range'; import { MarkdownRenderer } from 'vs/editor/browser/core/markdownRenderer'; import { asArray } from 'vs/base/common/arrays'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IModelDecoration } from 'vs/editor/common/model'; import { IEditorHover, IEditorHoverParticipant, IHoverPart } from 'vs/editor/contrib/hover/modesContentHover'; import { HoverProviderRegistry } from 'vs/editor/common/modes'; import { getHover } from 'vs/editor/contrib/hover/getHover'; import { Position } from 'vs/editor/common/core/position'; import { CancellationToken } from 'vs/base/common/cancellation'; const $ = dom.$; export class MarkdownHover implements IHoverPart { constructor( public readonly range: Range, public readonly contents: IMarkdownString[] ) { } public equals(other: IHoverPart): boolean { if (other instanceof MarkdownHover) { return markedStringsEquals(this.contents, other.contents); } return false; } } export class MarkdownHoverParticipant implements IEditorHoverParticipant<MarkdownHover> { constructor( private readonly _editor: ICodeEditor, private readonly _hover: IEditorHover, @IModeService private readonly _modeService: IModeService, @IOpenerService private readonly _openerService: IOpenerService, ) { } public createLoadingMessage(range: Range): MarkdownHover { return new MarkdownHover(range, [new MarkdownString().appendText(nls.localize('modesContentHover.loading', "Loading..."))]); } public computeSync(hoverRange: Range, lineDecorations: IModelDecoration[]): MarkdownHover[] { if (!this._editor.hasModel()) { return []; } const model = this._editor.getModel(); const lineNumber = hoverRange.startLineNumber; const maxColumn = model.getLineMaxColumn(lineNumber); const result: MarkdownHover[] = []; for (const d of lineDecorations) { const startColumn = (d.range.startLineNumber === lineNumber) ? d.range.startColumn : 1; const endColumn = (d.range.endLineNumber === lineNumber) ? d.range.endColumn : maxColumn; const hoverMessage = d.options.hoverMessage; if (!hoverMessage || isEmptyMarkdownString(hoverMessage)) { continue; } const range = new Range(hoverRange.startLineNumber, startColumn, hoverRange.startLineNumber, endColumn); result.push(new MarkdownHover(range, asArray(hoverMessage))); } return result; } public async computeAsync(range: Range, token: CancellationToken): Promise<MarkdownHover[]> { if (!this._editor.hasModel() || !range) { return Promise.resolve([]); } const model = this._editor.getModel(); if (!HoverProviderRegistry.has(model)) { return Promise.resolve([]); } const hovers = await getHover(model, new Position( range.startLineNumber, range.startColumn ), token); const result: MarkdownHover[] = []; for (const hover of hovers) { if (isEmptyMarkdownString(hover.contents)) { continue; } const rng = hover.range ? Range.lift(hover.range) : range; result.push(new MarkdownHover(rng, hover.contents)); } return result; } public renderHoverParts(hoverParts: MarkdownHover[], fragment: DocumentFragment): IDisposable { const disposables = new DisposableStore(); for (const hoverPart of hoverParts) { for (const contents of hoverPart.contents) { if (isEmptyMarkdownString(contents)) { continue; } const markdownHoverElement = $('div.hover-row.markdown-hover'); const hoverContentsElement = dom.append(markdownHoverElement, $('div.hover-contents')); const renderer = disposables.add(new MarkdownRenderer({ editor: this._editor }, this._modeService, this._openerService)); disposables.add(renderer.onDidRenderAsync(() => { hoverContentsElement.className = 'hover-contents code-hover-contents'; this._hover.onContentsChanged(); })); const renderedContents = disposables.add(renderer.render(contents)); hoverContentsElement.appendChild(renderedContents.element); fragment.appendChild(markdownHoverElement); } } return disposables; } }
src/vs/editor/contrib/hover/markdownHoverParticipant.ts
0
https://github.com/microsoft/vscode/commit/fcd005ce8c39946f69a9cbc3f99ac222c70de2d4
[ 0.00017763789219316095, 0.00017238104192074388, 0.00016490310372319072, 0.00017244934861082584, 0.000003644947810244048 ]
{ "id": 0, "code_window": [ " return matchContext.router\n", " }\n", "\n", " const { history } = this.props\n", " const router = createRouterObject(history, this.transitionManager)\n", "\n", " return {\n", " ...router,\n", " location: state.location,\n", " params: state.params\n", " }\n", " },\n", "\n", " createTransitionManager() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return createRouterObject(history, this.transitionManager, state)\n" ], "file_path": "modules/Router.js", "type": "replace", "edit_start_line_idx": 64 }
export function createRouterObject(history, transitionManager) { return { ...history, setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute, isActive: transitionManager.isActive } }
modules/RouterUtils.js
1
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.0016386212082579732, 0.0016386212082579732, 0.0016386212082579732, 0.0016386212082579732, 0 ]
{ "id": 0, "code_window": [ " return matchContext.router\n", " }\n", "\n", " const { history } = this.props\n", " const router = createRouterObject(history, this.transitionManager)\n", "\n", " return {\n", " ...router,\n", " location: state.location,\n", " params: state.params\n", " }\n", " },\n", "\n", " createTransitionManager() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return createRouterObject(history, this.transitionManager, state)\n" ], "file_path": "modules/Router.js", "type": "replace", "edit_start_line_idx": 64 }
<!doctype html public "restroom"> <title>Nested Animations Example</title> <base href="/nested-animations"/> <link href="/global.css" rel="stylesheet"/> <body> <h1 class="breadcrumbs"><a href="/">React Router Examples</a> / Nested Animations</h1> <div id="example"/> <script src="/__build__/shared.js"></script> <script src="/__build__/nested-animations.js"></script>
examples/nested-animations/index.html
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.0001719979045446962, 0.0001719979045446962, 0.0001719979045446962, 0.0001719979045446962, 0 ]