From 8cec4c99012d3c7390b7f26d80f65e6d566935f5 Mon Sep 17 00:00:00 2001 From: ConnectDotz Date: Thu, 8 Aug 2024 15:02:44 -0400 Subject: [PATCH] Vscode coverage support (#1151) * supports vscode coverage API * update version --- .gitignore | 2 + __mocks__/vscode.ts | 18 +- jest.config.js | 2 +- package.json | 4 +- src/JestExt/core.ts | 13 +- src/JestExt/helper.ts | 5 +- src/JestExt/types.ts | 6 + src/JestProcessManagement/JestProcess.ts | 18 +- src/JestProcessManagement/types.ts | 49 +- src/test-provider/jest-test-run.ts | 10 +- src/test-provider/test-coverage.ts | 134 + src/test-provider/test-item-data.ts | 53 +- src/test-provider/test-provider-context.ts | 1 + src/test-provider/test-provider.ts | 28 +- src/test-provider/types.ts | 6 +- tests/JestExt/core.test.ts | 7 + tests/JestExt/helper.test.ts | 14 + .../JestProcessManagement/JestProcess.test.ts | 64 +- tests/diagnostics.test.ts | 1 + tests/test-helper.ts | 1 + tests/test-provider/jest-test-runt.test.ts | 16 +- tests/test-provider/test-coverage.test.ts | 245 ++ tests/test-provider/test-item-data.test.ts | 27 +- tests/test-provider/test-provider.test.ts | 170 +- typings/vscode.d.ts | 3146 ++++++++++++++--- 25 files changed, 3466 insertions(+), 574 deletions(-) create mode 100644 src/test-provider/test-coverage.ts create mode 100644 tests/test-provider/test-coverage.test.ts diff --git a/.gitignore b/.gitignore index b7f4def1d..a3e2160c7 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,5 @@ generated-icons/ *.vsix *.zip coverage_comparison_report.html +yarn-error.log + diff --git a/__mocks__/vscode.ts b/__mocks__/vscode.ts index d4ff4ec88..0f2f1de10 100644 --- a/__mocks__/vscode.ts +++ b/__mocks__/vscode.ts @@ -22,6 +22,10 @@ const window = { createWebviewPanel: jest.fn(), }; +const extensions = { + getExtension: jest.fn(), +}; + const workspace = { getConfiguration: jest.fn(), workspaceFolders: [], @@ -66,7 +70,6 @@ const commands = { registerTextEditorCommand: jest.fn(), }; -// eslint-disable-next-line @typescript-eslint/no-empty-function const CodeLens = function CodeLens() {}; const QuickInputButtons = { @@ -102,7 +105,15 @@ const QuickPickItemKind = { Default: 0, }; +// for coverage +const FileCoverage = jest.fn(); +const StatementCoverage = jest.fn(); +const BranchCoverage = jest.fn(); +const DeclarationCoverage = jest.fn(); +const TestCoverageCount = jest.fn(); + export = { + extensions, ThemeColor, CodeLens, languages, @@ -128,4 +139,9 @@ export = { TestRunRequest, ViewColumn, QuickPickItemKind, + FileCoverage, + StatementCoverage, + BranchCoverage, + DeclarationCoverage, + TestCoverageCount, }; diff --git a/jest.config.js b/jest.config.js index b93e94829..ca57ebf56 100644 --- a/jest.config.js +++ b/jest.config.js @@ -10,7 +10,7 @@ module.exports = { }, testEnvironment: 'node', testRegex: 'tests/.*\\.test\\.ts$', - collectCoverageFrom: ['src/**/*.ts'], + coveragePathIgnorePatterns: ['/node_modules/', '/tests/'], automock: true, moduleFileExtensions: ['ts', 'js', 'json'], unmockedModulePathPatterns: [ diff --git a/package.json b/package.json index 78549a2ee..917ae5d35 100644 --- a/package.json +++ b/package.json @@ -2,10 +2,10 @@ "name": "vscode-jest", "displayName": "Jest", "description": "Use Facebook's Jest With Pleasure.", - "version": "7.0.0", + "version": "6.3.0", "publisher": "Orta", "engines": { - "vscode": "^1.68.1" + "vscode": "^1.88.1" }, "author": { "name": "Orta Therox, ConnectDotz & Sean Poulter", diff --git a/src/JestExt/core.ts b/src/JestExt/core.ts index e1602e56d..fdb24fa34 100644 --- a/src/JestExt/core.ts +++ b/src/JestExt/core.ts @@ -18,7 +18,13 @@ import { resultsWithoutAnsiEscapeSequence } from '../TestResults/TestResult'; import { CoverageMapData } from 'istanbul-lib-coverage'; import { Logging } from '../logging'; import { createProcessSession, ProcessSession } from './process-session'; -import { JestExtContext, JestSessionEvents, JestExtSessionContext, JestRunEvent } from './types'; +import { + JestExtContext, + JestSessionEvents, + JestExtSessionContext, + JestRunEvent, + JestTestDataAvailableEvent, +} from './types'; import { extensionName, SupportedLanguageIds } from '../appGlobals'; import { createJestExtContext, getExtensionResourceSettings, prefixWorkspace } from './helper'; import { PluginResourceSettings } from '../Settings'; @@ -99,6 +105,7 @@ export class JestExt { onRunEvent: new vscode.EventEmitter(), onTestSessionStarted: new vscode.EventEmitter(), onTestSessionStopped: new vscode.EventEmitter(), + onTestDataAvailable: new vscode.EventEmitter(), }; this.setupRunEvents(this.events); @@ -863,8 +870,10 @@ export class JestExt { private updateWithData(data: JestTotalResults, process: JestProcessInfo): void { const noAnsiData = resultsWithoutAnsiEscapeSequence(data); const normalizedData = resultsWithLowerCaseWindowsDriveLetters(noAnsiData); - this._updateCoverageMap(normalizedData.coverageMap); + this.events.onTestDataAvailable.fire({ data: normalizedData, process }); + + this._updateCoverageMap(normalizedData.coverageMap); const statusList = this.testResultProvider.updateTestResults(normalizedData, process); updateDiagnostics(statusList, this.failDiagnostics); diff --git a/src/JestExt/helper.ts b/src/JestExt/helper.ts index 566ae5efb..5c12a0c3d 100644 --- a/src/JestExt/helper.ts +++ b/src/JestExt/helper.ts @@ -46,6 +46,9 @@ export const outputFileSuffix = (ws: string, extra?: string): string => { // replace non-word with '_' return s.replace(/\W/g, '_'); }; +export const collectCoverage = (coverage?: boolean, settings?: PluginResourceSettings) => + coverage ?? settings?.runMode.config.coverage ?? false; + export const createJestExtContext = ( workspaceFolder: vscode.WorkspaceFolder, settings: PluginResourceSettings, @@ -64,7 +67,7 @@ export const createJestExtContext = ( '', currentJestVersion, outputFileSuffix(ws, options?.outputFileSuffix), - options?.collectCoverage ?? settings.runMode.config.coverage ?? false, + collectCoverage(options?.collectCoverage, settings), settings.debugMode, settings.nodeEnv, settings.shell.toSetting(), diff --git a/src/JestExt/types.ts b/src/JestExt/types.ts index cc72b2329..5fa520fa1 100644 --- a/src/JestExt/types.ts +++ b/src/JestExt/types.ts @@ -43,10 +43,16 @@ export type JestRunEvent = RunEventBase & | { type: 'exit'; error?: string; code?: number } | { type: 'long-run'; threshold: number; numTotalTestSuites?: number } ); + +export interface JestTestDataAvailableEvent { + data: JestTotalResults; + process: JestProcessInfo; +} export interface JestSessionEvents { onRunEvent: vscode.EventEmitter; onTestSessionStarted: vscode.EventEmitter; onTestSessionStopped: vscode.EventEmitter; + onTestDataAvailable: vscode.EventEmitter; } export interface JestExtProcessContextRaw extends JestExtContext { updateWithData: (data: JestTotalResults, process: JestProcessInfo) => void; diff --git a/src/JestProcessManagement/JestProcess.ts b/src/JestProcessManagement/JestProcess.ts index 43d4d7db0..7e0277ba5 100644 --- a/src/JestProcessManagement/JestProcess.ts +++ b/src/JestProcessManagement/JestProcess.ts @@ -2,6 +2,7 @@ import * as vscode from 'vscode'; import { join } from 'path'; import { Runner, RunnerEvent, Options } from 'jest-editor-support'; import { JestExtContext, WatchMode } from '../JestExt/types'; +import { collectCoverage } from '../JestExt/helper'; import { extensionId } from '../appGlobals'; import { Logging } from '../logging'; import { JestProcessInfo, JestProcessRequest, ProcessStatus, UserDataType } from './types'; @@ -34,6 +35,7 @@ export class JestProcess implements JestProcessInfo { private desc: string; public readonly request: JestProcessRequest; public _status: ProcessStatus; + private coverage: boolean | undefined; private autoStopTimer?: NodeJS.Timeout; constructor( @@ -44,9 +46,11 @@ export class JestProcess implements JestProcessInfo { this.extContext = extContext; this.request = request; this.logging = extContext.loggingFactory.create(`JestProcess ${request.type}`); - this.id = `${request.type}-${SEQ++}`; - this.desc = `id: ${this.id}, request: ${requestString(request)}`; this._status = ProcessStatus.Pending; + this.coverage = collectCoverage(this.getRequestCoverage(), this.extContext.settings); + const extra = (this.coverage ? 'with-coverage:' : '') + `${SEQ++}`; + this.id = `${request.type}:${extra}`; + this.desc = `id: ${this.id}, request: ${requestString(request)}`; } public get status(): ProcessStatus { @@ -122,6 +126,15 @@ export class JestProcess implements JestProcessInfo { return `"${removeSurroundingQuote(aString)}"`; } + private getRequestCoverage(): boolean | undefined { + if (this.request.type === 'not-test') { + return; + } + // Note, we are ignoring coverage = false use-case, which doesn't exist yet, by returning undefined + // and let the runMode to decide in createRunnerWorkspace() + return this.request.coverage || undefined; + } + private getTestPathPattern(pattern: string): string[] { return this.extContext.settings.useJest30 ? ['--testPathPatterns', pattern] @@ -210,6 +223,7 @@ export class JestProcess implements JestProcessInfo { const runnerWorkspace = this.extContext.createRunnerWorkspace({ outputFileSuffix: this.request.schedule.queue === 'blocking-2' ? '2' : undefined, + collectCoverage: this.coverage, }); const runner = new Runner(runnerWorkspace, options); diff --git a/src/JestProcessManagement/types.ts b/src/JestProcessManagement/types.ts index 2981a9e06..f0a9b06fe 100644 --- a/src/JestProcessManagement/types.ts +++ b/src/JestProcessManagement/types.ts @@ -53,22 +53,8 @@ export interface TaskPredicate { filterByStatus?: TaskStatus[]; filterByContent?: boolean; } -/** - * define the eligibility for process scheduling - * @param queue the type of the queue - * @param dedupe a predicate to match the task in queue. - */ -export interface ScheduleStrategy { - queue: QueueType; - dedupe?: TaskPredicate; -} -interface JestProcessRequestCommon { - schedule: ScheduleStrategy; - listener: JestProcessListener; -} - -export type JestProcessRequestSimple = +type JestProcessTestRequestBase = | { type: Extract; } @@ -99,15 +85,38 @@ export type JestProcessRequestSimple = testFileNamePattern: string; testNamePattern: TestNamePattern; updateSnapshot?: boolean; - } - | { - type: Extract; - args: string[]; }; +type JestProcessTestRequestCommon = { + coverage?: boolean; +}; + +export type JestProcessTestRequestType = JestProcessTestRequestCommon & JestProcessTestRequestBase; + +type JestProcessNonTestRequest = { + type: Extract; + args: string[]; +}; + +type JestProcessRequestType = JestProcessTestRequestType | JestProcessNonTestRequest; + +/** + * define the eligibility for process scheduling + * @param queue the type of the queue + * @param dedupe a predicate to match the task in queue. + */ +export interface ScheduleStrategy { + queue: QueueType; + dedupe?: TaskPredicate; +} + +interface JestProcessRequestCommon { + schedule: ScheduleStrategy; + listener: JestProcessListener; +} export type JestProcessRequestTransform = (request: JestProcessRequest) => JestProcessRequest; -export type JestProcessRequestBase = JestProcessRequestSimple & { +export type JestProcessRequestBase = JestProcessRequestType & { transform?: JestProcessRequestTransform; }; export type JestProcessRequest = JestProcessRequestBase & JestProcessRequestCommon; diff --git a/src/test-provider/jest-test-run.ts b/src/test-provider/jest-test-run.ts index 332f79c5a..75c3d8c38 100644 --- a/src/test-provider/jest-test-run.ts +++ b/src/test-provider/jest-test-run.ts @@ -1,6 +1,6 @@ import * as vscode from 'vscode'; import { JestExtOutput, JestOutputTerminal, OutputOptions } from '../JestExt/output-terminal'; -import { JestTestProviderContext } from './test-provider-context'; +import { JestTestProviderContext, CreateTestRun } from './test-provider-context'; import { JestProcessInfo } from '../JestProcessManagement'; export type TestRunProtocol = Pick< @@ -8,7 +8,6 @@ export type TestRunProtocol = Pick< 'name' | 'enqueued' | 'started' | 'errored' | 'failed' | 'passed' | 'skipped' | 'end' >; -export type CreateTestRun = (request: vscode.TestRunRequest, name: string) => vscode.TestRun; export type EndProcessOption = { process: JestProcessInfo; delay?: number; reason?: string }; export type EndOption = EndProcessOption | { reason: string }; const isEndProcessOption = (arg?: EndOption): arg is EndProcessOption => @@ -41,7 +40,7 @@ export class JestTestRun implements JestExtOutput, TestRunProtocol { private request: vscode.TestRunRequest, private createRun: CreateTestRun ) { - this.name = `${this.context.ext.workspace.name}:${name}:${SEQ++}`; + this.name = `[${this.context.ext.workspace.name}] ${name}:${SEQ++}`; this.output = context.output; this.processes = new Map(); this.verbose = context.ext.settings.debugMode === true; @@ -89,6 +88,9 @@ export class JestTestRun implements JestExtOutput, TestRunProtocol { } // TestRunProtocol + public addCoverage = (fileCoverage: vscode.FileCoverage): void => { + this.vscodeRun()?.addCoverage(fileCoverage); + }; public enqueued = (test: vscode.TestItem): void => { this.vscodeRun()?.enqueued(test); }; @@ -129,7 +131,7 @@ export class JestTestRun implements JestExtOutput, TestRunProtocol { const pid = process.id; const pInfo = this.processes.get(pid); if (pInfo?.timeoutId) { - clearTimeout(pInfo?.timeoutId); + clearTimeout(pInfo.timeoutId); } if (!delay) { diff --git a/src/test-provider/test-coverage.ts b/src/test-provider/test-coverage.ts new file mode 100644 index 000000000..e065bc03b --- /dev/null +++ b/src/test-provider/test-coverage.ts @@ -0,0 +1,134 @@ +import * as vscode from 'vscode'; +import { FileCoverage, createFileCoverage, Range } from 'istanbul-lib-coverage'; +import { JestSessionEvents, JestTestDataAvailableEvent } from '../JestExt/types'; + +const isRange = (location: vscode.Position | vscode.Range): location is vscode.Range => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (location as any).start !== undefined && (location as any).end !== undefined; + +export class JestFileCoverage extends vscode.FileCoverage { + private iCoverage: FileCoverage; + private details?: vscode.FileCoverageDetail[]; + + constructor(fileCoverage: FileCoverage) { + const summary = fileCoverage.toSummary(); + super( + vscode.Uri.file(fileCoverage.path), + new vscode.TestCoverageCount(summary.lines.covered, summary.lines.total), + new vscode.TestCoverageCount(summary.branches.covered, summary.branches.total), + new vscode.TestCoverageCount(summary.functions.covered, summary.functions.total) + ); + this.iCoverage = fileCoverage; + } + public get rawCoverage(): FileCoverage { + return this.iCoverage; + } + + public loadDetails(): vscode.FileCoverageDetail[] { + if (this.details) { + return this.details; + } + + const transformed = this.iCoverage; + const details: vscode.FileCoverageDetail[] = []; + // zero-based line number to statement coverage + const statementByLine: Record = {}; + + const getEOL = (line: number): number | undefined => { + const statement = statementByLine[line]; + if (statement && isRange(statement.location)) { + return statement.location.end.character; + } + }; + // transform istanbul line number from 1-based to vscode 0-based + // and replace null end-column with the end of line, if available + const transformRange = (range: Range): vscode.Range => { + const endColumn = range.end.column ?? getEOL(range.end.line) ?? range.start.column; + return new vscode.Range( + range.start.line - 1, + range.start.column, + range.end.line - 1, + endColumn + ); + }; + + try { + // Collect statements and index by start line for direct access + Object.entries(transformed.statementMap).forEach(([statementId, range]) => { + const executionCount = transformed.s[statementId]; + const vRange = transformRange(range); + const statementCoverage = new vscode.StatementCoverage(executionCount, vRange); + details.push(statementCoverage); + statementByLine[vRange.start.line] = statementCoverage; + }); + + // Process branches and attach them directly to the corresponding statement coverage + Object.entries(transformed.branchMap).forEach(([branchId, branch]) => { + branch.locations.forEach((location, index) => { + const branchExecutionCount = transformed.b[branchId][index]; + const vRange = transformRange(location); + const branchCoverage = new vscode.BranchCoverage( + branchExecutionCount > 0, + vRange, + `"${branch.type.toUpperCase()}" (ID: ${branchId}, Path: ${index + 1})` + ); + + if (statementByLine[vRange.start.line]) { + statementByLine[vRange.start.line].branches.push(branchCoverage); + } + }); + }); + + // Process functions, adjusting end column using statementByLine if needed + Object.entries(transformed.fnMap).forEach(([functionId, func]) => { + const executionCount = transformed.f[functionId]; + const vRange = transformRange(func.loc); + details.push(new vscode.DeclarationCoverage(func.name, executionCount, vRange)); + }); + } catch (e) { + console.error(`JestFileCoverage getDetailed failed for ${this.iCoverage.path}:`, e); + return []; + } + + if (details.length > 0) { + this.details = details; + } + + return details; + } +} + +export class JestTestCoverageProvider { + private subscriptions: vscode.Disposable[] = []; + + constructor(events: JestSessionEvents) { + this.subscriptions.push(events.onTestDataAvailable.event(this.onTestDataAvailable)); + } + + private onTestDataAvailable = (event: JestTestDataAvailableEvent): void => { + const run = event.process.userData?.run; + if (event.data.coverageMap && run) { + for (const fileCoverage of Object.values(event.data.coverageMap)) { + const jestFileCoverage = new JestFileCoverage(createFileCoverage(fileCoverage)); + run.addCoverage(jestFileCoverage); + } + } + }; + + public async loadDetailedCoverage( + fileCoverage: vscode.FileCoverage + ): Promise { + if (!(fileCoverage instanceof JestFileCoverage)) { + throw new Error( + 'Invalid file coverage object, expected JestFileCoverage instance. but got: ' + + typeof fileCoverage + ); + } + const details = fileCoverage.loadDetails(); + return details; + } + + public dispose(): void { + this.subscriptions.forEach((sub) => sub.dispose()); + } +} diff --git a/src/test-provider/test-item-data.ts b/src/test-provider/test-item-data.ts index ae1bb6649..aa71c4c64 100644 --- a/src/test-provider/test-item-data.ts +++ b/src/test-provider/test-item-data.ts @@ -8,7 +8,7 @@ import { ItBlock, TestAssertionStatus } from 'jest-editor-support'; import { ContainerNode, DataNode, NodeType, ROOT_NODE_NAME } from '../TestResults/match-node'; import { Logging } from '../logging'; import { TestSuitChangeEvent } from '../TestResults/test-result-events'; -import { Debuggable, ItemCommand, TestItemData } from './types'; +import { Debuggable, ItemCommand, ScheduleTestOptions, TestItemData } from './types'; import { JestTestProviderContext } from './test-provider-context'; import { JestTestRun } from './jest-test-run'; import { JestProcessInfo, ProcessStatus } from '../JestProcessManagement'; @@ -20,7 +20,7 @@ import { outputManager } from '../output-manager'; import { TestNamePattern } from '../types'; interface JestRunnable { - getJestRunRequest: () => JestExtRequestType; + getJestRunRequest: (options?: ScheduleTestOptions) => JestExtRequestType; } interface WithUri { @@ -59,18 +59,18 @@ abstract class TestItemDataBase implements TestItemData, JestRunnable, WithUri { return true; } - scheduleTest(run: JestTestRun, itemCommand?: ItemCommand): void { + scheduleTest(run: JestTestRun, options?: ScheduleTestOptions): void { if (!this.isTestNameResolved()) { const parent = this.item.parent && this.context.getData(this.item.parent); if (parent) { run.end({ reason: 'unresolved parameterized test' }); run.updateRequest(new vscode.TestRunRequest([parent.item])); - return parent.scheduleTest(run, itemCommand); + return parent.scheduleTest(run, options); } this.context.output.write(`running an unresolved parameterized test might fail`, 'warn'); } - const jestRequest = this.getJestRunRequest(itemCommand); + const jestRequest = this.getJestRunRequest(options); this.deepItemState(this.item, run.enqueued); @@ -88,14 +88,14 @@ abstract class TestItemDataBase implements TestItemData, JestRunnable, WithUri { } } - runItemCommand(command: ItemCommand): void | Promise { - switch (command) { + runItemCommand(itemCommand: ItemCommand): void | Promise { + switch (itemCommand) { case ItemCommand.updateSnapshot: { const request = new vscode.TestRunRequest([this.item]); const run = this.context.createTestRun(request, { - name: `${command}-${this.item.id}`, + name: `${itemCommand}-${this.item.id}`, }); - this.scheduleTest(run, command); + this.scheduleTest(run, { itemCommand }); break; } case ItemCommand.viewSnapshot: { @@ -109,7 +109,7 @@ abstract class TestItemDataBase implements TestItemData, JestRunnable, WithUri { viewSnapshot(): Promise { return Promise.reject(`viewSnapshot is not supported for ${this.item.id}`); } - abstract getJestRunRequest(itemCommand?: ItemCommand): JestExtRequestType; + abstract getJestRunRequest(options?: ScheduleTestOptions): JestExtRequestType; } interface SnapshotItemCollection { @@ -152,9 +152,13 @@ export class WorkspaceRoot extends TestItemDataBase { return item; } - getJestRunRequest(itemCommand?: ItemCommand): JestExtRequestType { - const updateSnapshot = itemCommand === ItemCommand.updateSnapshot; - return { type: 'all-tests', nonBlocking: true, updateSnapshot }; + getJestRunRequest(options?: ScheduleTestOptions): JestExtRequestType { + return { + type: 'all-tests', + nonBlocking: true, + updateSnapshot: options?.itemCommand === ItemCommand.updateSnapshot, + coverage: options?.profile?.kind === vscode.TestRunProfileKind.Coverage, + }; } discoverTest(run: JestTestRun): void { const testList = this.context.ext.testResultProvider.getTestList(); @@ -427,7 +431,7 @@ export class WorkspaceRoot extends TestItemDataBase { case 'start': { this.deepItemState(event.process.userData?.testItem, run.started); outputManager.clearOutputOnRun(this.context.ext.output); - this.runLog('started'); + this.runLog(`"${event.process.id}" started`); break; } case 'end': { @@ -435,7 +439,7 @@ export class WorkspaceRoot extends TestItemDataBase { run.write(event.error, 'error'); event.process.userData = { ...(event.process.userData ?? {}), execError: true }; } - this.runLog('finished'); + this.runLog(`"${event.process.id}" finished`); run.end({ process: event.process, delay: 30000, reason: 'process end' }); break; } @@ -451,7 +455,7 @@ export class WorkspaceRoot extends TestItemDataBase { event.process.userData = { ...(event.process.userData ?? {}), execError: true }; } } - this.runLog('exited'); + this.runLog(`"${event.process.id}" exited`); run.end({ process: event.process, delay: 1000, reason: 'process exit' }); break; } @@ -494,12 +498,12 @@ export class FolderData extends TestItemDataBase { item.canResolveChildren = false; return item; } - getJestRunRequest(itemCommand?: ItemCommand): JestExtRequestType { - const updateSnapshot = itemCommand === ItemCommand.updateSnapshot; + getJestRunRequest(options?: ScheduleTestOptions): JestExtRequestType { return { type: 'by-file-pattern', - updateSnapshot, testFileNamePattern: this.uri.fsPath, + updateSnapshot: options?.itemCommand === ItemCommand.updateSnapshot, + coverage: options?.profile?.kind === vscode.TestRunProfileKind.Coverage, }; } } @@ -684,12 +688,12 @@ export class TestDocumentRoot extends TestResultData { this.forEachChild((child) => child.updateResultState(run)); } - getJestRunRequest(itemCommand?: ItemCommand): JestExtRequestType { - const updateSnapshot = itemCommand === ItemCommand.updateSnapshot; + getJestRunRequest(options?: ScheduleTestOptions): JestExtRequestType { return { type: 'by-file-pattern', - updateSnapshot, testFileNamePattern: this.uri.fsPath, + updateSnapshot: options?.itemCommand === ItemCommand.updateSnapshot, + coverage: options?.profile?.kind === vscode.TestRunProfileKind.Coverage, }; } @@ -737,12 +741,13 @@ export class TestData extends TestResultData implements Debuggable { return { value: this.node.fullName, exactMatch: false }; } - getJestRunRequest(itemCommand?: ItemCommand): JestExtRequestType { + getJestRunRequest(options?: ScheduleTestOptions): JestExtRequestType { return { type: 'by-file-test-pattern', - updateSnapshot: itemCommand === ItemCommand.updateSnapshot, testFileNamePattern: this.uri.fsPath, testNamePattern: this.getTestNamePattern(), + updateSnapshot: options?.itemCommand === ItemCommand.updateSnapshot, + coverage: options?.profile?.kind === vscode.TestRunProfileKind.Coverage, }; } diff --git a/src/test-provider/test-provider-context.ts b/src/test-provider/test-provider-context.ts index 637b9bc23..a299a2f01 100644 --- a/src/test-provider/test-provider-context.ts +++ b/src/test-provider/test-provider-context.ts @@ -15,6 +15,7 @@ export type TagIdType = 'run' | 'debug' | 'update-snapshot'; export interface JestTestRunOptions { name?: string; } +export type CreateTestRun = vscode.TestController['createTestRun']; let SEQ = 0; export class JestTestProviderContext { diff --git a/src/test-provider/test-provider.ts b/src/test-provider/test-provider.ts index 5a1cdf2af..01139670f 100644 --- a/src/test-provider/test-provider.ts +++ b/src/test-provider/test-provider.ts @@ -7,6 +7,7 @@ import { Logging } from '../logging'; import { toErrorString } from '../helpers'; import { tiContextManager } from './test-item-context-manager'; import { JestTestRun } from './jest-test-run'; +import { JestTestCoverageProvider } from './test-coverage'; // eslint-disable-next-line @typescript-eslint/no-explicit-any const isDebuggable = (arg: any): arg is Debuggable => arg && typeof arg.getDebugInfo === 'function'; @@ -16,6 +17,7 @@ export class JestTestProvider { private context: JestTestProviderContext; private workspaceRoot: WorkspaceRoot; private log: Logging; + private coverageProvider: JestTestCoverageProvider; constructor(jestContext: JestExtExplorerContext) { this.log = jestContext.loggingFactory.create('JestTestProvider'); @@ -29,6 +31,7 @@ export class JestTestProvider { this.createProfiles(this.controller) ); this.workspaceRoot = new WorkspaceRoot(this.context); + this.coverageProvider = new JestTestCoverageProvider(this.context.ext.sessionEvents); this.updateMenuContext(); } @@ -58,7 +61,7 @@ export class JestTestProvider { const runTag = new vscode.TestTag(TestTagId.Run); const debugTag = new vscode.TestTag(TestTagId.Debug); const runProfile = controller.createRunProfile( - 'run', + 'run tests', vscode.TestRunProfileKind.Run, this.runTests, true, @@ -71,15 +74,29 @@ export class JestTestProvider { ); }; const debugProfile = controller.createRunProfile( - 'debug', + 'debug tests', vscode.TestRunProfileKind.Debug, this.runTests, true, debugTag ); - return [runProfile, debugProfile]; + const coverageProfile = controller.createRunProfile( + 'run tests with coverage', + vscode.TestRunProfileKind.Coverage, + this.runTests, + false, + runTag + ); + coverageProfile.loadDetailedCoverage = this.loadDetailedCoverage; + return [runProfile, debugProfile, coverageProfile]; }; + private loadDetailedCoverage = async ( + _testRun: vscode.TestRun, + fileCoverage: vscode.FileCoverage + ): Promise => + this.coverageProvider.loadDetailedCoverage(fileCoverage); + private discoverTest = (item: vscode.TestItem | undefined): void => { const theItem = item ?? this.workspaceRoot.item; if (!theItem.canResolveChildren) { @@ -161,7 +178,7 @@ export class JestTestProvider { } const run = this.context.createTestRun(req, { - name: `runTest: ${this.controller.id}`, + name: `${request.profile?.label ?? 'runTest'}: ${this.controller.id}`, }); cancelToken?.onCancellationRequested(() => { @@ -180,7 +197,7 @@ export class JestTestProvider { await this.debugTest(tData, run); } else { try { - tData.scheduleTest(run); + tData.scheduleTest(run, { profile: request.profile }); } catch (e) { const msg = `failed to schedule test for ${tData.item.id}: ${toErrorString(e)}`; this.log('error', msg, e); @@ -200,5 +217,6 @@ export class JestTestProvider { dispose(): void { this.workspaceRoot.dispose(); this.controller.dispose(); + this.coverageProvider.dispose(); } } diff --git a/src/test-provider/types.ts b/src/test-provider/types.ts index 6856291bc..7a019f493 100644 --- a/src/test-provider/types.ts +++ b/src/test-provider/types.ts @@ -15,12 +15,16 @@ export interface JestExtExplorerContext extends JestExtSessionContext { debugTests: DebugFunction; } +export interface ScheduleTestOptions { + itemCommand?: ItemCommand; + profile?: vscode.TestRunProfile; +} export interface TestItemData { readonly item: vscode.TestItem; readonly uri: vscode.Uri; context: JestTestProviderContext; discoverTest?: (run: JestTestRun) => void; - scheduleTest: (run: JestTestRun, itemCommand?: ItemCommand) => void; + scheduleTest: (run: JestTestRun, options?: ScheduleTestOptions) => void; runItemCommand: (command: ItemCommand) => void; } diff --git a/tests/JestExt/core.test.ts b/tests/JestExt/core.test.ts index 80528ca97..335c41139 100644 --- a/tests/JestExt/core.test.ts +++ b/tests/JestExt/core.test.ts @@ -1024,6 +1024,13 @@ describe('JestExt', () => { updateWithData(); expect(triggerUpdateActiveEditorSpy).toHaveBeenCalledTimes(2); }); + it('will fire onTestDataAvailable event', () => { + const process: any = { id: 'a process id' }; + updateWithData({}, process); + expect(sut.events.onTestDataAvailable.fire).toHaveBeenCalledWith( + expect.objectContaining({ data: expect.anything(), process }) + ); + }); }); describe('deactivate', () => { diff --git a/tests/JestExt/helper.test.ts b/tests/JestExt/helper.test.ts index b1d0606cf..87e5781f6 100644 --- a/tests/JestExt/helper.test.ts +++ b/tests/JestExt/helper.test.ts @@ -10,6 +10,7 @@ jest.mock('os', () => ({ platform: mockPlatform, userInfo: mockUserInfo })); import * as vscode from 'vscode'; import { readFileSync } from 'fs'; import { + collectCoverage, createJestExtContext, getExtensionResourceSettings, isWatchRequest, @@ -236,3 +237,16 @@ describe('prefixWorkspace', () => { expect(prefixWorkspace(context, 'a message')).toEqual('(ws) a message'); }); }); + +describe('collectCoverage', () => { + it.each` + case | coverage | settings | expected + ${1} | ${undefined} | ${undefined} | ${false} + ${2} | ${true} | ${{ runMode: { config: { coverage: false } } }} | ${true} + ${3} | ${false} | ${{ runMode: { config: { coverage: true } } }} | ${false} + ${4} | ${undefined} | ${{ runMode: { config: { coverage: true } } }} | ${true} + ${5} | ${undefined} | ${{ runMode: { config: { coverage: false } } }} | ${false} + `('case $case', ({ coverage, settings, expected }) => { + expect(collectCoverage(coverage, settings)).toEqual(expected); + }); +}); diff --git a/tests/JestProcessManagement/JestProcess.test.ts b/tests/JestProcessManagement/JestProcess.test.ts index 2407b7dc8..626cc1cfd 100644 --- a/tests/JestProcessManagement/JestProcess.test.ts +++ b/tests/JestProcessManagement/JestProcess.test.ts @@ -8,6 +8,7 @@ const mockRelease = jest.fn(); mockRelease.mockReturnValue(''); jest.mock('os', () => ({ platform: mockPlatform, release: mockRelease })); +import * as vscode from 'vscode'; import { Runner } from 'jest-editor-support'; import { JestProcess, RunnerEvents } from '../../src/JestProcessManagement/JestProcess'; import { EventEmitter } from 'events'; @@ -15,14 +16,8 @@ import { mockProcessRequest, mockJestExtContext } from '../test-helper'; import { normalize } from 'path'; import { JestProcessRequest, ProcessStatus } from '../../src/JestProcessManagement/types'; import { JestTestProcessType } from '../../src/Settings'; +import { collectCoverage } from '../../src/JestExt/helper'; jest.unmock('path'); -jest.mock('vscode', () => ({ - extensions: { - getExtension: () => { - return { extensionPath: normalize('/my/vscode/extensions') }; - }, - }, -})); describe('JestProcess', () => { let jestProcess; @@ -52,6 +47,9 @@ describe('JestProcess', () => { }; RunnerClassMock.mockReturnValueOnce(mockRunner); extContext = mockJestExtContext(); + (vscode.extensions.getExtension as jest.Mocked).mockReturnValue({ + extensionPath: normalize('/my/vscode/extensions'), + }); }); it('can report its own state via toString()', () => { @@ -59,7 +57,7 @@ describe('JestProcess', () => { jestProcess = new JestProcess(extContext, request); expect(`${jestProcess}`).toEqual(jestProcess.toString()); expect(jestProcess.toString()).toMatchInlineSnapshot( - `"JestProcess: id: all-tests-0, request: {"type":"all-tests","schedule":{"queue":"blocking"},"listener":"function"}; status: "pending""` + `"JestProcess: id: all-tests:0, request: {"type":"all-tests","schedule":{"queue":"blocking"},"listener":"function"}; status: "pending""` ); }); describe('when creating', () => { @@ -97,6 +95,19 @@ describe('JestProcess', () => { expect(jestProcess.isWatchMode).toEqual(isWatchMode); }); }); + describe('populate an id based on request info', () => { + it.each` + requestType | extraProperty | expected + ${'all-tests'} | ${undefined} | ${'all-tests:'} + ${'all-tests'} | ${{ coverage: true }} | ${'all-tests:with-coverage:'} + ${'watch-tests'} | ${undefined} | ${'watch-tests:'} + `('$requestType:$extraProperty', ({ requestType, extraProperty, expected }) => { + (collectCoverage as jest.Mocked).mockImplementation((c) => c); + const request = mockProcessRequest(requestType, extraProperty); + jestProcess = new JestProcess(extContext, request); + expect(jestProcess.id).toEqual(expect.stringContaining(expected)); + }); + }); }); describe('when start', () => { it('returns a promise that resolved when process closed', async () => { @@ -337,6 +348,43 @@ describe('JestProcess', () => { expect.objectContaining({ outputFileSuffix: expect.stringContaining('2') }) ); }); + describe('can pass on coverage info from request', () => { + it.each` + requestType | extraProperty | canPassCoverage + ${'all-tests'} | ${undefined} | ${true} + ${'watch-tests'} | ${undefined} | ${true} + ${'watch-all-tests'} | ${undefined} | ${true} + ${'by-file'} | ${{ testFileName: '"c:\\a\\b.ts"' }} | ${true} + ${'by-file-test'} | ${{ testFileName: '"/a/b.js"', testNamePattern: 'a test' }} | ${true} + ${'by-file-pattern'} | ${{ testFileNamePattern: '"c:\\a\\b.ts"' }} | ${true} + ${'by-file-test-pattern'} | ${{ testFileNamePattern: '/a/b.js', testNamePattern: 'a test' }} | ${true} + ${'not-test'} | ${{ args: ['--listTests', '--watchAll=false'] }} | ${false} + `('$requestType', ({ requestType, extraProperty, canPassCoverage }) => { + expect.hasAssertions(); + (collectCoverage as jest.Mocked).mockImplementation((c) => c); + // when no coverage + let req = mockRequest(requestType, extraProperty); + jestProcess = new JestProcess(extContext, req); + jestProcess.start(); + expect(extContext.createRunnerWorkspace).not.toHaveBeenCalledWith( + expect.objectContaining({ collectCoverage: true }) + ); + + // when with coverage + req = mockRequest(requestType, { ...extraProperty, coverage: true }); + jestProcess = new JestProcess(extContext, req); + jestProcess.start(); + if (canPassCoverage) { + expect(extContext.createRunnerWorkspace).toHaveBeenCalledWith( + expect.objectContaining({ collectCoverage: true }) + ); + } else { + expect(extContext.createRunnerWorkspace).not.toHaveBeenCalledWith( + expect.objectContaining({ collectCoverage: true }) + ); + } + }); + }); }); describe('to interrupt the process', () => { diff --git a/tests/diagnostics.test.ts b/tests/diagnostics.test.ts index 73a74c70a..d23403139 100644 --- a/tests/diagnostics.test.ts +++ b/tests/diagnostics.test.ts @@ -25,6 +25,7 @@ class MockDiagnosticCollection implements vscode.DiagnosticCollection { get = jest.fn(); has = jest.fn(); dispose = jest.fn(); + [Symbol.iterator] = jest.fn(); // Add this line } vscode.window.visibleTextEditors = []; diff --git a/tests/test-helper.ts b/tests/test-helper.ts index c974136c5..3a4b6ae21 100644 --- a/tests/test-helper.ts +++ b/tests/test-helper.ts @@ -166,6 +166,7 @@ export const mockJestExtEvents: any = () => ({ onRunEvent: mockEvent(), onTestSessionStarted: mockEvent(), onTestSessionStopped: mockEvent(), + onTestDataAvailable: mockEvent(), }); export const mockJestExtContext = (runMode?: RunMode): any => { diff --git a/tests/test-provider/jest-test-runt.test.ts b/tests/test-provider/jest-test-runt.test.ts index b379aafcc..760e36ba7 100644 --- a/tests/test-provider/jest-test-runt.test.ts +++ b/tests/test-provider/jest-test-runt.test.ts @@ -41,6 +41,7 @@ describe('JestTestRun', () => { passed: jest.fn(), skipped: jest.fn(), end: jest.fn(), + addCoverage: jest.fn(), })); mockRequest = {}; @@ -51,7 +52,7 @@ describe('JestTestRun', () => { describe('constructor', () => { it('should set the name property', () => { - expect(jestRun.name).toBe('testWorkspace:test:0'); + expect(jestRun.name).toBe('[testWorkspace] test:0'); }); it('does not create vscode TestRun until it is needed', () => { expect(mockCreateTestRun).not.toHaveBeenCalled(); @@ -318,6 +319,16 @@ describe('JestTestRun', () => { }); }); }); + describe('addCoverage', () => { + it('should call the addCoverage method on the test run', () => { + const coverage = {} as vscode.FileCoverage; + expect(mockCreateTestRun).toHaveBeenCalledTimes(0); + jestRun.addCoverage(coverage); + expect(mockCreateTestRun).toHaveBeenCalledTimes(1); + const run = mockCreateTestRun.mock.results[0].value; + expect(run.addCoverage).toHaveBeenCalledWith(coverage); + }); + }); }); it('print warning for runs re-created after close: this means the test-run will be splitted into multiple TestRun', () => { mockContext.ext.settings.debugMode = true; @@ -472,6 +483,9 @@ describe('JestTestRun', () => { jestRun.skipped({} as any); expect(run.skipped).not.toHaveBeenCalled(); + jestRun.addCoverage({} as any); + expect(run.addCoverage).not.toHaveBeenCalled(); + // no new run should be created expect(mockCreateTestRun).not.toHaveBeenCalled(); }); diff --git a/tests/test-provider/test-coverage.test.ts b/tests/test-provider/test-coverage.test.ts new file mode 100644 index 000000000..01c5ed2ed --- /dev/null +++ b/tests/test-provider/test-coverage.test.ts @@ -0,0 +1,245 @@ +jest.unmock('../../src/test-provider/test-coverage'); + +import * as vscode from 'vscode'; +import { JestFileCoverage, JestTestCoverageProvider } from '../../src/test-provider/test-coverage'; +import { createFileCoverage } from 'istanbul-lib-coverage'; + +const createFileCoverageMock = (): any => ({ + path: '/path/to/file', + toSummary: jest.fn().mockReturnValue({ + lines: { covered: 10, total: 20 }, + branches: { covered: 5, total: 10 }, + functions: { covered: 3, total: 5 }, + }), + statementMap: { + '1': { start: { line: 1, column: 0 }, end: { line: 1, column: 10 } }, + '2': { start: { line: 2, column: 0 }, end: { line: 2, column: 20 } }, + }, + s: { '1': 5, '2': 3, '3': 2 }, + branchMap: { + '1': { + locations: [ + { start: { line: 1, column: 0 }, end: { line: 1, column: 5 } }, + { start: { line: 2, column: 10 }, end: { line: 2, column: 15 } }, + ], + type: 'if', + }, + }, + b: { '1': [1, 0] }, + fnMap: { + '1': { + name: 'testFunction', + loc: { start: { line: 1, column: 0 }, end: { line: 3, column: 10 } }, + }, + }, + f: { '1': 2 }, +}); + +describe('test-coverage', () => { + beforeEach(() => { + jest.resetAllMocks(); + vscode.Uri.file = jest.fn().mockImplementation((path) => ({ fsPath: path })); + (vscode.TestCoverageCount as jest.Mocked).mockImplementation((covered, total) => ({ + covered, + total, + })); + (vscode.Range as jest.Mocked).mockImplementation((sl, sc, el, ec) => ({ + start: { line: sl, column: sc }, + end: { line: el, column: ec }, + })); + (vscode.StatementCoverage as jest.Mocked).mockImplementation( + (count, location, branches) => ({ + count, + location, + branches: branches ?? [], + }) + ); + (vscode.BranchCoverage as jest.Mocked).mockImplementation((count, location, label) => ({ + count, + location, + label, + })); + (vscode.DeclarationCoverage as jest.Mocked).mockImplementation( + (name, count, location) => ({ + name, + count, + location, + }) + ); + (createFileCoverage as jest.Mocked).mockImplementation((data) => { + return data; + }); + }); + + describe('JestFileCoverage', () => { + let jestFileCoverage: JestFileCoverage; + let fileCoverageMock: any; + + beforeEach(() => { + fileCoverageMock = createFileCoverageMock(); + + jestFileCoverage = new JestFileCoverage(fileCoverageMock); + }); + + it('is an instance of vscode.FileCoverage', () => { + expect(jestFileCoverage).toBeInstanceOf(JestFileCoverage); + expect(vscode.FileCoverage).toHaveBeenCalledWith( + vscode.Uri.file(fileCoverageMock.path), + new vscode.TestCoverageCount(10, 20), + new vscode.TestCoverageCount(5, 10), + new vscode.TestCoverageCount(3, 5) + ); + }); + + it('should return the raw coverage', () => { + expect(jestFileCoverage.rawCoverage).toEqual(fileCoverageMock); + }); + + describe('loadDetails', () => { + it('should return the details if already loaded', () => { + const detailsMock = [new vscode.StatementCoverage(5, new vscode.Range(0, 0, 0, 10))]; + jestFileCoverage['details'] = detailsMock; + + const details = jestFileCoverage.loadDetails(); + + expect(details).toEqual(detailsMock); + }); + + it('should load and return the details', () => { + const details = jestFileCoverage.loadDetails(); + + expect(details).toEqual([ + new vscode.StatementCoverage(5, new vscode.Range(0, 0, 0, 10), [ + new vscode.BranchCoverage(true, new vscode.Range(0, 0, 0, 5), '"IF" (ID: 1, Path: 1)'), + ]), + new vscode.StatementCoverage(3, new vscode.Range(1, 0, 1, 20), [ + new vscode.BranchCoverage( + false, + new vscode.Range(1, 10, 1, 15), + '"IF" (ID: 1, Path: 2)' + ), + ]), + new vscode.DeclarationCoverage('testFunction', 2, new vscode.Range(0, 0, 2, 10)), + ]); + }); + + describe('handle invalid data', () => { + it('if statementMap location has no end column, it should use the start column', () => { + fileCoverageMock = createFileCoverageMock(); + fileCoverageMock.statementMap['3'] = { + start: { line: 3, column: 0 }, + end: { line: 3, column: null }, + }; + jestFileCoverage = new JestFileCoverage(fileCoverageMock); + const details = jestFileCoverage.loadDetails(); + const statement: any = details.find((d: any) => d.location.start.line === 2); + expect(statement.location.end.column).toBe(statement.location.start.column); + }); + it('if branchMap location has no end column, it should use the eol from statement coverage', () => { + fileCoverageMock = createFileCoverageMock(); + fileCoverageMock.branchMap['1'].locations[0].end.column = null; + jestFileCoverage = new JestFileCoverage(fileCoverageMock); + const details = jestFileCoverage.loadDetails(); + const branch: any = details.find((d: any) => d.branches?.[0].location.start.line === 0); + + // statement line 1's end column is 10 + expect(branch.location.end.column).toBe(10); + }); + it('if function location has no end column, it should use the eol from statement coverage', () => { + fileCoverageMock = createFileCoverageMock(); + fileCoverageMock.fnMap['1'].loc.end.column = null; + jestFileCoverage = new JestFileCoverage(fileCoverageMock); + const details = jestFileCoverage.loadDetails(); + const func: any = details.find((d: any) => d.location.start.line === 0); + + // statement line 1's end column is 10 + expect(func.location.end.column).toBe(10); + }); + }); + it('if exception occurs, it will returns empty array', () => { + (vscode.Range as jest.Mocked).mockImplementation(() => { + throw new Error('Test error'); + }); + const saved = console.error; + console.error = jest.fn(); + + fileCoverageMock = createFileCoverageMock(); + jestFileCoverage = new JestFileCoverage(fileCoverageMock); + expect(jestFileCoverage.loadDetails()).toEqual([]); + expect(console.error).toHaveBeenCalled(); + console.error = saved; + }); + }); + }); + + describe('JestTestCoverageProvider', () => { + const createMockRun = () => ({ addCoverage: jest.fn() }); + let mockEvents: any; + let mockSubscription: any; + let mockRun: any; + beforeEach(() => { + mockRun = createMockRun(); + mockSubscription = { dispose: jest.fn() }; + mockEvents = { + onTestDataAvailable: { event: jest.fn().mockReturnValue(mockSubscription) }, + }; + }); + + describe('handle test data available event', () => { + it('register for the event upon creation', () => { + new JestTestCoverageProvider(mockEvents); + expect(mockEvents.onTestDataAvailable.event).toHaveBeenCalled(); + }); + it('will dispose the subscription on dispose', () => { + const provider = new JestTestCoverageProvider(mockEvents); + provider.dispose(); + expect(mockSubscription.dispose).toHaveBeenCalled(); + }); + describe('onTestDataAvailable', () => { + describe('extract coverage data from test data and add to run', () => { + it.each` + case | hasCoverage | process | doNothing + ${1} | ${false} | ${{}} | ${true} + ${2} | ${false} | ${{ userData: {} }} | ${true} + ${3} | ${false} | ${{ userData: { run: createMockRun() } }} | ${true} + ${4} | ${true} | ${{}} | ${true} + ${5} | ${true} | ${{ userData: {} }} | ${true} + ${6} | ${true} | ${{ userData: { run: createMockRun() } }} | ${false} + `('case $case', ({ hasCoverage, process, doNothing }) => { + const data = hasCoverage ? { coverageMap: { '1': createFileCoverageMock() } } : {}; + const event: any = { + data, + process, + }; + new JestTestCoverageProvider(mockEvents); + const onTestDataAvailable = mockEvents.onTestDataAvailable.event.mock.calls[0][0]; + onTestDataAvailable(event); + if (doNothing) { + expect(vscode.FileCoverage).not.toHaveBeenCalled(); + expect(mockRun.addCoverage).not.toHaveBeenCalled(); + } else { + expect(vscode.FileCoverage).toHaveBeenCalledTimes(1); + expect(process.userData.run.addCoverage).toHaveBeenCalledTimes(1); + } + }); + }); + }); + }); + describe('loadDetailedCoverage', () => { + it('expect a JestFileCoverage', async () => { + expect.hasAssertions(); + + const provider = new JestTestCoverageProvider(mockEvents); + await expect(provider.loadDetailedCoverage({} as any)).rejects.toThrow( + /Invalid file coverage object/ + ); + }); + it('should return the details', async () => { + const provider = new JestTestCoverageProvider(mockEvents); + const fileCoverage = new JestFileCoverage(createFileCoverageMock()); + const details = await provider.loadDetailedCoverage(fileCoverage); + expect(details.length > 0).toBeTruthy(); + }); + }); + }); +}); diff --git a/tests/test-provider/test-item-data.test.ts b/tests/test-provider/test-item-data.test.ts index e2a46c91e..2b6c03114 100644 --- a/tests/test-provider/test-item-data.test.ts +++ b/tests/test-provider/test-item-data.test.ts @@ -147,7 +147,6 @@ describe('test-item-data', () => { const data = context.getData(item); const jestRun = createTestRun(); data.scheduleTest(jestRun); - // mockedJestTestRun.mockClear(); return item; }; @@ -879,7 +878,7 @@ describe('test-item-data', () => { expect(process.userData.testItem.id).toBe(testItem.item.id); }); }); - describe('can update snapshot based on runProfile', () => { + describe('can update snapshot', () => { let wsRoot, folder, doc, testItem; beforeEach(() => { ({ wsRoot, folder, doc, testItem } = createAllTestItems()); @@ -887,7 +886,7 @@ describe('test-item-data', () => { it('with snapshot profile', () => { [wsRoot, folder, doc, testItem].forEach((testItem) => { const jestRun = createTestRun(); - testItem.scheduleTest(jestRun, ItemCommand.updateSnapshot); + testItem.scheduleTest(jestRun, { itemCommand: ItemCommand.updateSnapshot }); expect(context.ext.session.scheduleProcess).toHaveBeenCalledWith( expect.objectContaining({ updateSnapshot: true, @@ -897,6 +896,28 @@ describe('test-item-data', () => { }); }); }); + describe('can run with coverage', () => { + let wsRoot, folder, doc, testItem; + beforeEach(() => { + ({ wsRoot, folder, doc, testItem } = createAllTestItems()); + }); + it('with coverage profile', () => { + [wsRoot, folder, doc, testItem].forEach((itemDaa) => { + const jestRun = createTestRun(); + // test for each test data + context.ext.session.scheduleProcess.mockClear(); + itemDaa.scheduleTest(jestRun, { + profile: { kind: vscode.TestRunProfileKind.Coverage }, + }); + expect(context.ext.session.scheduleProcess).toHaveBeenCalledWith( + expect.objectContaining({ + coverage: true, + }), + expect.anything() + ); + }); + }); + }); }); describe('when test result is ready', () => { diff --git a/tests/test-provider/test-provider.test.ts b/tests/test-provider/test-provider.test.ts index dd01db885..f8cd28f0c 100644 --- a/tests/test-provider/test-provider.test.ts +++ b/tests/test-provider/test-provider.test.ts @@ -16,6 +16,7 @@ import { tiContextManager } from '../../src/test-provider/test-item-context-mana import { ItemCommand } from '../../src/test-provider/types'; import { RunMode } from '../../src/JestExt/run-mode'; import { JestTestRun } from '../../src/test-provider/jest-test-run'; +import { JestTestCoverageProvider } from '../../src/test-provider/test-coverage'; const throwError = () => { throw new Error('debug error'); @@ -45,14 +46,23 @@ describe('JestTestProvider', () => { return data; }; + const setupItemData = (context, items = [1, 2, 3]) => { + const itemDataList = items.map((n) => setupTestItemData(`item-${n}`, true, context)); + itemDataList.forEach((d) => { + d.context = { workspace: { name: 'whatever' } }; + d.getDebugInfo = jest.fn().mockReturnValueOnce({}); + }); + return itemDataList; + }; + let controllerMock; let extExplorerContextMock; let workspaceRootMock; let mockTestTag; const mockedJestTestRun = JestTestRun as jest.MockedClass; + let mockCoverageProvider: any; beforeEach(() => { - // jest.resetAllMocks(); jest.clearAllMocks(); extExplorerContextMock = mockExtExplorerContext(); @@ -76,6 +86,8 @@ describe('JestTestProvider', () => { workspaceRootMock.context = context; return workspaceRootMock; }); + mockCoverageProvider = { loadDetailedCoverage: jest.fn(), dispose: jest.fn() }; + (JestTestCoverageProvider as jest.MockedClass).mockReturnValue(mockCoverageProvider); }); describe('upon creation', () => { @@ -87,29 +99,64 @@ describe('JestTestProvider', () => { `${extensionId}:TestProvider:ws-1`, expect.stringContaining('ws-1') ); - expect(controllerMock.createRunProfile).toHaveBeenCalledTimes(2); - [ - [vscode.TestRunProfileKind.Run, 'run', true], - [vscode.TestRunProfileKind.Debug, 'debug', true], - ].forEach(([kind, id, isDefault]) => { + expect(controllerMock.createRunProfile).toHaveBeenCalledTimes(3); + expect(WorkspaceRoot).toHaveBeenCalled(); + }); + describe('profiles', () => { + it('the default run profile', () => { + new JestTestProvider(extExplorerContextMock); + expect(controllerMock.createRunProfile).toHaveBeenCalledWith( + 'run tests', + vscode.TestRunProfileKind.Run, + expect.any(Function), + true, + { id: 'run' } + ); const profile = controllerMock.createRunProfile.mock.results.find( - (r) => r.value.label === id + (r) => r.value.kind === vscode.TestRunProfileKind.Run )?.value; - expect(profile.kind).toEqual(kind); - expect(profile.isDefault).toEqual(isDefault); - if (id === 'run') { - expect(profile.configureHandler).toBeDefined(); - profile.configureHandler(); - expect(vscode.commands.executeCommand).toHaveBeenCalledWith( - expect.stringContaining(`with-workspace.change-run-mode`), - extExplorerContextMock.workspace - ); - } else { - expect(profile.configureHandler).not.toBeDefined(); - } + expect(profile.configureHandler).toBeDefined(); + expect(profile.runHandler).toBeDefined(); + profile.configureHandler(); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + expect.stringContaining(`with-workspace.change-run-mode`), + extExplorerContextMock.workspace + ); + expect(profile.loadDetailedCoverage).not.toBeDefined(); + }); + + it('the default debug profile', () => { + new JestTestProvider(extExplorerContextMock); + expect(controllerMock.createRunProfile).toHaveBeenCalledWith( + 'debug tests', + vscode.TestRunProfileKind.Debug, + expect.any(Function), + true, + { id: 'debug' } + ); + const profile = controllerMock.createRunProfile.mock.results.find( + (r) => r.value.kind === vscode.TestRunProfileKind.Debug + )?.value; + expect(profile.runHandler).toBeDefined(); + expect(profile.configureHandler).not.toBeDefined(); + expect(profile.loadDetailedCoverage).not.toBeDefined(); + }); + it('the coverage profile', () => { + new JestTestProvider(extExplorerContextMock); + expect(controllerMock.createRunProfile).toHaveBeenCalledWith( + 'run tests with coverage', + vscode.TestRunProfileKind.Coverage, + expect.any(Function), + false, + { id: 'run' } + ); + const profile = controllerMock.createRunProfile.mock.results.find( + (r) => r.value.kind === vscode.TestRunProfileKind.Coverage + )?.value; + expect(profile.runHandler).toBeDefined(); + expect(profile.configureHandler).not.toBeDefined(); + expect(profile.loadDetailedCoverage).toBeDefined(); }); - controllerMock.createRunProfile.mock.results.find((r) => r.label === 'run'); - expect(WorkspaceRoot).toHaveBeenCalled(); }); }); @@ -197,24 +244,33 @@ describe('JestTestProvider', () => { }); }); }); + describe('can provide test coverage', () => { + it('use coverageProvider to manage coverage', () => { + new JestTestProvider(extExplorerContextMock); + expect(JestTestCoverageProvider).toHaveBeenCalledWith(extExplorerContextMock.sessionEvents); + }); + it('can load detailed coverage', async () => { + new JestTestProvider(extExplorerContextMock); + const coverageProfile = controllerMock.createRunProfile.mock.results.find( + (r) => r.value.kind === vscode.TestRunProfileKind.Coverage + )?.value; + const fileCoverage = { path: 'file' }; + await coverageProfile.loadDetailedCoverage({}, fileCoverage); + expect(mockCoverageProvider.loadDetailedCoverage).toHaveBeenCalledWith(fileCoverage); + }); + }); describe('upon dispose', () => { it('vscode.TestController will be disposed', () => { const testProvider = new JestTestProvider(extExplorerContextMock); testProvider.dispose(); expect(controllerMock.dispose).toHaveBeenCalled(); expect(workspaceRootMock.dispose).toHaveBeenCalled(); + expect(mockCoverageProvider.dispose).toHaveBeenCalled(); }); }); describe('supports explorer UI run and debug request', () => { let cancelToken; - const setupItemData = (context, items = [1, 2, 3]) => { - const itemDataList = items.map((n) => setupTestItemData(`item-${n}`, true, context)); - itemDataList.forEach((d) => { - d.context = { workspace: { name: 'whatever' } }; - d.getDebugInfo = jest.fn().mockReturnValueOnce({}); - }); - return itemDataList; - }; + beforeEach(() => { cancelToken = { onCancellationRequested: jest.fn(), isCancellationRequested: false }; }); @@ -445,7 +501,6 @@ describe('JestTestProvider', () => { const testProvider = new JestTestProvider(extExplorerContextMock); const itemDataList = setupItemData(workspaceRootMock.context); - // itemDataList.forEach((d, idx) => d.scheduleTest.mockReturnValueOnce(`pid-${idx}`)); const request: any = { include: itemDataList.map((d) => d.item), @@ -570,6 +625,25 @@ describe('JestTestProvider', () => { await p; expect(jestRun.end).toHaveBeenCalledTimes(1); }); + it('if request has exclude, will run test for the whole workplace except the exclude', async () => { + expect.hasAssertions(); + + const testProvider = new JestTestProvider(extExplorerContextMock); + + const request: any = { + exclude: [workspaceRootMock.item], + profile: { kind: vscode.TestRunProfileKind.Run }, + }; + + const p = testProvider.runTests(request, cancelToken); + + expect(JestTestRun).toHaveBeenCalledTimes(1); + const jestRun = mockedJestTestRun.mock.results[0].value; + expect(workspaceRootMock.scheduleTest).not.toHaveBeenCalled(); + + await p; + expect(jestRun.end).toHaveBeenCalledTimes(1); + }); it('will reject run request without profile', async () => { expect.hasAssertions(); @@ -582,6 +656,7 @@ describe('JestTestProvider', () => { }); }); }); + describe('supports test-explorer item-menu', () => { it('updates item-menu context', () => { new JestTestProvider(extExplorerContextMock); @@ -601,10 +676,37 @@ describe('JestTestProvider', () => { ); }); }); - it('supports runItemCommand', () => { - const provider = new JestTestProvider(extExplorerContextMock); - provider.runItemCommand(workspaceRootMock.item, ItemCommand.updateSnapshot); - expect(workspaceRootMock.runItemCommand).toHaveBeenCalled(); + describe('support direct invocation of runTests', () => { + it('use runTests after exiting defer mode', async () => { + expect.hasAssertions(); + + const testProvider = new JestTestProvider(extExplorerContextMock); + const itemDataList = setupItemData(workspaceRootMock.context); + + const requestFromSpy = jest.spyOn(workspaceRootMock.context, 'requestFrom'); + requestFromSpy.mockImplementation((r) => r); + const createTestRunSpy = jest.spyOn(workspaceRootMock.context, 'createTestRun'); + + const request: any = { + include: [itemDataList[0].item], + profile: { kind: vscode.TestRunProfileKind.Run }, + }; + await testProvider.runTests(request, undefined, true); + expect(requestFromSpy).toHaveBeenCalledWith(request); + expect(createTestRunSpy).toHaveBeenCalled(); + }); + }); + describe('runItemCommand', () => { + it('supports runItemCommand', () => { + const provider = new JestTestProvider(extExplorerContextMock); + provider.runItemCommand(workspaceRootMock.item, ItemCommand.updateSnapshot); + expect(workspaceRootMock.runItemCommand).toHaveBeenCalled(); + }); + it('if no itemData found, will not crash', () => { + const provider = new JestTestProvider(extExplorerContextMock); + provider.runItemCommand({ id: 'not-found' } as any, ItemCommand.updateSnapshot); + expect(workspaceRootMock.runItemCommand).not.toHaveBeenCalled(); + }); }); it('will exit defer mode upon any run request', async () => { expect.hasAssertions(); diff --git a/typings/vscode.d.ts b/typings/vscode.d.ts index 485dff493..357bd5ee9 100644 --- a/typings/vscode.d.ts +++ b/typings/vscode.d.ts @@ -136,7 +136,7 @@ declare module 'vscode' { /** * Save the underlying file. * - * @return A promise that will resolve to `true` when the file + * @returns A promise that will resolve to `true` when the file * has been saved. If the save failed, will return `false`. */ save(): Thenable; @@ -158,7 +158,7 @@ declare module 'vscode' { * document are not reflected. * * @param line A line number in [0, lineCount). - * @return A {@link TextLine line}. + * @returns A {@link TextLine line}. */ lineAt(line: number): TextLine; @@ -172,7 +172,7 @@ declare module 'vscode' { * @see {@link TextDocument.lineAt} * * @param position A position. - * @return A {@link TextLine line}. + * @returns A {@link TextLine line}. */ lineAt(position: Position): TextLine; @@ -182,7 +182,7 @@ declare module 'vscode' { * The position will be {@link TextDocument.validatePosition adjusted}. * * @param position A position. - * @return A valid zero-based offset. + * @returns A valid zero-based offset. */ offsetAt(position: Position): number; @@ -190,7 +190,7 @@ declare module 'vscode' { * Converts a zero-based offset to a position. * * @param offset A zero-based offset. - * @return A valid {@link Position}. + * @returns A valid {@link Position}. */ positionAt(offset: number): Position; @@ -199,14 +199,14 @@ declare module 'vscode' { * a range. The range will be {@link TextDocument.validateRange adjusted}. * * @param range Include only the text included by the range. - * @return The text inside the provided range or the entire text. + * @returns The text inside the provided range or the entire text. */ getText(range?: Range): string; /** * Get a word-range at the given position. By default words are defined by * common separators, like space, -, _, etc. In addition, per language custom - * [word definitions} can be defined. It + * [word definitions] can be defined. It * is also possible to provide a custom regular expression. * * * *Note 1:* A custom regular expression must not match the empty string and @@ -219,7 +219,7 @@ declare module 'vscode' { * * @param position A position. * @param regex Optional regular expression that describes what a word is. - * @return A range spanning a word, or `undefined`. + * @returns A range spanning a word, or `undefined`. */ getWordRangeAtPosition(position: Position, regex?: RegExp): Range | undefined; @@ -227,7 +227,7 @@ declare module 'vscode' { * Ensure a range is completely contained in this document. * * @param range A range. - * @return The given range or a new, adjusted range. + * @returns The given range or a new, adjusted range. */ validateRange(range: Range): Range; @@ -235,7 +235,7 @@ declare module 'vscode' { * Ensure a position is contained in the range of this document. * * @param position A position. - * @return The given position or a new, adjusted position. + * @returns The given position or a new, adjusted position. */ validatePosition(position: Position): Position; } @@ -270,7 +270,7 @@ declare module 'vscode' { * Check if this position is before `other`. * * @param other A position. - * @return `true` if position is on a smaller line + * @returns `true` if position is on a smaller line * or on the same line on a smaller character. */ isBefore(other: Position): boolean; @@ -279,7 +279,7 @@ declare module 'vscode' { * Check if this position is before or equal to `other`. * * @param other A position. - * @return `true` if position is on a smaller line + * @returns `true` if position is on a smaller line * or on the same line on a smaller or equal character. */ isBeforeOrEqual(other: Position): boolean; @@ -288,7 +288,7 @@ declare module 'vscode' { * Check if this position is after `other`. * * @param other A position. - * @return `true` if position is on a greater line + * @returns `true` if position is on a greater line * or on the same line on a greater character. */ isAfter(other: Position): boolean; @@ -297,7 +297,7 @@ declare module 'vscode' { * Check if this position is after or equal to `other`. * * @param other A position. - * @return `true` if position is on a greater line + * @returns `true` if position is on a greater line * or on the same line on a greater or equal character. */ isAfterOrEqual(other: Position): boolean; @@ -306,7 +306,7 @@ declare module 'vscode' { * Check if this position is equal to `other`. * * @param other A position. - * @return `true` if the line and character of the given position are equal to + * @returns `true` if the line and character of the given position are equal to * the line and character of this position. */ isEqual(other: Position): boolean; @@ -315,7 +315,7 @@ declare module 'vscode' { * Compare this to `other`. * * @param other A position. - * @return A number smaller than zero if this position is before the given position, + * @returns A number smaller than zero if this position is before the given position, * a number greater than zero if this position is after the given position, or zero when * this and the given position are equal. */ @@ -326,7 +326,7 @@ declare module 'vscode' { * * @param lineDelta Delta value for the line value, default is `0`. * @param characterDelta Delta value for the character value, default is `0`. - * @return A position which line and character is the sum of the current line and + * @returns A position which line and character is the sum of the current line and * character and the corresponding deltas. */ translate(lineDelta?: number, characterDelta?: number): Position; @@ -335,17 +335,26 @@ declare module 'vscode' { * Derived a new position relative to this position. * * @param change An object that describes a delta to this position. - * @return A position that reflects the given delta. Will return `this` position if the change + * @returns A position that reflects the given delta. Will return `this` position if the change * is not changing anything. */ - translate(change: { lineDelta?: number; characterDelta?: number }): Position; + translate(change: { + /** + * Delta value for the line value, default is `0`. + */ + lineDelta?: number; + /** + * Delta value for the character value, default is `0`. + */ + characterDelta?: number; + }): Position; /** * Create a new position derived from this position. * * @param line Value that should be used as line value, default is the {@link Position.line existing value} * @param character Value that should be used as character value, default is the {@link Position.character existing value} - * @return A position where line and character are replaced by the given values. + * @returns A position where line and character are replaced by the given values. */ with(line?: number, character?: number): Position; @@ -353,10 +362,19 @@ declare module 'vscode' { * Derived a new position from this position. * * @param change An object that describes a change to this position. - * @return A position that reflects the given change. Will return `this` position if the change + * @returns A position that reflects the given change. Will return `this` position if the change * is not changing anything. */ - with(change: { line?: number; character?: number }): Position; + with(change: { + /** + * New line value, defaults the line value of `this`. + */ + line?: number; + /** + * New character value, defaults the character value of `this`. + */ + character?: number; + }): Position; } /** @@ -413,7 +431,7 @@ declare module 'vscode' { * Check if a position or a range is contained in this range. * * @param positionOrRange A position or a range. - * @return `true` if the position or range is inside or equal + * @returns `true` if the position or range is inside or equal * to this range. */ contains(positionOrRange: Position | Range): boolean; @@ -422,7 +440,7 @@ declare module 'vscode' { * Check if `other` equals this range. * * @param other A range. - * @return `true` when start and end are {@link Position.isEqual equal} to + * @returns `true` when start and end are {@link Position.isEqual equal} to * start and end of this range. */ isEqual(other: Range): boolean; @@ -432,7 +450,7 @@ declare module 'vscode' { * if the ranges have no overlap. * * @param range A range. - * @return A range of the greater start and smaller end positions. Will + * @returns A range of the greater start and smaller end positions. Will * return undefined when there is no overlap. */ intersection(range: Range): Range | undefined; @@ -441,7 +459,7 @@ declare module 'vscode' { * Compute the union of `other` with this range. * * @param other A range. - * @return A range of smaller start position and the greater end position. + * @returns A range of smaller start position and the greater end position. */ union(other: Range): Range; @@ -450,7 +468,7 @@ declare module 'vscode' { * * @param start A position that should be used as start. The default value is the {@link Range.start current start}. * @param end A position that should be used as end. The default value is the {@link Range.end current end}. - * @return A range derived from this range with the given start and end position. + * @returns A range derived from this range with the given start and end position. * If start and end are not different `this` range will be returned. */ with(start?: Position, end?: Position): Range; @@ -459,10 +477,19 @@ declare module 'vscode' { * Derived a new range from this range. * * @param change An object that describes a change to this range. - * @return A range that reflects the given change. Will return `this` range if the change + * @returns A range that reflects the given change. Will return `this` range if the change * is not changing anything. */ - with(change: { start?: Position; end?: Position }): Range; + with(change: { + /** + * New start position, defaults to {@link Range.start current start} + */ + start?: Position; + /** + * New end position, defaults to {@link Range.end current end} + */ + end?: Position; + }): Range; } /** @@ -630,7 +657,11 @@ declare module 'vscode' { /** * Render the line numbers with values relative to the primary cursor location. */ - Relative = 2 + Relative = 2, + /** + * Render the line numbers on every 10th line number. + */ + Interval = 3, } /** @@ -641,13 +672,22 @@ declare module 'vscode' { /** * The size in spaces a tab takes. This is used for two purposes: * - the rendering width of a tab character; - * - the number of spaces to insert when {@link TextEditorOptions.insertSpaces insertSpaces} is true. + * - the number of spaces to insert when {@link TextEditorOptions.insertSpaces insertSpaces} is true + * and `indentSize` is set to `"tabSize"`. * * When getting a text editor's options, this property will always be a number (resolved). * When setting a text editor's options, this property is optional and it can be a number or `"auto"`. */ tabSize?: number | string; + /** + * The number of spaces to insert when {@link TextEditorOptions.insertSpaces insertSpaces} is true. + * + * When getting a text editor's options, this property will always be a number (resolved). + * When setting a text editor's options, this property is optional and it can be a number or `"tabSize"`. + */ + indentSize?: number | string; + /** * When pressing Tab insert {@link TextEditorOptions.tabSize n} spaces. * When getting a text editor's options, this property will always be a boolean (resolved). @@ -718,9 +758,21 @@ declare module 'vscode' { * The overview ruler supports three lanes. */ export enum OverviewRulerLane { + /** + * The left lane of the overview ruler. + */ Left = 1, + /** + * The center lane of the overview ruler. + */ Center = 2, + /** + * The right lane of the overview ruler. + */ Right = 4, + /** + * All lanes of the overview ruler. + */ Full = 7 } @@ -733,7 +785,7 @@ declare module 'vscode' { */ OpenOpen = 0, /** - * The decoration's range will not widen when edits occur at the start of end. + * The decoration's range will not widen when edits occur at the start or end. */ ClosedClosed = 1, /** @@ -752,10 +804,10 @@ declare module 'vscode' { export interface TextDocumentShowOptions { /** * An optional view column in which the {@link TextEditor editor} should be shown. - * The default is the {@link ViewColumn.Active active}, other values are adjusted to - * be `Min(column, columnCount + 1)`, the {@link ViewColumn.Active active}-column is - * not adjusted. Use {@linkcode ViewColumn.Beside} to open the - * editor to the side of the currently active one. + * The default is the {@link ViewColumn.Active active}. Columns that do not exist + * will be created as needed up to the maximum of {@linkcode ViewColumn.Nine}. + * Use {@linkcode ViewColumn.Beside} to open the editor to the side of the currently + * active one. */ viewColumn?: ViewColumn; @@ -814,10 +866,10 @@ declare module 'vscode' { export interface NotebookDocumentShowOptions { /** * An optional view column in which the {@link NotebookEditor notebook editor} should be shown. - * The default is the {@link ViewColumn.Active active}, other values are adjusted to - * be `Min(column, columnCount + 1)`, the {@link ViewColumn.Active active}-column is - * not adjusted. Use {@linkcode ViewColumn.Beside} to open the - * editor to the side of the currently active one. + * The default is the {@link ViewColumn.Active active}. Columns that do not exist + * will be created as needed up to the maximum of {@linkcode ViewColumn.Nine}. + * Use {@linkcode ViewColumn.Beside} to open the editor to the side of the currently + * active one. */ readonly viewColumn?: ViewColumn; @@ -840,14 +892,14 @@ declare module 'vscode' { } /** - * A reference to one of the workbench colors as defined in https://code.visualstudio.com/docs/getstarted/theme-color-reference. + * A reference to one of the workbench colors as defined in https://code.visualstudio.com/api/references/theme-color. * Using a theme color is preferred over a custom color as it gives theme authors and users the possibility to change the color. */ export class ThemeColor { /** * Creates a reference to a theme color. - * @param id of the color. The available colors are listed in https://code.visualstudio.com/docs/getstarted/theme-color-reference. + * @param id of the color. The available colors are listed in https://code.visualstudio.com/api/references/theme-color. */ constructor(id: string); } @@ -1020,6 +1072,10 @@ declare module 'vscode' { after?: ThemableDecorationAttachmentRenderOptions; } + /** + * Represents theme specific rendeirng styles for {@link ThemableDecorationRenderOptions.before before} and + * {@link ThemableDecorationRenderOptions.after after} the content of text decorations. + */ export interface ThemableDecorationAttachmentRenderOptions { /** * Defines a text content that is shown in the attachment. Either an icon or a text can be shown, but not both. @@ -1126,6 +1182,9 @@ declare module 'vscode' { renderOptions?: DecorationInstanceRenderOptions; } + /** + * Represents themable render options for decoration instances. + */ export interface ThemableDecorationInstanceRenderOptions { /** * Defines the rendering options of the attachment that is inserted before the decorated text. @@ -1138,6 +1197,9 @@ declare module 'vscode' { after?: ThemableDecorationAttachmentRenderOptions; } + /** + * Represents render options for decoration instances. See {@link DecorationOptions.renderOptions}. + */ export interface DecorationInstanceRenderOptions extends ThemableDecorationInstanceRenderOptions { /** * Overwrite options for light themes. @@ -1197,9 +1259,18 @@ declare module 'vscode' { * * @param callback A function which can create edits using an {@link TextEditorEdit edit-builder}. * @param options The undo/redo behavior around this edit. By default, undo stops will be created before and after this edit. - * @return A promise that resolves with a value indicating if the edits could be applied. + * @returns A promise that resolves with a value indicating if the edits could be applied. */ - edit(callback: (editBuilder: TextEditorEdit) => void, options?: { readonly undoStopBefore: boolean; readonly undoStopAfter: boolean }): Thenable; + edit(callback: (editBuilder: TextEditorEdit) => void, options?: { + /** + * Add undo stop before making the edits. + */ + readonly undoStopBefore: boolean; + /** + * Add undo stop after making the edits. + */ + readonly undoStopAfter: boolean; + }): Thenable; /** * Insert a {@link SnippetString snippet} and put the editor into snippet mode. "Snippet mode" @@ -1209,10 +1280,19 @@ declare module 'vscode' { * @param snippet The snippet to insert in this edit. * @param location Position or range at which to insert the snippet, defaults to the current editor selection or selections. * @param options The undo/redo behavior around this edit. By default, undo stops will be created before and after this edit. - * @return A promise that resolves with a value indicating if the snippet could be inserted. Note that the promise does not signal + * @returns A promise that resolves with a value indicating if the snippet could be inserted. Note that the promise does not signal * that the snippet is completely filled-in or accepted. */ - insertSnippet(snippet: SnippetString, location?: Position | Range | readonly Position[] | readonly Range[], options?: { readonly undoStopBefore: boolean; readonly undoStopAfter: boolean }): Thenable; + insertSnippet(snippet: SnippetString, location?: Position | Range | readonly Position[] | readonly Range[], options?: { + /** + * Add undo stop before making the edits. + */ + readonly undoStopBefore: boolean; + /** + * Add undo stop after making the edits. + */ + readonly undoStopAfter: boolean; + }): Thenable; /** * Adds a set of decorations to the text editor. If a set of decorations already exists with @@ -1276,7 +1356,7 @@ declare module 'vscode' { export interface TextEditorEdit { /** * Replace a certain text region with a new value. - * You can use \r\n or \n in `value` and they will be normalized to the current {@link TextDocument document}. + * You can use `\r\n` or `\n` in `value` and they will be normalized to the current {@link TextDocument document}. * * @param location The range this operation should remove. * @param value The new text this operation should insert after removing `location`. @@ -1285,7 +1365,7 @@ declare module 'vscode' { /** * Insert text at a location. - * You can use \r\n or \n in `value` and they will be normalized to the current {@link TextDocument document}. + * You can use `\r\n` or `\n` in `value` and they will be normalized to the current {@link TextDocument document}. * Although the equivalent text edit can be made with {@link TextEditorEdit.replace replace}, `insert` will produce a different resulting selection (it will get moved). * * @param location The position where the new text should be inserted. @@ -1325,7 +1405,7 @@ declare module 'vscode' { * @see {@link Uri.toString} * @param value The string value of an Uri. * @param strict Throw an error when `value` is empty or when no `scheme` can be parsed. - * @return A new Uri instance. + * @returns A new Uri instance. */ static parse(value: string, strict?: boolean): Uri; @@ -1350,7 +1430,7 @@ declare module 'vscode' { * ``` * * @param path A file system or UNC path. - * @return A new Uri instance. + * @returns A new Uri instance. */ static file(path: string): Uri; @@ -1381,9 +1461,30 @@ declare module 'vscode' { * * @see {@link Uri.toString} * @param components The component parts of an Uri. - * @return A new Uri instance. + * @returns A new Uri instance. */ - static from(components: { readonly scheme: string; readonly authority?: string; readonly path?: string; readonly query?: string; readonly fragment?: string }): Uri; + static from(components: { + /** + * The scheme of the uri + */ + readonly scheme: string; + /** + * The authority of the uri + */ + readonly authority?: string; + /** + * The path of the uri + */ + readonly path?: string; + /** + * The query string of the uri + */ + readonly query?: string; + /** + * The fragment identifier of the uri + */ + readonly fragment?: string; + }): Uri; /** * Use the `file` and `parse` factory functions to create new `Uri` objects. @@ -1433,7 +1534,7 @@ declare module 'vscode' { * ```ts * const u = URI.parse('file://server/c$/folder/file.txt') * u.authority === 'server' - * u.path === '/shares/c$/file.txt' + * u.path === '/c$/folder/file.txt' * u.fsPath === '\\server\c$\folder\file.txt' * ``` */ @@ -1450,10 +1551,31 @@ declare module 'vscode' { * * @param change An object that describes a change to this Uri. To unset components use `null` or * the empty string. - * @return A new Uri that reflects the given change. Will return `this` Uri if the change + * @returns A new Uri that reflects the given change. Will return `this` Uri if the change * is not changing anything. */ - with(change: { scheme?: string; authority?: string; path?: string; query?: string; fragment?: string }): Uri; + with(change: { + /** + * The new scheme, defaults to this Uri's scheme. + */ + scheme?: string; + /** + * The new authority, defaults to this Uri's authority. + */ + authority?: string; + /** + * The new path, defaults to this Uri's path. + */ + path?: string; + /** + * The new query, defaults to this Uri's query. + */ + query?: string; + /** + * The new fragment, defaults to this Uri's fragment. + */ + fragment?: string; + }): Uri; /** * Returns a string representation of this Uri. The representation and normalization @@ -1477,7 +1599,7 @@ declare module 'vscode' { /** * Returns a JSON representation of this Uri. * - * @return An object. + * @returns An object. */ toJSON(): any; } @@ -1551,10 +1673,15 @@ declare module 'vscode' { * * @param disposableLikes Objects that have at least a `dispose`-function member. Note that asynchronous * dispose-functions aren't awaited. - * @return Returns a new disposable which, upon dispose, will + * @returns Returns a new disposable which, upon dispose, will * dispose all provided disposables. */ - static from(...disposableLikes: { dispose: () => any }[]): Disposable; + static from(...disposableLikes: { + /** + * Function to clean up resources. + */ + dispose: () => any; + }[]): Disposable; /** * Creates a new disposable that calls the provided function @@ -1590,7 +1717,7 @@ declare module 'vscode' { * @param listener The listener function will be called when the event happens. * @param thisArgs The `this`-argument which will be used when calling the event listener. * @param disposables An array to which a {@link Disposable} will be added. - * @return A disposable which unsubscribes the event listener. + * @returns A disposable which unsubscribes the event listener. */ (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]): Disposable; } @@ -1608,7 +1735,6 @@ declare module 'vscode' { /** * The event listeners can subscribe to. */ - // eslint-disable-next-line vscode-dts-event-naming event: Event; /** @@ -1638,34 +1764,34 @@ declare module 'vscode' { * true if this file system watcher has been created such that * it ignores creation file system events. */ - ignoreCreateEvents: boolean; + readonly ignoreCreateEvents: boolean; /** * true if this file system watcher has been created such that * it ignores change file system events. */ - ignoreChangeEvents: boolean; + readonly ignoreChangeEvents: boolean; /** * true if this file system watcher has been created such that * it ignores delete file system events. */ - ignoreDeleteEvents: boolean; + readonly ignoreDeleteEvents: boolean; /** * An event which fires on file/folder creation. */ - onDidCreate: Event; + readonly onDidCreate: Event; /** * An event which fires on file/folder change. */ - onDidChange: Event; + readonly onDidChange: Event; /** * An event which fires on file/folder deletion. */ - onDidDelete: Event; + readonly onDidDelete: Event; } /** @@ -1696,7 +1822,7 @@ declare module 'vscode' { * * @param uri An uri which scheme matches the scheme this provider was {@link workspace.registerTextDocumentContentProvider registered} for. * @param token A cancellation token. - * @return A string or a thenable that resolves to such. + * @returns A string or a thenable that resolves to such. */ provideTextDocumentContent(uri: Uri, token: CancellationToken): ProviderResult; } @@ -1734,6 +1860,20 @@ declare module 'vscode' { */ kind?: QuickPickItemKind; + /** + * The icon path or {@link ThemeIcon} for the QuickPickItem. + */ + iconPath?: Uri | { + /** + * The icon path for the light theme. + */ + light: Uri; + /** + * The icon path for the dark theme. + */ + dark: Uri; + } | ThemeIcon; + /** * A human-readable string which is rendered less prominent in the same line. Supports rendering of * {@link ThemeIcon theme icons} via the `$()`-syntax. @@ -1752,8 +1892,9 @@ declare module 'vscode' { /** * Optional flag indicating if this item is picked initially. This is only honored when using - * the {@link window.showQuickPick()} API. To do the same thing with the {@link window.createQuickPick()} API, - * simply set the {@link QuickPick.selectedItems} to the items you want picked initially. + * the {@link window.showQuickPick showQuickPick()} API. To do the same thing with + * the {@link window.createQuickPick createQuickPick()} API, simply set the {@link QuickPick.selectedItems} + * to the items you want picked initially. * (*Note:* This is only honored when the picker allows multiple selections.) * * @see {@link QuickPickOptions.canPickMany} @@ -1772,8 +1913,8 @@ declare module 'vscode' { /** * Optional buttons that will be rendered on this particular item. These buttons will trigger * an {@link QuickPickItemButtonEvent} when clicked. Buttons are only rendered when using a quickpick - * created by the {@link window.createQuickPick()} API. Buttons are not rendered when using - * the {@link window.showQuickPick()} API. + * created by the {@link window.createQuickPick createQuickPick()} API. Buttons are not rendered when using + * the {@link window.showQuickPick showQuickPick()} API. * * Note: this property is ignored when {@link QuickPickItem.kind kind} is set to {@link QuickPickItemKind.Separator} */ @@ -1875,10 +2016,10 @@ declare module 'vscode' { /** * A set of file filters that are used by the dialog. Each entry is a human-readable label, - * like "TypeScript", and an array of extensions, e.g. + * like "TypeScript", and an array of extensions, for example: * ```ts * { - * 'Images': ['png', 'jpg'] + * 'Images': ['png', 'jpg'], * 'TypeScript': ['ts', 'tsx'] * } * ``` @@ -1910,10 +2051,10 @@ declare module 'vscode' { /** * A set of file filters that are used by the dialog. Each entry is a human-readable label, - * like "TypeScript", and an array of extensions, e.g. + * like "TypeScript", and an array of extensions, for example: * ```ts * { - * 'Images': ['png', 'jpg'] + * 'Images': ['png', 'jpg'], * 'TypeScript': ['ts', 'tsx'] * } * ``` @@ -1978,9 +2119,21 @@ declare module 'vscode' { /** * Impacts the behavior and appearance of the validation message. */ + /** + * The severity level for input box validation. + */ export enum InputBoxValidationSeverity { + /** + * Informational severity level. + */ Info = 1, + /** + * Warning severity level. + */ Warning = 2, + /** + * Error severity level. + */ Error = 3 } @@ -2019,7 +2172,7 @@ declare module 'vscode' { /** * Selection of the pre-filled {@linkcode InputBoxOptions.value value}. Defined as tuple of two number where the * first is the inclusive start index and the second the exclusive end index. When `undefined` the whole - * word will be selected, when empty (start equals end) only the cursor will be set, + * pre-filled value will be selected, when empty (start equals end) only the cursor will be set, * otherwise the defined range will be selected. */ valueSelection?: [number, number]; @@ -2050,7 +2203,7 @@ declare module 'vscode' { * to the user. * * @param value The current value of the input box. - * @return Either a human-readable string which is presented as an error message or an {@link InputBoxValidationMessage} + * @returns Either a human-readable string which is presented as an error message or an {@link InputBoxValidationMessage} * which can provide a specific message severity. Return `undefined`, `null`, or the empty string when 'value' is valid. */ validateInput?(value: string): string | InputBoxValidationMessage | undefined | null | @@ -2066,7 +2219,9 @@ declare module 'vscode' { export class RelativePattern { /** - * A base file path to which this pattern will be matched against relatively. + * A base file path to which this pattern will be matched against relatively. The + * file path must be absolute, should not have any trailing path separators and + * not include any relative segments (`.` or `..`). */ baseUri: Uri; @@ -2276,6 +2431,18 @@ declare module 'vscode' { */ static readonly RefactorInline: CodeActionKind; + /** + * Base kind for refactoring move actions: `refactor.move` + * + * Example move actions: + * + * - Move a function to a new file + * - Move a property between classes + * - Move method to base class + * - ... + */ + static readonly RefactorMove: CodeActionKind; + /** * Base kind for refactoring rewrite actions: `refactor.rewrite` * @@ -2285,7 +2452,6 @@ declare module 'vscode' { * - Add or remove parameter * - Encapsulate field * - Make method static - * - Move method to base class * - ... */ static readonly RefactorRewrite: CodeActionKind; @@ -2312,6 +2478,29 @@ declare module 'vscode' { */ static readonly SourceFixAll: CodeActionKind; + /** + * Base kind for all code actions applying to the enitre notebook's scope. CodeActionKinds using + * this should always begin with `notebook.` + * + * This requires that new CodeActions be created for it and contributed via extensions. + * Pre-existing kinds can not just have the new `notebook.` prefix added to them, as the functionality + * is unique to the full-notebook scope. + * + * Notebook CodeActionKinds can be initialized as either of the following (both resulting in `notebook.source.xyz`): + * - `const newKind = CodeActionKind.Notebook.append(CodeActionKind.Source.append('xyz').value)` + * - `const newKind = CodeActionKind.Notebook.append('source.xyz')` + * + * Example Kinds/Actions: + * - `notebook.source.organizeImports` (might move all imports to a new top cell) + * - `notebook.source.normalizeVariableNames` (might rename all variables to a standardized casing format) + */ + static readonly Notebook: CodeActionKind; + + /** + * Private constructor, use statix `CodeActionKind.XYZ` to derive from an existing code action kind. + * + * @param value The value of the kind, such as `refactor.extract.function`. + */ private constructor(value: string); /** @@ -2470,22 +2659,35 @@ declare module 'vscode' { } /** - * The code action interface defines the contract between extensions and - * the [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature. + * Provides contextual actions for code. Code actions typically either fix problems or beautify/refactor code. * - * A code action can be any command that is {@link commands.getCommands known} to the system. + * Code actions are surfaced to users in a few different ways: + * + * - The [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature, which shows + * a list of code actions at the current cursor position. The lightbulb's list of actions includes both quick fixes + * and refactorings. + * - As commands that users can run, such as `Refactor`. Users can run these from the command palette or with keybindings. + * - As source actions, such `Organize Imports`. + * - {@link CodeActionKind.QuickFix Quick fixes} are shown in the problems view. + * - Change applied on save by the `editor.codeActionsOnSave` setting. */ export interface CodeActionProvider { /** - * Provide commands for the given document and range. + * Get code actions for a given range in a document. + * + * Only return code actions that are relevant to user for the requested range. Also keep in mind how the + * returned code actions will appear in the UI. The lightbulb widget and `Refactor` commands for instance show + * returned code actions as a list, so do not return a large number of code actions that will overwhelm the user. * * @param document The document in which the command was invoked. - * @param range The selector or range for which the command was invoked. This will always be a selection if - * there is a currently active editor. - * @param context Context carrying additional information. + * @param range The selector or range for which the command was invoked. This will always be a + * {@link Selection selection} if the actions are being requested in the currently active editor. + * @param context Provides additional information about what code actions are being requested. You can use this + * to see what specific type of code actions are being requested by the editor in order to return more relevant + * actions and avoid returning irrelevant code actions that the editor will discard. * @param token A cancellation token. * - * @return An array of code actions, such as quick fixes or refactorings. The lack of a result can be signaled + * @returns An array of code actions, such as quick fixes or refactorings. The lack of a result can be signaled * by returning `undefined`, `null`, or an empty array. * * We also support returning `Command` for legacy reasons, however all new extensions should return @@ -2504,7 +2706,7 @@ declare module 'vscode' { * * @param codeAction A code action. * @param token A cancellation token. - * @return The resolved code action or a thenable that resolves to such. It is OK to return the given + * @returns The resolved code action or a thenable that resolves to such. It is OK to return the given * `item`. When no result is returned, the given `item` will be used. */ resolveCodeAction?(codeAction: T, token: CancellationToken): ProviderResult; @@ -2613,7 +2815,7 @@ declare module 'vscode' { * * @param document The document in which the command was invoked. * @param token A cancellation token. - * @return An array of code lenses or a thenable that resolves to such. The lack of a result can be + * @returns An array of code lenses or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined`, `null`, or an empty array. */ provideCodeLenses(document: TextDocument, token: CancellationToken): ProviderResult; @@ -2624,7 +2826,7 @@ declare module 'vscode' { * * @param codeLens Code lens that must be resolved. * @param token A cancellation token. - * @return The given, resolved code lens or thenable that resolves to such. + * @returns The given, resolved code lens or thenable that resolves to such. */ resolveCodeLens?(codeLens: T, token: CancellationToken): ProviderResult; } @@ -2657,7 +2859,7 @@ declare module 'vscode' { * @param document The document in which the command was invoked. * @param position The position at which the command was invoked. * @param token A cancellation token. - * @return A definition or a thenable that resolves to such. The lack of a result can be + * @returns A definition or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideDefinition(document: TextDocument, position: Position, token: CancellationToken): ProviderResult; @@ -2675,7 +2877,7 @@ declare module 'vscode' { * @param document The document in which the command was invoked. * @param position The position at which the command was invoked. * @param token A cancellation token. - * @return A definition or a thenable that resolves to such. The lack of a result can be + * @returns A definition or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideImplementation(document: TextDocument, position: Position, token: CancellationToken): ProviderResult; @@ -2693,7 +2895,7 @@ declare module 'vscode' { * @param document The document in which the command was invoked. * @param position The position at which the command was invoked. * @param token A cancellation token. - * @return A definition or a thenable that resolves to such. The lack of a result can be + * @returns A definition or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideTypeDefinition(document: TextDocument, position: Position, token: CancellationToken): ProviderResult; @@ -2717,7 +2919,7 @@ declare module 'vscode' { * @param document The document in which the command was invoked. * @param position The position at which the command was invoked. * @param token A cancellation token. - * @return A declaration or a thenable that resolves to such. The lack of a result can be + * @returns A declaration or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideDeclaration(document: TextDocument, position: Position, token: CancellationToken): ProviderResult; @@ -2741,8 +2943,15 @@ declare module 'vscode' { /** * Indicates that this markdown string is from a trusted source. Only *trusted* * markdown supports links that execute commands, e.g. `[Run it](command:myCommandId)`. + * + * Defaults to `false` (commands are disabled). */ - isTrusted?: boolean; + isTrusted?: boolean | { + /** + * A set of commend ids that are allowed to be executed by this markdown string. + */ + readonly enabledCommands: readonly string[]; + }; /** * Indicates that this markdown string can contain {@link ThemeIcon ThemeIcons}, e.g. `$(zap)`. @@ -2817,7 +3026,18 @@ declare module 'vscode' { * * @deprecated This type is deprecated, please use {@linkcode MarkdownString} instead. */ - export type MarkedString = string | { language: string; value: string }; + export type MarkedString = string | { + /** + * The language of a markdown code block + * @deprecated please use {@linkcode MarkdownString} instead + */ + language: string; + /** + * The code snippet of a markdown code block. + * @deprecated please use {@linkcode MarkdownString} instead + */ + value: string; + }; /** * A hover represents additional information for a symbol or word. Hovers are @@ -2860,7 +3080,7 @@ declare module 'vscode' { * @param document The document in which the command was invoked. * @param position The position at which the command was invoked. * @param token A cancellation token. - * @return A hover or a thenable that resolves to such. The lack of a result can be + * @returns A hover or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideHover(document: TextDocument, position: Position, token: CancellationToken): ProviderResult; @@ -2909,7 +3129,7 @@ declare module 'vscode' { * @param document The document for which the debug hover is about to appear. * @param position The line and character position in the document where the debug hover is about to appear. * @param token A cancellation token. - * @return An EvaluatableExpression or a thenable that resolves to such. The lack of a result can be + * @returns An EvaluatableExpression or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideEvaluatableExpression(document: TextDocument, position: Position, token: CancellationToken): ProviderResult; @@ -3037,7 +3257,7 @@ declare module 'vscode' { * @param viewPort The visible document range for which inline values should be computed. * @param context A bag containing contextual information like the current location. * @param token A cancellation token. - * @return An array of InlineValueDescriptors or a thenable that resolves to such. The lack of a result can be + * @returns An array of InlineValueDescriptors or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideInlineValues(document: TextDocument, viewPort: Range, context: InlineValueContext, token: CancellationToken): ProviderResult; @@ -3103,7 +3323,7 @@ declare module 'vscode' { * @param document The document in which the command was invoked. * @param position The position at which the command was invoked. * @param token A cancellation token. - * @return An array of document highlights or a thenable that resolves to such. The lack of a result can be + * @returns An array of document highlights or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined`, `null`, or an empty array. */ provideDocumentHighlights(document: TextDocument, position: Position, token: CancellationToken): ProviderResult; @@ -3113,31 +3333,109 @@ declare module 'vscode' { * A symbol kind. */ export enum SymbolKind { + /** + * The `File` symbol kind. + */ File = 0, + /** + * The `Module` symbol kind. + */ Module = 1, + /** + * The `Namespace` symbol kind. + */ Namespace = 2, + /** + * The `Package` symbol kind. + */ Package = 3, + /** + * The `Class` symbol kind. + */ Class = 4, + /** + * The `Method` symbol kind. + */ Method = 5, + /** + * The `Property` symbol kind. + */ Property = 6, + /** + * The `Field` symbol kind. + */ Field = 7, + /** + * The `Constructor` symbol kind. + */ Constructor = 8, + /** + * The `Enum` symbol kind. + */ Enum = 9, + /** + * The `Interface` symbol kind. + */ Interface = 10, + /** + * The `Function` symbol kind. + */ Function = 11, + /** + * The `Variable` symbol kind. + */ Variable = 12, + /** + * The `Constant` symbol kind. + */ Constant = 13, + /** + * The `String` symbol kind. + */ String = 14, + /** + * The `Number` symbol kind. + */ Number = 15, + /** + * The `Boolean` symbol kind. + */ Boolean = 16, + /** + * The `Array` symbol kind. + */ Array = 17, + /** + * The `Object` symbol kind. + */ Object = 18, + /** + * The `Key` symbol kind. + */ Key = 19, + /** + * The `Null` symbol kind. + */ Null = 20, + /** + * The `EnumMember` symbol kind. + */ EnumMember = 21, + /** + * The `Struct` symbol kind. + */ Struct = 22, + /** + * The `Event` symbol kind. + */ Event = 23, + /** + * The `Operator` symbol kind. + */ Operator = 24, + /** + * The `TypeParameter` symbol kind. + */ TypeParameter = 25 } @@ -3273,7 +3571,7 @@ declare module 'vscode' { * * @param document The document in which the command was invoked. * @param token A cancellation token. - * @return An array of document highlights or a thenable that resolves to such. The lack of a result can be + * @returns An array of document highlights or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined`, `null`, or an empty array. */ provideDocumentSymbols(document: TextDocument, token: CancellationToken): ProviderResult; @@ -3309,7 +3607,7 @@ declare module 'vscode' { * * @param query A query string, can be the empty string in which case all symbols should be returned. * @param token A cancellation token. - * @return An array of document highlights or a thenable that resolves to such. The lack of a result can be + * @returns An array of document highlights or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined`, `null`, or an empty array. */ provideWorkspaceSymbols(query: string, token: CancellationToken): ProviderResult; @@ -3323,7 +3621,7 @@ declare module 'vscode' { * @param symbol The symbol that is to be resolved. Guaranteed to be an instance of an object returned from an * earlier call to `provideWorkspaceSymbols`. * @param token A cancellation token. - * @return The resolved symbol or a thenable that resolves to that. When no result is returned, + * @returns The resolved symbol or a thenable that resolves to that. When no result is returned, * the given `symbol` is used. */ resolveWorkspaceSymbol?(symbol: T, token: CancellationToken): ProviderResult; @@ -3354,7 +3652,7 @@ declare module 'vscode' { * @param position The position at which the command was invoked. * @param token A cancellation token. * - * @return An array of locations or a thenable that resolves to such. The lack of a result can be + * @returns An array of locations or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined`, `null`, or an empty array. */ provideReferences(document: TextDocument, position: Position, context: ReferenceContext, token: CancellationToken): ProviderResult; @@ -3371,7 +3669,7 @@ declare module 'vscode' { * * @param range A range. * @param newText A string. - * @return A new text edit object. + * @returns A new text edit object. */ static replace(range: Range, newText: string): TextEdit; @@ -3380,7 +3678,7 @@ declare module 'vscode' { * * @param position A position, will become an empty range. * @param newText A string. - * @return A new text edit object. + * @returns A new text edit object. */ static insert(position: Position, newText: string): TextEdit; @@ -3388,7 +3686,7 @@ declare module 'vscode' { * Utility to create a delete edit. * * @param range A range. - * @return A new text edit object. + * @returns A new text edit object. */ static delete(range: Range): TextEdit; @@ -3396,7 +3694,7 @@ declare module 'vscode' { * Utility to create an eol-edit. * * @param eol An eol-sequence - * @return A new text edit object. + * @returns A new text edit object. */ static setEndOfLine(eol: EndOfLine): TextEdit; @@ -3427,6 +3725,126 @@ declare module 'vscode' { constructor(range: Range, newText: string); } + /** + * A snippet edit represents an interactive edit that is performed by + * the editor. + * + * *Note* that a snippet edit can always be performed as a normal {@link TextEdit text edit}. + * This will happen when no matching editor is open or when a {@link WorkspaceEdit workspace edit} + * contains snippet edits for multiple files. In that case only those that match the active editor + * will be performed as snippet edits and the others as normal text edits. + */ + export class SnippetTextEdit { + + /** + * Utility to create a replace snippet edit. + * + * @param range A range. + * @param snippet A snippet string. + * @returns A new snippet edit object. + */ + static replace(range: Range, snippet: SnippetString): SnippetTextEdit; + + /** + * Utility to create an insert snippet edit. + * + * @param position A position, will become an empty range. + * @param snippet A snippet string. + * @returns A new snippet edit object. + */ + static insert(position: Position, snippet: SnippetString): SnippetTextEdit; + + /** + * The range this edit applies to. + */ + range: Range; + + /** + * The {@link SnippetString snippet} this edit will perform. + */ + snippet: SnippetString; + + /** + * Create a new snippet edit. + * + * @param range A range. + * @param snippet A snippet string. + */ + constructor(range: Range, snippet: SnippetString); + } + + /** + * A notebook edit represents edits that should be applied to the contents of a notebook. + */ + export class NotebookEdit { + + /** + * Utility to create a edit that replaces cells in a notebook. + * + * @param range The range of cells to replace + * @param newCells The new notebook cells. + */ + static replaceCells(range: NotebookRange, newCells: NotebookCellData[]): NotebookEdit; + + /** + * Utility to create an edit that replaces cells in a notebook. + * + * @param index The index to insert cells at. + * @param newCells The new notebook cells. + */ + static insertCells(index: number, newCells: NotebookCellData[]): NotebookEdit; + + /** + * Utility to create an edit that deletes cells in a notebook. + * + * @param range The range of cells to delete. + */ + static deleteCells(range: NotebookRange): NotebookEdit; + + /** + * Utility to create an edit that update a cell's metadata. + * + * @param index The index of the cell to update. + * @param newCellMetadata The new metadata for the cell. + */ + static updateCellMetadata(index: number, newCellMetadata: { [key: string]: any }): NotebookEdit; + + /** + * Utility to create an edit that updates the notebook's metadata. + * + * @param newNotebookMetadata The new metadata for the notebook. + */ + static updateNotebookMetadata(newNotebookMetadata: { [key: string]: any }): NotebookEdit; + + /** + * Range of the cells being edited. May be empty. + */ + range: NotebookRange; + + /** + * New cells being inserted. May be empty. + */ + newCells: NotebookCellData[]; + + /** + * Optional new metadata for the cells. + */ + newCellMetadata?: { [key: string]: any }; + + /** + * Optional new metadata for the notebook. + */ + newNotebookMetadata?: { [key: string]: any }; + + /** + * Create a new notebook edit. + * + * @param range A notebook range. + * @param newCells An array of new cell data. + */ + constructor(range: NotebookRange, newCells: NotebookCellData[]); + } + /** * Additional data for entries of a workspace edit. Supports to label entries and marks entries * as needing confirmation by the user. The editor groups edits with equal labels into tree nodes, @@ -3452,7 +3870,26 @@ declare module 'vscode' { /** * The icon path or {@link ThemeIcon} for the edit. */ - iconPath?: Uri | { light: Uri; dark: Uri } | ThemeIcon; + iconPath?: Uri | { + /** + * The icon path for the light theme. + */ + light: Uri; + /** + * The icon path for the dark theme. + */ + dark: Uri; + } | ThemeIcon; + } + + /** + * Additional data about a workspace edit. + */ + export interface WorkspaceEditMetadata { + /** + * Signal to the editor that this edit is a refactoring. + */ + isRefactoring?: boolean; } /** @@ -3501,61 +3938,120 @@ declare module 'vscode' { * Check if a text edit for a resource exists. * * @param uri A resource identifier. - * @return `true` if the given resource will be touched by this edit. + * @returns `true` if the given resource will be touched by this edit. */ has(uri: Uri): boolean; /** - * Set (and replace) text edits for a resource. + * Set (and replace) text edits or snippet edits for a resource. * * @param uri A resource identifier. - * @param edits An array of text edits. + * @param edits An array of edits. */ - set(uri: Uri, edits: TextEdit[]): void; + set(uri: Uri, edits: ReadonlyArray): void; /** - * Get the text edits for a resource. + * Set (and replace) text edits or snippet edits with metadata for a resource. * * @param uri A resource identifier. - * @return An array of text edits. + * @param edits An array of edits. */ - get(uri: Uri): TextEdit[]; + set(uri: Uri, edits: ReadonlyArray<[TextEdit | SnippetTextEdit, WorkspaceEditEntryMetadata | undefined]>): void; /** - * Create a regular file. + * Set (and replace) notebook edits for a resource. * - * @param uri Uri of the new file.. - * @param options Defines if an existing file should be overwritten or be - * ignored. When overwrite and ignoreIfExists are both set overwrite wins. - * When both are unset and when the file already exists then the edit cannot - * be applied successfully. - * @param metadata Optional metadata for the entry. + * @param uri A resource identifier. + * @param edits An array of edits. */ - createFile(uri: Uri, options?: { overwrite?: boolean; ignoreIfExists?: boolean }, metadata?: WorkspaceEditEntryMetadata): void; + set(uri: Uri, edits: readonly NotebookEdit[]): void; /** - * Delete a file or folder. + * Set (and replace) notebook edits with metadata for a resource. * - * @param uri The uri of the file that is to be deleted. - * @param metadata Optional metadata for the entry. + * @param uri A resource identifier. + * @param edits An array of edits. */ - deleteFile(uri: Uri, options?: { recursive?: boolean; ignoreIfNotExists?: boolean }, metadata?: WorkspaceEditEntryMetadata): void; + set(uri: Uri, edits: ReadonlyArray<[NotebookEdit, WorkspaceEditEntryMetadata | undefined]>): void; /** - * Rename a file or folder. + * Get the text edits for a resource. * - * @param oldUri The existing file. - * @param newUri The new location. - * @param options Defines if existing files should be overwritten or be - * ignored. When overwrite and ignoreIfExists are both set overwrite wins. + * @param uri A resource identifier. + * @returns An array of text edits. + */ + get(uri: Uri): TextEdit[]; + + /** + * Create a regular file. + * + * @param uri Uri of the new file. + * @param options Defines if an existing file should be overwritten or be + * ignored. When `overwrite` and `ignoreIfExists` are both set `overwrite` wins. + * When both are unset and when the file already exists then the edit cannot + * be applied successfully. The `content`-property allows to set the initial contents + * the file is being created with. + * @param metadata Optional metadata for the entry. + */ + createFile(uri: Uri, options?: { + /** + * Overwrite existing file. Overwrite wins over `ignoreIfExists` + */ + readonly overwrite?: boolean; + /** + * Do nothing if a file with `uri` exists already. + */ + readonly ignoreIfExists?: boolean; + /** + * The initial contents of the new file. + * + * If creating a file from a {@link DocumentDropEditProvider drop operation}, you can + * pass in a {@link DataTransferFile} to improve performance by avoiding extra data copying. + */ + readonly contents?: Uint8Array | DataTransferFile; + }, metadata?: WorkspaceEditEntryMetadata): void; + + /** + * Delete a file or folder. + * + * @param uri The uri of the file that is to be deleted. + * @param metadata Optional metadata for the entry. + */ + deleteFile(uri: Uri, options?: { + /** + * Delete the content recursively if a folder is denoted. + */ + readonly recursive?: boolean; + /** + * Do nothing if a file with `uri` exists already. + */ + readonly ignoreIfNotExists?: boolean; + }, metadata?: WorkspaceEditEntryMetadata): void; + + /** + * Rename a file or folder. + * + * @param oldUri The existing file. + * @param newUri The new location. + * @param options Defines if existing files should be overwritten or be + * ignored. When overwrite and ignoreIfExists are both set overwrite wins. * @param metadata Optional metadata for the entry. */ - renameFile(oldUri: Uri, newUri: Uri, options?: { overwrite?: boolean; ignoreIfExists?: boolean }, metadata?: WorkspaceEditEntryMetadata): void; + renameFile(oldUri: Uri, newUri: Uri, options?: { + /** + * Overwrite existing file. Overwrite wins over `ignoreIfExists` + */ + readonly overwrite?: boolean; + /** + * Do nothing if a file with `uri` exists already. + */ + readonly ignoreIfExists?: boolean; + }, metadata?: WorkspaceEditEntryMetadata): void; /** * Get all text edits grouped by resource. * - * @return A shallow copy of `[Uri, TextEdit[]]`-tuples. + * @returns A shallow copy of `[Uri, TextEdit[]]`-tuples. */ entries(): [Uri, TextEdit[]][]; } @@ -3568,7 +4064,7 @@ declare module 'vscode' { * and `${3:foo}`. `$0` defines the final tab stop, it defaults to * the end of the snippet. Variables are defined with `$name` and * `${name:default value}`. Also see - * [the full snippet syntax](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_creating-your-own-snippets). + * [the full snippet syntax](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_create-your-own-snippets). */ export class SnippetString { @@ -3577,6 +4073,11 @@ declare module 'vscode' { */ value: string; + /** + * Create a new snippet string. + * + * @param value A snippet string. + */ constructor(value?: string); /** @@ -3584,7 +4085,7 @@ declare module 'vscode' { * the {@linkcode SnippetString.value value} of this snippet string. * * @param string A value to append 'as given'. The string will be escaped. - * @return This snippet string. + * @returns This snippet string. */ appendText(string: string): SnippetString; @@ -3594,7 +4095,7 @@ declare module 'vscode' { * * @param number The number of this tabstop, defaults to an auto-increment * value starting at 1. - * @return This snippet string. + * @returns This snippet string. */ appendTabstop(number?: number): SnippetString; @@ -3606,7 +4107,7 @@ declare module 'vscode' { * with which a nested snippet can be created. * @param number The number of this tabstop, defaults to an auto-increment * value starting at 1. - * @return This snippet string. + * @returns This snippet string. */ appendPlaceholder(value: string | ((snippet: SnippetString) => any), number?: number): SnippetString; @@ -3617,7 +4118,7 @@ declare module 'vscode' { * @param values The values for choices - the array of strings * @param number The number of this tabstop, defaults to an auto-increment * value starting at 1. - * @return This snippet string. + * @returns This snippet string. */ appendChoice(values: readonly string[], number?: number): SnippetString; @@ -3628,7 +4129,7 @@ declare module 'vscode' { * @param name The name of the variable - excluding the `$`. * @param defaultValue The default value which is used when the variable name cannot * be resolved - either a string or a function with which a nested snippet can be created. - * @return This snippet string. + * @returns This snippet string. */ appendVariable(name: string, defaultValue: string | ((snippet: SnippetString) => any)): SnippetString; } @@ -3647,7 +4148,7 @@ declare module 'vscode' { * @param position The position at which the command was invoked. * @param newName The new name of the symbol. If the given name is not valid, the provider must return a rejected promise. * @param token A cancellation token. - * @return A workspace edit or a thenable that resolves to such. The lack of a result can be + * @returns A workspace edit or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideRenameEdits(document: TextDocument, position: Position, newName: string, token: CancellationToken): ProviderResult; @@ -3663,9 +4164,18 @@ declare module 'vscode' { * @param document The document in which rename will be invoked. * @param position The position at which rename will be invoked. * @param token A cancellation token. - * @return The range or range and placeholder text of the identifier that is to be renamed. The lack of a result can signaled by returning `undefined` or `null`. + * @returns The range or range and placeholder text of the identifier that is to be renamed. The lack of a result can signaled by returning `undefined` or `null`. */ - prepareRename?(document: TextDocument, position: Position, token: CancellationToken): ProviderResult; + prepareRename?(document: TextDocument, position: Position, token: CancellationToken): ProviderResult; } /** @@ -3682,6 +4192,12 @@ declare module 'vscode' { */ readonly tokenModifiers: string[]; + /** + * Creates a semantic tokens legend. + * + * @param tokenTypes An array of token types. + * @param tokenModifiers An array of token modifiers. + */ constructor(tokenTypes: string[], tokenModifiers?: string[]); } @@ -3691,6 +4207,11 @@ declare module 'vscode' { */ export class SemanticTokensBuilder { + /** + * Creates a semantic tokens builder. + * + * @param legend A semantic tokens legent. + */ constructor(legend?: SemanticTokensLegend); /** @@ -3737,6 +4258,12 @@ declare module 'vscode' { */ readonly data: Uint32Array; + /** + * Create new semantic tokens. + * + * @param data Token data. + * @param resultId Result identifier. + */ constructor(data: Uint32Array, resultId?: string); } @@ -3757,6 +4284,12 @@ declare module 'vscode' { */ readonly edits: SemanticTokensEdit[]; + /** + * Create new semantic tokens edits. + * + * @param edits An array of semantic token edits + * @param resultId Result identifier. + */ constructor(edits: SemanticTokensEdit[], resultId?: string); } @@ -3778,6 +4311,13 @@ declare module 'vscode' { */ readonly data: Uint32Array | undefined; + /** + * Create a semantic token edit. + * + * @param start Start offset + * @param deleteCount Number of elements to remove. + * @param data Elements to insert + */ constructor(start: number, deleteCount: number, data?: Uint32Array); } @@ -3928,7 +4468,7 @@ declare module 'vscode' { * @param document The document in which the command was invoked. * @param options Options controlling formatting. * @param token A cancellation token. - * @return A set of text edits or a thenable that resolves to such. The lack of a result can be + * @returns A set of text edits or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined`, `null`, or an empty array. */ provideDocumentFormattingEdits(document: TextDocument, options: FormattingOptions, token: CancellationToken): ProviderResult; @@ -3951,10 +4491,30 @@ declare module 'vscode' { * @param range The range which should be formatted. * @param options Options controlling formatting. * @param token A cancellation token. - * @return A set of text edits or a thenable that resolves to such. The lack of a result can be + * @returns A set of text edits or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined`, `null`, or an empty array. */ provideDocumentRangeFormattingEdits(document: TextDocument, range: Range, options: FormattingOptions, token: CancellationToken): ProviderResult; + + + /** + * Provide formatting edits for multiple ranges in a document. + * + * This function is optional but allows a formatter to perform faster when formatting only modified ranges or when + * formatting a large number of selections. + * + * The given ranges are hints and providers can decide to format a smaller + * or larger range. Often this is done by adjusting the start and end + * of the range to full syntax nodes. + * + * @param document The document in which the command was invoked. + * @param ranges The ranges which should be formatted. + * @param options Options controlling formatting. + * @param token A cancellation token. + * @returns A set of text edits or a thenable that resolves to such. The lack of a result can be + * signaled by returning `undefined`, `null`, or an empty array. + */ + provideDocumentRangesFormattingEdits?(document: TextDocument, ranges: Range[], options: FormattingOptions, token: CancellationToken): ProviderResult; } /** @@ -3975,7 +4535,7 @@ declare module 'vscode' { * @param ch The character that has been typed. * @param options Options controlling formatting. * @param token A cancellation token. - * @return A set of text edits or a thenable that resolves to such. The lack of a result can be + * @returns A set of text edits or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined`, `null`, or an empty array. */ provideOnTypeFormattingEdits(document: TextDocument, position: Position, ch: string, options: FormattingOptions, token: CancellationToken): ProviderResult; @@ -4038,7 +4598,7 @@ declare module 'vscode' { /** * The index of the active parameter. * - * If provided, this is used in place of {@linkcode SignatureHelp.activeSignature}. + * If provided, this is used in place of {@linkcode SignatureHelp.activeParameter}. */ activeParameter?: number; @@ -4143,7 +4703,7 @@ declare module 'vscode' { * @param token A cancellation token. * @param context Information about how signature help was triggered. * - * @return Signature help or a thenable that resolves to such. The lack of a result can be + * @returns Signature help or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideSignatureHelp(document: TextDocument, position: Position, token: CancellationToken, context: SignatureHelpContext): ProviderResult; @@ -4196,32 +4756,113 @@ declare module 'vscode' { * Completion item kinds. */ export enum CompletionItemKind { + /** + * The `Text` completion item kind. + */ Text = 0, + /** + * The `Method` completion item kind. + */ Method = 1, + /** + * The `Function` completion item kind. + */ Function = 2, + /** + * The `Constructor` completion item kind. + */ Constructor = 3, + /** + * The `Field` completion item kind. + */ Field = 4, + /** + * The `Variable` completion item kind. + */ Variable = 5, + /** + * The `Class` completion item kind. + */ Class = 6, + /** + * The `Interface` completion item kind. + */ Interface = 7, + /** + * The `Module` completion item kind. + */ Module = 8, + /** + * The `Property` completion item kind. + */ Property = 9, + /** + * The `Unit` completion item kind. + */ Unit = 10, + /** + * The `Value` completion item kind. + */ Value = 11, + /** + * The `Enum` completion item kind. + */ Enum = 12, + /** + * The `Keyword` completion item kind. + */ Keyword = 13, + /** + * The `Snippet` completion item kind. + */ Snippet = 14, + /** + * The `Color` completion item kind. + */ Color = 15, + /** + * The `Reference` completion item kind. + */ Reference = 17, + /** + * The `File` completion item kind. + */ File = 16, + /** + * The `Folder` completion item kind. + */ Folder = 18, + /** + * The `EnumMember` completion item kind. + */ EnumMember = 19, + /** + * The `Constant` completion item kind. + */ Constant = 20, + /** + * The `Struct` completion item kind. + */ Struct = 21, + /** + * The `Event` completion item kind. + */ Event = 22, + /** + * The `Operator` completion item kind. + */ Operator = 23, + /** + * The `TypeParameter` completion item kind. + */ TypeParameter = 24, + /** + * The `User` completion item kind. + */ User = 25, + /** + * The `Issue` completion item kind. + */ Issue = 26, } @@ -4331,7 +4972,16 @@ declare module 'vscode' { * {@link Range.contains contain} the position at which completion has been {@link CompletionItemProvider.provideCompletionItems requested}. * *Note 2:* A insert range must be a prefix of a replace range, that means it must be contained and starting at the same position. */ - range?: Range | { inserting: Range; replacing: Range }; + range?: Range | { + /** + * The range that should be used when insert-accepting a completion. Must be a prefix of `replaceRange`. + */ + inserting: Range; + /** + * The range that should be used when replace-accepting a completion. + */ + replacing: Range; + }; /** * An optional set of characters that when pressed while this completion is active will accept it first and @@ -4472,7 +5122,7 @@ declare module 'vscode' { * @param token A cancellation token. * @param context How the completion was triggered. * - * @return An array of completions, a {@link CompletionList completion list}, or a thenable that resolves to either. + * @returns An array of completions, a {@link CompletionList completion list}, or a thenable that resolves to either. * The lack of a result can be signaled by returning `undefined`, `null`, or an empty array. */ provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext): ProviderResult>; @@ -4493,7 +5143,7 @@ declare module 'vscode' { * * @param item A completion item currently active in the UI. * @param token A cancellation token. - * @return The resolved completion item or a thenable that resolves to of such. It is OK to return the given + * @returns The resolved completion item or a thenable that resolves to of such. It is OK to return the given * `item`. When no result is returned, the given `item` will be used. */ resolveCompletionItem?(item: T, token: CancellationToken): ProviderResult; @@ -4519,7 +5169,7 @@ declare module 'vscode' { * @param position The position inline completions are requested for. * @param context A context object with additional information. * @param token A cancellation token. - * @return An array of completion items or a thenable that resolves to an array of completion items. + * @returns An array of completion items or a thenable that resolves to an array of completion items. */ provideInlineCompletionItems(document: TextDocument, position: Position, context: InlineCompletionContext, token: CancellationToken): ProviderResult; } @@ -4683,7 +5333,7 @@ declare module 'vscode' { * * @param document The document in which the command was invoked. * @param token A cancellation token. - * @return An array of {@link DocumentLink document links} or a thenable that resolves to such. The lack of a result + * @returns An array of {@link DocumentLink document links} or a thenable that resolves to such. The lack of a result * can be signaled by returning `undefined`, `null`, or an empty array. */ provideDocumentLinks(document: TextDocument, token: CancellationToken): ProviderResult; @@ -4809,7 +5459,7 @@ declare module 'vscode' { * * @param document The document in which the command was invoked. * @param token A cancellation token. - * @return An array of {@link ColorInformation color information} or a thenable that resolves to such. The lack of a result + * @returns An array of {@link ColorInformation color information} or a thenable that resolves to such. The lack of a result * can be signaled by returning `undefined`, `null`, or an empty array. */ provideDocumentColors(document: TextDocument, token: CancellationToken): ProviderResult; @@ -4820,10 +5470,19 @@ declare module 'vscode' { * @param color The color to show and insert. * @param context A context object with additional information * @param token A cancellation token. - * @return An array of color presentations or a thenable that resolves to such. The lack of a result + * @returns An array of color presentations or a thenable that resolves to such. The lack of a result * can be signaled by returning `undefined`, `null`, or an empty array. */ - provideColorPresentations(color: Color, context: { readonly document: TextDocument; readonly range: Range }, token: CancellationToken): ProviderResult; + provideColorPresentations(color: Color, context: { + /** + * The text document that contains the color + */ + readonly document: TextDocument; + /** + * The range in the document where the color is located. + */ + readonly range: Range; + }, token: CancellationToken): ProviderResult; } /** @@ -4979,7 +5638,7 @@ declare module 'vscode' { * @param document The document in which the command was invoked. * @param range The range for which inlay hints should be computed. * @param token A cancellation token. - * @return An array of inlay hints or a thenable that resolves to such. + * @returns An array of inlay hints or a thenable that resolves to such. */ provideInlayHints(document: TextDocument, range: Range, token: CancellationToken): ProviderResult; @@ -4991,7 +5650,7 @@ declare module 'vscode' { * * @param hint An inlay hint. * @param token A cancellation token. - * @return The resolved inlay hint or a thenable that resolves to such. It is OK to return the given `item`. When no result is returned, the given `item` will be used. + * @returns The resolved inlay hint or a thenable that resolves to such. It is OK to return the given `item`. When no result is returned, the given `item` will be used. */ resolveInlayHint?(hint: T, token: CancellationToken): ProviderResult; } @@ -5106,6 +5765,9 @@ declare module 'vscode' { constructor(range: Range, parent?: SelectionRange); } + /** + * The selection range provider interface defines the contract between extensions and the "Expand and Shrink Selection" feature. + */ export interface SelectionRangeProvider { /** * Provide selection ranges for the given positions. @@ -5117,7 +5779,7 @@ declare module 'vscode' { * @param document The document in which the command was invoked. * @param positions The positions at which the command was invoked. * @param token A cancellation token. - * @return Selection ranges or a thenable that resolves to such. The lack of a result can be + * @returns Selection ranges or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideSelectionRanges(document: TextDocument, positions: readonly Position[], token: CancellationToken): ProviderResult; @@ -5403,11 +6065,53 @@ declare module 'vscode' { * @param document The document in which the provider was invoked. * @param position The position at which the provider was invoked. * @param token A cancellation token. - * @return A list of ranges that can be edited together + * @returns A list of ranges that can be edited together */ provideLinkedEditingRanges(document: TextDocument, position: Position, token: CancellationToken): ProviderResult; } + /** + * An edit operation applied {@link DocumentDropEditProvider on drop}. + */ + export class DocumentDropEdit { + /** + * The text or snippet to insert at the drop location. + */ + insertText: string | SnippetString; + + /** + * An optional additional edit to apply on drop. + */ + additionalEdit?: WorkspaceEdit; + + /** + * @param insertText The text or snippet to insert at the drop location. + */ + constructor(insertText: string | SnippetString); + } + + /** + * Provider which handles dropping of resources into a text editor. + * + * This allows users to drag and drop resources (including resources from external apps) into the editor. While dragging + * and dropping files, users can hold down `shift` to drop the file into the editor instead of opening it. + * Requires `editor.dropIntoEditor.enabled` to be on. + */ + export interface DocumentDropEditProvider { + /** + * Provide edits which inserts the content being dragged and dropped into the document. + * + * @param document The document in which the drop occurred. + * @param position The position in the document where the drop occurred. + * @param dataTransfer A {@link DataTransfer} object that holds data about what is being dragged and dropped. + * @param token A cancellation token. + * + * @returns A {@link DocumentDropEdit} or a thenable that resolves to such. The lack of a result can be + * signaled by returning `undefined` or `null`. + */ + provideDocumentDropEdits(document: TextDocument, position: Position, dataTransfer: DataTransfer, token: CancellationToken): ProviderResult; + } + /** * A tuple of two characters, like a pair of * opening and closing brackets. @@ -5516,6 +6220,46 @@ declare module 'vscode' { action: EnterAction; } + /** + * Enumeration of commonly encountered syntax token types. + */ + export enum SyntaxTokenType { + /** + * Everything except tokens that are part of comments, string literals and regular expressions. + */ + Other = 0, + /** + * A comment. + */ + Comment = 1, + /** + * A string literal. + */ + String = 2, + /** + * A regular expression. + */ + RegEx = 3 + } + + /** + * Describes pairs of strings where the close string will be automatically inserted when typing the opening string. + */ + export interface AutoClosingPair { + /** + * The string that will trigger the automatic insertion of the closing string. + */ + open: string; + /** + * The closing string that will be automatically inserted when typing the opening string. + */ + close: string; + /** + * A set of tokens where the pair should not be auto closed. + */ + notIn?: SyntaxTokenType[]; + } + /** * The language configuration interfaces defines the contract between extensions * and various editor features, like automatic bracket insertion, automatic indentation etc. @@ -5546,6 +6290,10 @@ declare module 'vscode' { * The language's rules to be evaluated when pressing Enter. */ onEnterRules?: OnEnterRule[]; + /** + * The language's auto closing pairs. + */ + autoClosingPairs?: AutoClosingPair[]; /** * **Deprecated** Do not use. @@ -5566,9 +6314,21 @@ declare module 'vscode' { * @deprecated */ docComment?: { + /** + * @deprecated + */ scope: string; + /** + * @deprecated + */ open: string; + /** + * @deprecated + */ lineStart: string; + /** + * @deprecated + */ close?: string; }; }; @@ -5579,9 +6339,21 @@ declare module 'vscode' { * @deprecated * Use the autoClosingPairs property in the language configuration file instead. */ __characterPairSupport?: { + /** + * @deprecated + */ autoClosingPairs: { + /** + * @deprecated + */ open: string; + /** + * @deprecated + */ close: string; + /** + * @deprecated + */ notIn?: string[]; }[]; }; @@ -5676,7 +6448,7 @@ declare module 'vscode' { * Return a value from this configuration. * * @param section Configuration name, supports _dotted_ names. - * @return The value `section` denotes or `undefined`. + * @returns The value `section` denotes or `undefined`. */ get(section: string): T | undefined; @@ -5685,7 +6457,7 @@ declare module 'vscode' { * * @param section Configuration name, supports _dotted_ names. * @param defaultValue A value should be returned when no value could be found, is `undefined`. - * @return The value `section` denotes or the default. + * @returns The value `section` denotes or the default. */ get(section: string, defaultValue: T): T; @@ -5693,7 +6465,7 @@ declare module 'vscode' { * Check if this configuration has a certain value. * * @param section Configuration name, supports _dotted_ names. - * @return `true` if the section doesn't resolve to `undefined`. + * @returns `true` if the section doesn't resolve to `undefined`. */ has(section: string): boolean; @@ -5709,21 +6481,58 @@ declare module 'vscode' { * (`editor.fontSize` vs `editor`) otherwise no result is returned. * * @param section Configuration name, supports _dotted_ names. - * @return Information about a configuration setting or `undefined`. + * @returns Information about a configuration setting or `undefined`. */ inspect(section: string): { + + /** + * The fully qualified key of the configuration value + */ key: string; + /** + * The default value which is used when no other value is defined + */ defaultValue?: T; + + /** + * The global or installation-wide value. + */ globalValue?: T; + + /** + * The workspace-specific value. + */ workspaceValue?: T; + + /** + * The workpace-folder-specific value. + */ workspaceFolderValue?: T; + /** + * Language specific default value when this configuration value is created for a {@link ConfigurationScope language scope}. + */ defaultLanguageValue?: T; + + /** + * Language specific global value when this configuration value is created for a {@link ConfigurationScope language scope}. + */ globalLanguageValue?: T; + + /** + * Language specific workspace value when this configuration value is created for a {@link ConfigurationScope language scope}. + */ workspaceLanguageValue?: T; + + /** + * Language specific workspace-folder value when this configuration value is created for a {@link ConfigurationScope language scope}. + */ workspaceFolderLanguageValue?: T; + /** + * All language identifiers for which this configuration is defined. + */ languageIds?: string[]; } | undefined; @@ -5980,7 +6789,7 @@ declare module 'vscode' { * To get an instance of a `DiagnosticCollection` use * {@link languages.createDiagnosticCollection createDiagnosticCollection}. */ - export interface DiagnosticCollection { + export interface DiagnosticCollection extends Iterable<[uri: Uri, diagnostics: readonly Diagnostic[]]> { /** * The name of this diagnostic collection, for instance `typescript`. Every diagnostic @@ -6060,9 +6869,21 @@ declare module 'vscode' { /** * Represents the severity of a language status item. */ + /** + * Represents the severity level of a language status. + */ export enum LanguageStatusSeverity { + /** + * Informational severity level. + */ Information = 0, + /** + * Warning severity level. + */ Warning = 1, + /** + * Error severity level. + */ Error = 2 } @@ -6258,22 +7079,86 @@ declare module 'vscode' { } /** - * Accessibility information which controls screen reader behavior. + * A channel for containing log output. + * + * To get an instance of a `LogOutputChannel` use + * {@link window.createOutputChannel createOutputChannel}. */ - export interface AccessibilityInformation { + export interface LogOutputChannel extends OutputChannel { + /** - * Label to be read out by a screen reader once the item has focus. + * The current log level of the channel. Defaults to {@link env.logLevel editor log level}. */ - readonly label: string; + readonly logLevel: LogLevel; /** - * Role of the widget which defines how a screen reader interacts with it. - * The role should be set in special cases when for example a tree-like element behaves like a checkbox. - * If role is not specified the editor will pick the appropriate role automatically. - * More about aria roles can be found here https://w3c.github.io/aria/#widget_roles + * An {@link Event} which fires when the log level of the channel changes. */ - readonly role?: string; - } + readonly onDidChangeLogLevel: Event; + + /** + * Outputs the given trace message to the channel. Use this method to log verbose information. + * + * The message is only logged if the channel is configured to display {@link LogLevel.Trace trace} log level. + * + * @param message trace message to log + */ + trace(message: string, ...args: any[]): void; + + /** + * Outputs the given debug message to the channel. + * + * The message is only logged if the channel is configured to display {@link LogLevel.Debug debug} log level or lower. + * + * @param message debug message to log + */ + debug(message: string, ...args: any[]): void; + + /** + * Outputs the given information message to the channel. + * + * The message is only logged if the channel is configured to display {@link LogLevel.Info info} log level or lower. + * + * @param message info message to log + */ + info(message: string, ...args: any[]): void; + + /** + * Outputs the given warning message to the channel. + * + * The message is only logged if the channel is configured to display {@link LogLevel.Warning warning} log level or lower. + * + * @param message warning message to log + */ + warn(message: string, ...args: any[]): void; + + /** + * Outputs the given error or error message to the channel. + * + * The message is only logged if the channel is configured to display {@link LogLevel.Error error} log level or lower. + * + * @param error Error or error message to log + */ + error(error: string | Error, ...args: any[]): void; + } + + /** + * Accessibility information which controls screen reader behavior. + */ + export interface AccessibilityInformation { + /** + * Label to be read out by a screen reader once the item has focus. + */ + readonly label: string; + + /** + * Role of the widget which defines how a screen reader interacts with it. + * The role should be set in special cases when for example a tree-like element behaves like a checkbox. + * If role is not specified the editor will pick the appropriate role automatically. + * More about aria roles can be found here https://w3c.github.io/aria/#widget_roles + */ + readonly role?: string; + } /** * Represents the alignment of status bar items. @@ -6449,11 +7334,10 @@ declare module 'vscode' { * (shell) of the terminal. * * @param text The text to send. - * @param addNewLine Whether to add a new line to the text being sent, this is normally - * required to run a command in the terminal. The character(s) added are \n or \r\n - * depending on the platform. This defaults to `true`. + * @param shouldExecute Indicates that the text being sent should be executed rather than just inserted in the terminal. + * The character(s) added are `\n` or `\r\n`, depending on the platform. This defaults to `true`. */ - sendText(text: string, addNewLine?: boolean): void; + sendText(text: string, shouldExecute?: boolean): void; /** * Show the terminal panel and reveal this terminal in the UI. @@ -6494,10 +7378,10 @@ declare module 'vscode' { export interface TerminalEditorLocationOptions { /** * A view column in which the {@link Terminal terminal} should be shown in the editor area. - * Use {@link ViewColumn.Active active} to open in the active editor group, other values are - * adjusted to be `Min(column, columnCount + 1)`, the - * {@link ViewColumn.Active active}-column is not adjusted. Use - * {@linkcode ViewColumn.Beside} to open the editor to the side of the currently active one. + * The default is the {@link ViewColumn.Active active}. Columns that do not exist + * will be created as needed up to the maximum of {@linkcode ViewColumn.Nine}. + * Use {@linkcode ViewColumn.Beside} to open the editor to the side of the currently + * active one. */ viewColumn: ViewColumn; /** @@ -6563,7 +7447,7 @@ declare module 'vscode' { * that could have problems when asynchronous usage may overlap. * @param context Information about what links are being provided for. * @param token A cancellation token. - * @return A list of terminal links for the given line. + * @returns A list of terminal links for the given line. */ provideTerminalLinks(context: TerminalLinkContext, token: CancellationToken): ProviderResult; @@ -6773,7 +7657,7 @@ declare module 'vscode' { /** * Activates this extension and returns its public API. * - * @return A promise that will resolve when this extension has been activated. + * @returns A promise that will resolve when this extension has been activated. */ activate(): Thenable; } @@ -6817,7 +7701,12 @@ declare module 'vscode' { * * *Note* that asynchronous dispose-functions aren't awaited. */ - readonly subscriptions: { dispose(): any }[]; + readonly subscriptions: { + /** + * Function to clean up resources. + */ + dispose(): any; + }[]; /** * A memento object that stores state in the context @@ -6864,10 +7753,10 @@ declare module 'vscode' { readonly extensionPath: string; /** - * Gets the extension's environment variable collection for this workspace, enabling changes - * to be applied to terminal environment variables. + * Gets the extension's global environment variable collection for this workspace, enabling changes to be + * applied to terminal environment variables. */ - readonly environmentVariableCollection: EnvironmentVariableCollection; + readonly environmentVariableCollection: GlobalEnvironmentVariableCollection; /** * Get the absolute path of a resource contained in the extension. @@ -6876,7 +7765,7 @@ declare module 'vscode' { * {@linkcode ExtensionContext.extensionUri extensionUri}, e.g. `vscode.Uri.joinPath(context.extensionUri, relativePath);` * * @param relativePath A relative path to a resource contained in the extension. - * @return The absolute path of the resource. + * @returns The absolute path of the resource. */ asAbsolutePath(relativePath: string): string; @@ -6949,9 +7838,8 @@ declare module 'vscode' { readonly logPath: string; /** - * The mode the extension is running in. This is specific to the current - * extension. One extension may be in `ExtensionMode.Development` while - * other extensions in the host run in `ExtensionMode.Release`. + * The mode the extension is running in. See {@link ExtensionMode} + * for possible values and scenarios. */ readonly extensionMode: ExtensionMode; @@ -6970,7 +7858,7 @@ declare module 'vscode' { /** * Returns the stored keys. * - * @return The stored keys. + * @returns The stored keys. */ keys(): readonly string[]; @@ -6978,7 +7866,7 @@ declare module 'vscode' { * Return a value. * * @param key A string. - * @return The stored value or `undefined`. + * @returns The stored value or `undefined`. */ get(key: string): T | undefined; @@ -6988,7 +7876,7 @@ declare module 'vscode' { * @param key A string. * @param defaultValue A value that should be returned when there is no * value (`undefined`) with the given key. - * @return The stored value or the defaultValue. + * @returns The stored value or the defaultValue. */ get(key: string, defaultValue: T): T; @@ -7050,9 +7938,21 @@ declare module 'vscode' { * Represents a color theme kind. */ export enum ColorThemeKind { + /** + * A light color theme. + */ Light = 1, + /** + * A dark color theme. + */ Dark = 2, + /** + * A dark high contrast color theme. + */ HighContrast = 3, + /** + * A light high contrast color theme. + */ HighContrastLight = 4 } @@ -7147,6 +8047,11 @@ declare module 'vscode' { * Controls whether the terminal is cleared before executing the task. */ clear?: boolean; + + /** + * Controls whether the terminal is closed after executing the task. + */ + close?: boolean; } /** @@ -7186,6 +8091,12 @@ declare module 'vscode' { */ readonly id: string; + /** + * Private constructor + * + * @param id Identifier of a task group. + * @param label The human-readable name of a task group. + */ private constructor(id: string, label: string); } @@ -7389,6 +8300,9 @@ declare module 'vscode' { quoting: ShellQuoting; } + /** + * Represents a task execution that happens inside a shell. + */ export class ShellExecution { /** * Creates a shell execution with a full command line. @@ -7578,7 +8492,7 @@ declare module 'vscode' { /** * Provides tasks. * @param token A cancellation token. - * @return an array of tasks + * @returns an array of tasks */ provideTasks(token: CancellationToken): ProviderResult; @@ -7597,7 +8511,7 @@ declare module 'vscode' { * * @param task The task to resolve. * @param token A cancellation token. - * @return The resolved task + * @returns The resolved task */ resolveTask(task: T, token: CancellationToken): ProviderResult; } @@ -7678,6 +8592,9 @@ declare module 'vscode' { readonly exitCode: number | undefined; } + /** + * A task filter denotes tasks by their version and types + */ export interface TaskFilter { /** * The task version as used in the tasks.json file. @@ -7701,7 +8618,7 @@ declare module 'vscode' { * * @param type The task kind type this provider is registered for. * @param provider A task provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerTaskProvider(type: string, provider: TaskProvider): Disposable; @@ -7711,6 +8628,7 @@ declare module 'vscode' { * contributed through extensions. * * @param filter Optional filter to select tasks of a certain type or version. + * @returns A thenable that resolves to an array of tasks. */ export function fetchTasks(filter?: TaskFilter): Thenable; @@ -7723,6 +8641,7 @@ declare module 'vscode' { * In such an environment, only CustomExecution tasks can be run. * * @param task the task to execute + * @returns A thenable that resolves to a task execution. */ export function executeTask(task: Task): Thenable; @@ -7780,6 +8699,9 @@ declare module 'vscode' { SymbolicLink = 64 } + /** + * Permissions of a file. + */ export enum FilePermission { /** * The file is readonly. @@ -7977,7 +8899,16 @@ declare module 'vscode' { * @param options Configures the watch. * @returns A disposable that tells the provider to stop watching the `uri`. */ - watch(uri: Uri, options: { readonly recursive: boolean; readonly excludes: readonly string[] }): Disposable; + watch(uri: Uri, options: { + /** + * When enabled also watch subfolders. + */ + readonly recursive: boolean; + /** + * A list of paths and pattern to exclude from watching. + */ + readonly excludes: readonly string[]; + }): Disposable; /** * Retrieve metadata about a file. @@ -7987,7 +8918,7 @@ declare module 'vscode' { * `FileType.SymbolicLink | FileType.Directory`. * * @param uri The uri of the file to retrieve metadata about. - * @return The file metadata about the file. + * @returns The file metadata about the file. * @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when `uri` doesn't exist. */ stat(uri: Uri): FileStat | Thenable; @@ -7996,7 +8927,7 @@ declare module 'vscode' { * Retrieve all entries of a {@link FileType.Directory directory}. * * @param uri The uri of the folder. - * @return An array of name/type-tuples or a thenable that resolves to such. + * @returns An array of name/type-tuples or a thenable that resolves to such. * @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when `uri` doesn't exist. */ readDirectory(uri: Uri): [string, FileType][] | Thenable<[string, FileType][]>; @@ -8015,7 +8946,7 @@ declare module 'vscode' { * Read the entire contents of a file. * * @param uri The uri of the file. - * @return An array of bytes or a thenable that resolves to such. + * @returns An array of bytes or a thenable that resolves to such. * @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when `uri` doesn't exist. */ readFile(uri: Uri): Uint8Array | Thenable; @@ -8031,7 +8962,16 @@ declare module 'vscode' { * @throws {@linkcode FileSystemError.FileExists FileExists} when `uri` already exists, `create` is set but `overwrite` is not set. * @throws {@linkcode FileSystemError.NoPermissions NoPermissions} when permissions aren't sufficient. */ - writeFile(uri: Uri, content: Uint8Array, options: { readonly create: boolean; readonly overwrite: boolean }): void | Thenable; + writeFile(uri: Uri, content: Uint8Array, options: { + /** + * Create the file if it does not exist already. + */ + readonly create: boolean; + /** + * Overwrite the file if it does exist. + */ + readonly overwrite: boolean; + }): void | Thenable; /** * Delete a file. @@ -8041,7 +8981,12 @@ declare module 'vscode' { * @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when `uri` doesn't exist. * @throws {@linkcode FileSystemError.NoPermissions NoPermissions} when permissions aren't sufficient. */ - delete(uri: Uri, options: { readonly recursive: boolean }): void | Thenable; + delete(uri: Uri, options: { + /** + * Delete the content recursively if a folder is denoted. + */ + readonly recursive: boolean; + }): void | Thenable; /** * Rename a file or folder. @@ -8054,7 +8999,12 @@ declare module 'vscode' { * @throws {@linkcode FileSystemError.FileExists FileExists} when `newUri` exists and when the `overwrite` option is not `true`. * @throws {@linkcode FileSystemError.NoPermissions NoPermissions} when permissions aren't sufficient. */ - rename(oldUri: Uri, newUri: Uri, options: { readonly overwrite: boolean }): void | Thenable; + rename(oldUri: Uri, newUri: Uri, options: { + /** + * Overwrite the file if it does exist. + */ + readonly overwrite: boolean; + }): void | Thenable; /** * Copy files or folders. Implementing this function is optional but it will speedup @@ -8068,7 +9018,12 @@ declare module 'vscode' { * @throws {@linkcode FileSystemError.FileExists FileExists} when `destination` exists and when the `overwrite` option is not `true`. * @throws {@linkcode FileSystemError.NoPermissions NoPermissions} when permissions aren't sufficient. */ - copy?(source: Uri, destination: Uri, options: { readonly overwrite: boolean }): void | Thenable; + copy?(source: Uri, destination: Uri, options: { + /** + * Overwrite the file if it does exist. + */ + readonly overwrite: boolean; + }): void | Thenable; } /** @@ -8085,7 +9040,7 @@ declare module 'vscode' { * Retrieve metadata about a file. * * @param uri The uri of the file to retrieve metadata about. - * @return The file metadata about the file. + * @returns The file metadata about the file. */ stat(uri: Uri): Thenable; @@ -8093,7 +9048,7 @@ declare module 'vscode' { * Retrieve all entries of a {@link FileType.Directory directory}. * * @param uri The uri of the folder. - * @return An array of name/type-tuples or a thenable that resolves to such. + * @returns An array of name/type-tuples or a thenable that resolves to such. */ readDirectory(uri: Uri): Thenable<[string, FileType][]>; @@ -8111,7 +9066,7 @@ declare module 'vscode' { * Read the entire contents of a file. * * @param uri The uri of the file. - * @return An array of bytes or a thenable that resolves to such. + * @returns An array of bytes or a thenable that resolves to such. */ readFile(uri: Uri): Thenable; @@ -8129,7 +9084,16 @@ declare module 'vscode' { * @param uri The resource that is to be deleted. * @param options Defines if trash can should be used and if deletion of folders is recursive */ - delete(uri: Uri, options?: { recursive?: boolean; useTrash?: boolean }): Thenable; + delete(uri: Uri, options?: { + /** + * Delete the content recursively if a folder is denoted. + */ + recursive?: boolean; + /** + * Use the os's trashcan instead of permanently deleting files whenever possible. + */ + useTrash?: boolean; + }): Thenable; /** * Rename a file or folder. @@ -8138,7 +9102,12 @@ declare module 'vscode' { * @param target The new location. * @param options Defines if existing files should be overwritten. */ - rename(source: Uri, target: Uri, options?: { overwrite?: boolean }): Thenable; + rename(source: Uri, target: Uri, options?: { + /** + * Overwrite the file if it does exist. + */ + overwrite?: boolean; + }): Thenable; /** * Copy files or folders. @@ -8147,7 +9116,12 @@ declare module 'vscode' { * @param target The destination location. * @param options Defines if existing files should be overwritten. */ - copy(source: Uri, target: Uri, options?: { overwrite?: boolean }): Thenable; + copy(source: Uri, target: Uri, options?: { + /** + * Overwrite the file if it does exist. + */ + overwrite?: boolean; + }): Thenable; /** * Check if a given file system supports writing files. @@ -8158,7 +9132,7 @@ declare module 'vscode' { * * @param scheme The scheme of the filesystem, for example `file` or `git`. * - * @return `true` if the file system supports writing, `false` if it does not + * @returns `true` if the file system supports writing, `false` if it does not * support writing (i.e. it is readonly), and `undefined` if the editor does not * know about the filesystem. */ @@ -8202,9 +9176,11 @@ declare module 'vscode' { /** * Controls whether command uris are enabled in webview content or not. * - * Defaults to false. + * Defaults to `false` (command uris are disabled). + * + * If you pass in an array, only the commands in the array are allowed. */ - readonly enableCommandUris?: boolean; + readonly enableCommandUris?: boolean | readonly string[]; /** * Root paths from which the webview can load local (filesystem) resources using uris from `asWebviewUri` @@ -8294,7 +9270,7 @@ declare module 'vscode' { * efficiently transferred to the webview and will also be correctly recreated inside * of the webview. * - * @return A promise that resolves when the message is posted to a webview or when it is + * @returns A promise that resolves when the message is posted to a webview or when it is * dropped because the message was not deliverable. * * Returns `true` if the message was posted to the webview. Messages can only be posted to @@ -8381,7 +9357,16 @@ declare module 'vscode' { /** * Icon for the panel shown in UI. */ - iconPath?: Uri | { readonly light: Uri; readonly dark: Uri }; + iconPath?: Uri | { + /** + * The icon path for the light theme. + */ + readonly light: Uri; + /** + * The icon path for the dark theme. + */ + readonly dark: Uri; + }; /** * {@linkcode Webview} belonging to the panel. @@ -8498,7 +9483,7 @@ declare module 'vscode' { * serializer must restore the webview's `.html` and hook up all webview events. * @param state Persisted state from the webview content. * - * @return Thenable indicating that the webview has been fully restored. + * @returns Thenable indicating that the webview has been fully restored. */ deserializeWebviewPanel(webviewPanel: WebviewPanel, state: T): Thenable; } @@ -8529,6 +9514,12 @@ declare module 'vscode' { */ description?: string; + /** + * The badge to display for this webview view. + * To remove the badge, set to undefined. + */ + badge?: ViewBadge | undefined; + /** * Event fired when the view is disposed. * @@ -8611,7 +9602,7 @@ declare module 'vscode' { */ export interface WebviewViewProvider { /** - * Revolves a webview view. + * Resolves a webview view. * * `resolveWebviewView` is called when a view first becomes visible. This may happen when the view is * first loaded or when the user hides and then shows a view again. @@ -8621,7 +9612,7 @@ declare module 'vscode' { * @param context Additional metadata about the view being resolved. * @param token Cancellation token indicating that the view being provided is no longer needed. * - * @return Optional thenable indicating that the view has been fully resolved. + * @returns Optional thenable indicating that the view has been fully resolved. */ resolveWebviewView(webviewView: WebviewView, context: WebviewViewResolveContext, token: CancellationToken): Thenable | void; } @@ -8652,7 +9643,7 @@ declare module 'vscode' { * * @param token A cancellation token that indicates the result is no longer needed. * - * @return Thenable indicating that the custom editor has been resolved. + * @returns Thenable indicating that the custom editor has been resolved. */ resolveCustomTextEditor(document: TextDocument, webviewPanel: WebviewPanel, token: CancellationToken): Thenable | void; } @@ -8750,7 +9741,7 @@ declare module 'vscode' { } /** - * Additional information used to implement {@linkcode CustomEditableDocument.backup}. + * Additional information used to implement {@linkcode CustomDocumentBackup}. */ interface CustomDocumentBackupContext { /** @@ -8811,7 +9802,7 @@ declare module 'vscode' { * @param openContext Additional information about the opening custom document. * @param token A cancellation token that indicates the result is no longer needed. * - * @return The custom document. + * @returns The custom document. */ openCustomDocument(uri: Uri, openContext: CustomDocumentOpenContext, token: CancellationToken): Thenable | T; @@ -8830,7 +9821,7 @@ declare module 'vscode' { * * @param token A cancellation token that indicates the result is no longer needed. * - * @return Optional thenable indicating that the custom editor has been resolved. + * @returns Optional thenable indicating that the custom editor has been resolved. */ resolveCustomEditor(document: T, webviewPanel: WebviewPanel, token: CancellationToken): Thenable | void; } @@ -8882,7 +9873,7 @@ declare module 'vscode' { * @param document Document to save. * @param cancellation Token that signals the save is no longer required (for example, if another save was triggered). * - * @return Thenable signaling that saving has completed. + * @returns Thenable signaling that saving has completed. */ saveCustomDocument(document: T, cancellation: CancellationToken): Thenable; @@ -8898,7 +9889,7 @@ declare module 'vscode' { * @param destination Location to save to. * @param cancellation Token that signals the save is no longer required. * - * @return Thenable signaling that saving has completed. + * @returns Thenable signaling that saving has completed. */ saveCustomDocumentAs(document: T, destination: Uri, cancellation: CancellationToken): Thenable; @@ -8915,7 +9906,7 @@ declare module 'vscode' { * @param document Document to revert. * @param cancellation Token that signals the revert is no longer required. * - * @return Thenable signaling that the change has completed. + * @returns Thenable signaling that the change has completed. */ revertCustomDocument(document: T, cancellation: CancellationToken): Thenable; @@ -8977,6 +9968,42 @@ declare module 'vscode' { Web = 2 } + /** + * Log levels + */ + export enum LogLevel { + + /** + * No messages are logged with this level. + */ + Off = 0, + + /** + * All messages are logged with this level. + */ + Trace = 1, + + /** + * Messages with debug and higher log level are logged with this level. + */ + Debug = 2, + + /** + * Messages with info and higher log level are logged with this level. + */ + Info = 3, + + /** + * Messages with warning and higher log level are logged with this level. + */ + Warning = 4, + + /** + * Only error messages are logged with this level. + */ + Error = 5 + } + /** * Namespace describing the environment the editor runs in. */ @@ -9047,6 +10074,21 @@ declare module 'vscode' { */ export const onDidChangeTelemetryEnabled: Event; + /** + * An {@link Event} which fires when the default shell changes. This fires with the new + * shell path. + */ + export const onDidChangeShell: Event; + + /** + * Creates a new {@link TelemetryLogger telemetry logger}. + * + * @param sender The telemetry sender that is used by the telemetry logger. + * @param options Options for the telemetry logger. + * @returns A new telemetry logger + */ + export function createTelemetryLogger(sender: TelemetrySender, options?: TelemetryLoggerOptions): TelemetryLogger; + /** * The name of a remote. Defined by extensions, popular samples are `wsl` for the Windows * Subsystem for Linux or `ssh-remote` for remotes using a secure shell. @@ -9138,9 +10180,19 @@ declare module 'vscode' { * Any other scheme will be handled as if the provided URI is a workspace URI. In that case, the method will return * a URI which, when handled, will make the editor open the workspace. * - * @return A uri that can be used on the client machine. + * @returns A uri that can be used on the client machine. */ export function asExternalUri(target: Uri): Thenable; + + /** + * The current log level of the editor. + */ + export const logLevel: LogLevel; + + /** + * An {@link Event} which fires when the log level of the editor changes. + */ + export const onDidChangeLogLevel: Event; } /** @@ -9154,7 +10206,7 @@ declare module 'vscode' { * * palette - Use the `commands`-section in `package.json` to make a command show in * the [command palette](https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette). * * keybinding - Use the `keybindings`-section in `package.json` to enable - * [keybindings](https://code.visualstudio.com/docs/getstarted/keybindings#_customizing-shortcuts) + * [keybindings](https://code.visualstudio.com/docs/getstarted/keybindings#_advanced-customization) * for your extension. * * Commands from other extensions and from the editor itself are accessible to an extension. However, @@ -9191,7 +10243,7 @@ declare module 'vscode' { * @param command A unique identifier for the command. * @param callback A command handler function. * @param thisArg The `this` context used when invoking the handler function. - * @return Disposable which unregisters this command on disposal. + * @returns Disposable which unregisters this command on disposal. */ export function registerCommand(command: string, callback: (...args: any[]) => any, thisArg?: any): Disposable; @@ -9208,7 +10260,7 @@ declare module 'vscode' { * @param command A unique identifier for the command. * @param callback A command handler function with access to an {@link TextEditor editor} and an {@link TextEditorEdit edit}. * @param thisArg The `this` context used when invoking the handler function. - * @return Disposable which unregisters this command on disposal. + * @returns Disposable which unregisters this command on disposal. */ export function registerTextEditorCommand(command: string, callback: (textEditor: TextEditor, edit: TextEditorEdit, ...args: any[]) => void, thisArg?: any): Disposable; @@ -9223,7 +10275,7 @@ declare module 'vscode' { * * @param command Identifier of the command to execute. * @param rest Parameters passed to the command function. - * @return A thenable that resolves to the returned value of the given command. Returns `undefined` when + * @returns A thenable that resolves to the returned value of the given command. Returns `undefined` when * the command handler function doesn't return anything. */ export function executeCommand(command: string, ...rest: any[]): Thenable; @@ -9233,7 +10285,7 @@ declare module 'vscode' { * treated as internal commands. * * @param filterInternal Set `true` to not see internal commands (starting with an underscore) - * @return Thenable that resolves to a list of command ids. + * @returns Thenable that resolves to a list of command ids. */ export function getCommands(filterInternal?: boolean): Thenable; } @@ -9408,11 +10460,11 @@ declare module 'vscode' { * to control where the editor is being shown. Might change the {@link window.activeTextEditor active editor}. * * @param document A text document to be shown. - * @param column A view column in which the {@link TextEditor editor} should be shown. The default is the {@link ViewColumn.Active active}, other values - * are adjusted to be `Min(column, columnCount + 1)`, the {@link ViewColumn.Active active}-column is not adjusted. Use {@linkcode ViewColumn.Beside} + * @param column A view column in which the {@link TextEditor editor} should be shown. The default is the {@link ViewColumn.Active active}. + * Columns that do not exist will be created as needed up to the maximum of {@linkcode ViewColumn.Nine}. Use {@linkcode ViewColumn.Beside} * to open the editor to the side of the currently active one. * @param preserveFocus When `true` the editor will not take focus. - * @return A promise that resolves to an {@link TextEditor editor}. + * @returns A promise that resolves to an {@link TextEditor editor}. */ export function showTextDocument(document: TextDocument, column?: ViewColumn, preserveFocus?: boolean): Thenable; @@ -9422,7 +10474,7 @@ declare module 'vscode' { * * @param document A text document to be shown. * @param options {@link TextDocumentShowOptions Editor options} to configure the behavior of showing the {@link TextEditor editor}. - * @return A promise that resolves to an {@link TextEditor editor}. + * @returns A promise that resolves to an {@link TextEditor editor}. */ export function showTextDocument(document: TextDocument, options?: TextDocumentShowOptions): Thenable; @@ -9433,7 +10485,7 @@ declare module 'vscode' { * * @param uri A resource identifier. * @param options {@link TextDocumentShowOptions Editor options} to configure the behavior of showing the {@link TextEditor editor}. - * @return A promise that resolves to an {@link TextEditor editor}. + * @returns A promise that resolves to an {@link TextEditor editor}. */ export function showTextDocument(uri: Uri, options?: TextDocumentShowOptions): Thenable; @@ -9443,7 +10495,7 @@ declare module 'vscode' { * @param document A text document to be shown. * @param options {@link NotebookDocumentShowOptions Editor options} to configure the behavior of showing the {@link NotebookEditor notebook editor}. * - * @return A promise that resolves to an {@link NotebookEditor notebook editor}. + * @returns A promise that resolves to an {@link NotebookEditor notebook editor}. */ export function showNotebookDocument(document: NotebookDocument, options?: NotebookDocumentShowOptions): Thenable; @@ -9451,7 +10503,7 @@ declare module 'vscode' { * Create a TextEditorDecorationType that can be used to add decorations to text editors. * * @param options Rendering options for the decoration type. - * @return A new decoration type instance. + * @returns A new decoration type instance. */ export function createTextEditorDecorationType(options: DecorationRenderOptions): TextEditorDecorationType; @@ -9461,7 +10513,7 @@ declare module 'vscode' { * * @param message The message to show. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showInformationMessage(message: string, ...items: T[]): Thenable; @@ -9472,7 +10524,7 @@ declare module 'vscode' { * @param message The message to show. * @param options Configures the behaviour of the message. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showInformationMessage(message: string, options: MessageOptions, ...items: T[]): Thenable; @@ -9483,7 +10535,7 @@ declare module 'vscode' { * * @param message The message to show. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showInformationMessage(message: string, ...items: T[]): Thenable; @@ -9495,7 +10547,7 @@ declare module 'vscode' { * @param message The message to show. * @param options Configures the behaviour of the message. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showInformationMessage(message: string, options: MessageOptions, ...items: T[]): Thenable; @@ -9506,7 +10558,7 @@ declare module 'vscode' { * * @param message The message to show. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showWarningMessage(message: string, ...items: T[]): Thenable; @@ -9518,7 +10570,7 @@ declare module 'vscode' { * @param message The message to show. * @param options Configures the behaviour of the message. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showWarningMessage(message: string, options: MessageOptions, ...items: T[]): Thenable; @@ -9529,7 +10581,7 @@ declare module 'vscode' { * * @param message The message to show. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showWarningMessage(message: string, ...items: T[]): Thenable; @@ -9541,7 +10593,7 @@ declare module 'vscode' { * @param message The message to show. * @param options Configures the behaviour of the message. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showWarningMessage(message: string, options: MessageOptions, ...items: T[]): Thenable; @@ -9552,7 +10604,7 @@ declare module 'vscode' { * * @param message The message to show. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showErrorMessage(message: string, ...items: T[]): Thenable; @@ -9564,7 +10616,7 @@ declare module 'vscode' { * @param message The message to show. * @param options Configures the behaviour of the message. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showErrorMessage(message: string, options: MessageOptions, ...items: T[]): Thenable; @@ -9575,7 +10627,7 @@ declare module 'vscode' { * * @param message The message to show. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showErrorMessage(message: string, ...items: T[]): Thenable; @@ -9587,7 +10639,7 @@ declare module 'vscode' { * @param message The message to show. * @param options Configures the behaviour of the message. * @param items A set of items that will be rendered as actions in the message. - * @return A thenable that resolves to the selected item or `undefined` when being dismissed. + * @returns A thenable that resolves to the selected item or `undefined` when being dismissed. */ export function showErrorMessage(message: string, options: MessageOptions, ...items: T[]): Thenable; @@ -9597,9 +10649,9 @@ declare module 'vscode' { * @param items An array of strings, or a promise that resolves to an array of strings. * @param options Configures the behavior of the selection list. * @param token A token that can be used to signal cancellation. - * @return A promise that resolves to the selected items or `undefined`. + * @returns A promise that resolves to the selected items or `undefined`. */ - export function showQuickPick(items: readonly string[] | Thenable, options: QuickPickOptions & { canPickMany: true }, token?: CancellationToken): Thenable; + export function showQuickPick(items: readonly string[] | Thenable, options: QuickPickOptions & { /** literal-type defines return type */canPickMany: true }, token?: CancellationToken): Thenable; /** * Shows a selection list. @@ -9607,7 +10659,7 @@ declare module 'vscode' { * @param items An array of strings, or a promise that resolves to an array of strings. * @param options Configures the behavior of the selection list. * @param token A token that can be used to signal cancellation. - * @return A promise that resolves to the selection or `undefined`. + * @returns A promise that resolves to the selection or `undefined`. */ export function showQuickPick(items: readonly string[] | Thenable, options?: QuickPickOptions, token?: CancellationToken): Thenable; @@ -9617,9 +10669,9 @@ declare module 'vscode' { * @param items An array of items, or a promise that resolves to an array of items. * @param options Configures the behavior of the selection list. * @param token A token that can be used to signal cancellation. - * @return A promise that resolves to the selected items or `undefined`. + * @returns A promise that resolves to the selected items or `undefined`. */ - export function showQuickPick(items: readonly T[] | Thenable, options: QuickPickOptions & { canPickMany: true }, token?: CancellationToken): Thenable; + export function showQuickPick(items: readonly T[] | Thenable, options: QuickPickOptions & { /** literal-type defines return type */ canPickMany: true }, token?: CancellationToken): Thenable; /** * Shows a selection list. @@ -9627,7 +10679,7 @@ declare module 'vscode' { * @param items An array of items, or a promise that resolves to an array of items. * @param options Configures the behavior of the selection list. * @param token A token that can be used to signal cancellation. - * @return A promise that resolves to the selected item or `undefined`. + * @returns A promise that resolves to the selected item or `undefined`. */ export function showQuickPick(items: readonly T[] | Thenable, options?: QuickPickOptions, token?: CancellationToken): Thenable; @@ -9636,7 +10688,7 @@ declare module 'vscode' { * Returns `undefined` if no folder is open. * * @param options Configures the behavior of the workspace folder list. - * @return A promise that resolves to the workspace folder or `undefined`. + * @returns A promise that resolves to the workspace folder or `undefined`. */ export function showWorkspaceFolderPick(options?: WorkspaceFolderPickOptions): Thenable; @@ -9667,7 +10719,7 @@ declare module 'vscode' { * * @param options Configures the behavior of the input box. * @param token A token that can be used to signal cancellation. - * @return A promise that resolves to a string the user provided or to `undefined` in case of dismissal. + * @returns A promise that resolves to a string the user provided or to `undefined` in case of dismissal. */ export function showInputBox(options?: InputBoxOptions, token?: CancellationToken): Thenable; @@ -9679,7 +10731,7 @@ declare module 'vscode' { * is easier to use. {@link window.createQuickPick} should be used * when {@link window.showQuickPick} does not offer the required flexibility. * - * @return A new {@link QuickPick}. + * @returns A new {@link QuickPick}. */ export function createQuickPick(): QuickPick; @@ -9690,7 +10742,7 @@ declare module 'vscode' { * is easier to use. {@link window.createInputBox} should be used * when {@link window.showInputBox} does not offer the required flexibility. * - * @return A new {@link InputBox}. + * @returns A new {@link InputBox}. */ export function createInputBox(): InputBox; @@ -9703,9 +10755,19 @@ declare module 'vscode' { * * @param name Human-readable string which will be used to represent the channel in the UI. * @param languageId The identifier of the language associated with the channel. + * @returns A new output channel. */ export function createOutputChannel(name: string, languageId?: string): OutputChannel; + /** + * Creates a new {@link LogOutputChannel log output channel} with the given name. + * + * @param name Human-readable string which will be used to represent the channel in the UI. + * @param options Options for the log output channel. + * @returns A new log output channel. + */ + export function createOutputChannel(name: string, options: { /** literal-type defines return type */log: true }): LogOutputChannel; + /** * Create and show a new webview panel. * @@ -9714,9 +10776,18 @@ declare module 'vscode' { * @param showOptions Where to show the webview in the editor. If preserveFocus is set, the new webview will not take focus. * @param options Settings for the new panel. * - * @return New webview panel. + * @returns New webview panel. */ - export function createWebviewPanel(viewType: string, title: string, showOptions: ViewColumn | { readonly viewColumn: ViewColumn; readonly preserveFocus?: boolean }, options?: WebviewPanelOptions & WebviewOptions): WebviewPanel; + export function createWebviewPanel(viewType: string, title: string, showOptions: ViewColumn | { + /** + * The view column in which the {@link WebviewPanel} should be shown. + */ + readonly viewColumn: ViewColumn; + /** + * An optional flag that when `true` will stop the panel from taking focus. + */ + readonly preserveFocus?: boolean; + }, options?: WebviewPanelOptions & WebviewOptions): WebviewPanel; /** * Set a message to the status bar. This is a short hand for the more powerful @@ -9724,7 +10795,7 @@ declare module 'vscode' { * * @param text The message to show, supports icon substitution as in status bar {@link StatusBarItem.text items}. * @param hideAfterTimeout Timeout in milliseconds after which the message will be disposed. - * @return A disposable which hides the status bar message. + * @returns A disposable which hides the status bar message. */ export function setStatusBarMessage(text: string, hideAfterTimeout: number): Disposable; @@ -9734,7 +10805,7 @@ declare module 'vscode' { * * @param text The message to show, supports icon substitution as in status bar {@link StatusBarItem.text items}. * @param hideWhenDone Thenable on which completion (resolve or reject) the message will be disposed. - * @return A disposable which hides the status bar message. + * @returns A disposable which hides the status bar message. */ export function setStatusBarMessage(text: string, hideWhenDone: Thenable): Disposable; @@ -9746,7 +10817,7 @@ declare module 'vscode' { * longer used. * * @param text The message to show, supports icon substitution as in status bar {@link StatusBarItem.text items}. - * @return A disposable which hides the status bar message. + * @returns A disposable which hides the status bar message. */ export function setStatusBarMessage(text: string): Disposable; @@ -9758,7 +10829,7 @@ declare module 'vscode' { * * @param task A callback returning a promise. Progress increments can be reported with * the provided {@link Progress}-object. - * @return The thenable the task did return. + * @returns The thenable the task did return. */ export function withScmProgress(task: (progress: Progress) => Thenable): Thenable; @@ -9767,6 +10838,7 @@ declare module 'vscode' { * and while the promise it returned isn't resolved nor rejected. The location at which * progress should show (and other details) is defined via the passed {@linkcode ProgressOptions}. * + * @param options A {@linkcode ProgressOptions}-object describing the options to use for showing progress, like its location * @param task A callback returning a promise. Progress state can be reported with * the provided {@link Progress}-object. * @@ -9779,28 +10851,38 @@ declare module 'vscode' { * Note that currently only `ProgressLocation.Notification` is supporting to show a cancel button to cancel the * long running operation. * - * @return The thenable the task-callback returned. + * @returns The thenable the task-callback returned. */ - export function withProgress(options: ProgressOptions, task: (progress: Progress<{ message?: string; increment?: number }>, token: CancellationToken) => Thenable): Thenable; + export function withProgress(options: ProgressOptions, task: (progress: Progress<{ + /** + * A progress message that represents a chunk of work + */ + message?: string; + /** + * An increment for discrete progress. Increments will be summed up until 100% is reached + */ + increment?: number; + }>, token: CancellationToken) => Thenable): Thenable; /** * Creates a status bar {@link StatusBarItem item}. * + * @param id The identifier of the item. Must be unique within the extension. * @param alignment The alignment of the item. * @param priority The priority of the item. Higher values mean the item should be shown more to the left. - * @return A new status bar item. + * @returns A new status bar item. */ - export function createStatusBarItem(alignment?: StatusBarAlignment, priority?: number): StatusBarItem; + export function createStatusBarItem(id: string, alignment?: StatusBarAlignment, priority?: number): StatusBarItem; /** * Creates a status bar {@link StatusBarItem item}. * - * @param id The unique identifier of the item. + * @see {@link createStatusBarItem} for creating a status bar item with an identifier. * @param alignment The alignment of the item. * @param priority The priority of the item. Higher values mean the item should be shown more to the left. - * @return A new status bar item. + * @returns A new status bar item. */ - export function createStatusBarItem(id: string, alignment?: StatusBarAlignment, priority?: number): StatusBarItem; + export function createStatusBarItem(alignment?: StatusBarAlignment, priority?: number): StatusBarItem; /** * Creates a {@link Terminal} with a backing shell process. The cwd of the terminal will be the workspace @@ -9811,7 +10893,7 @@ declare module 'vscode' { * @param shellArgs Optional args for the custom shell executable. A string can be used on Windows only which * allows specifying shell args in * [command-line format](https://msdn.microsoft.com/en-au/08dfcab2-eb6e-49a4-80eb-87d4076c98c6). - * @return A new Terminal. + * @returns A new Terminal. * @throws When running in an environment where a new process cannot be started. */ export function createTerminal(name?: string, shellPath?: string, shellArgs?: readonly string[] | string): Terminal; @@ -9820,7 +10902,7 @@ declare module 'vscode' { * Creates a {@link Terminal} with a backing shell process. * * @param options A TerminalOptions object describing the characteristics of the new terminal. - * @return A new Terminal. + * @returns A new Terminal. * @throws When running in an environment where a new process cannot be started. */ export function createTerminal(options: TerminalOptions): Terminal; @@ -9830,7 +10912,7 @@ declare module 'vscode' { * * @param options An {@link ExtensionTerminalOptions} object describing * the characteristics of the new terminal. - * @return A new Terminal. + * @returns A new Terminal. */ export function createTerminal(options: ExtensionTerminalOptions): Terminal; @@ -9842,6 +10924,7 @@ declare module 'vscode' { * * @param viewId Id of the view contributed using the extension point `views`. * @param treeDataProvider A {@link TreeDataProvider} that provides tree data for the view + * @returns A {@link Disposable disposable} that unregisters the {@link TreeDataProvider}. */ export function registerTreeDataProvider(viewId: string, treeDataProvider: TreeDataProvider): Disposable; @@ -9873,6 +10956,7 @@ declare module 'vscode' { * the current extension is about to be handled. * * @param handler The uri handler to register for this extension. + * @returns A {@link Disposable disposable} that unregisters the handler. */ export function registerUriHandler(handler: UriHandler): Disposable; @@ -9886,6 +10970,7 @@ declare module 'vscode' { * * @param viewType Type of the webview panel that can be serialized. * @param serializer Webview serializer. + * @returns A {@link Disposable disposable} that unregisters the serializer. */ export function registerWebviewPanelSerializer(viewType: string, serializer: WebviewPanelSerializer): Disposable; @@ -9896,7 +10981,7 @@ declare module 'vscode' { * `views` contribution in the package.json. * @param provider Provider for the webview views. * - * @return Disposable that unregisters the provider. + * @returns Disposable that unregisters the provider. */ export function registerWebviewViewProvider(viewId: string, provider: WebviewViewProvider, options?: { /** @@ -9935,7 +11020,7 @@ declare module 'vscode' { * @param provider Provider that resolves custom editors. * @param options Options for the provider. * - * @return Disposable that unregisters the provider. + * @returns Disposable that unregisters the provider. */ export function registerCustomEditorProvider(viewType: string, provider: CustomTextEditorProvider | CustomReadonlyEditorProvider | CustomEditorProvider, options?: { /** @@ -9963,21 +11048,23 @@ declare module 'vscode' { /** * Register provider that enables the detection and handling of links within the terminal. * @param provider The provider that provides the terminal links. - * @return Disposable that unregisters the provider. + * @returns Disposable that unregisters the provider. */ export function registerTerminalLinkProvider(provider: TerminalLinkProvider): Disposable; /** * Registers a provider for a contributed terminal profile. + * * @param id The ID of the contributed terminal profile. * @param provider The terminal profile provider. + * @returns A {@link Disposable disposable} that unregisters the provider. */ export function registerTerminalProfileProvider(id: string, provider: TerminalProfileProvider): Disposable; /** * Register a file decoration provider. * * @param provider A {@link FileDecorationProvider}. - * @return A {@link Disposable} that unregisters the provider. + * @returns A {@link Disposable} that unregisters the provider. */ export function registerFileDecorationProvider(provider: FileDecorationProvider): Disposable; @@ -10019,6 +11106,44 @@ declare module 'vscode' { * An optional interface to implement drag and drop in the tree view. */ dragAndDropController?: TreeDragAndDropController; + + /** + * By default, when the children of a tree item have already been fetched, child checkboxes are automatically managed based on the checked state of the parent tree item. + * If the tree item is collapsed by default (meaning that the children haven't yet been fetched) then child checkboxes will not be updated. + * To override this behavior and manage child and parent checkbox state in the extension, set this to `true`. + * + * Examples where {@link TreeViewOptions.manageCheckboxStateManually} is false, the default behavior: + * + * 1. A tree item is checked, then its children are fetched. The children will be checked. + * + * 2. A tree item's parent is checked. The tree item and all of it's siblings will be checked. + * - [ ] Parent + * - [ ] Child 1 + * - [ ] Child 2 + * When the user checks Parent, the tree will look like this: + * - [x] Parent + * - [x] Child 1 + * - [x] Child 2 + * + * 3. A tree item and all of it's siblings are checked. The parent will be checked. + * - [ ] Parent + * - [ ] Child 1 + * - [ ] Child 2 + * When the user checks Child 1 and Child 2, the tree will look like this: + * - [x] Parent + * - [x] Child 1 + * - [x] Child 2 + * + * 4. A tree item is unchecked. The parent will be unchecked. + * - [x] Parent + * - [x] Child 1 + * - [x] Child 2 + * When the user unchecks Child 1, the tree will look like this: + * - [ ] Parent + * - [ ] Child 1 + * - [x] Child 2 + */ + manageCheckboxStateManually?: boolean; } /** @@ -10054,18 +11179,64 @@ declare module 'vscode' { * `true` if the {@link TreeView tree view} is visible otherwise `false`. */ readonly visible: boolean; - } /** - * A class for encapsulating data transferred during a drag and drop event. + * A file associated with a {@linkcode DataTransferItem}. * - * You can use the `value` of the `DataTransferItem` to get back the object you put into it - * so long as the extension that created the `DataTransferItem` runs in the same extension host. + * Instances of this type can only be created by the editor and not by extensions. + */ + export interface DataTransferFile { + /** + * The name of the file. + */ + readonly name: string; + + /** + * The full file path of the file. + * + * May be `undefined` on web. + */ + readonly uri?: Uri; + + /** + * The full file contents of the file. + */ + data(): Thenable; + } + + /** + * Encapsulates data transferred during drag and drop operations. */ export class DataTransferItem { + /** + * Get a string representation of this item. + * + * If {@linkcode DataTransferItem.value} is an object, this returns the result of json stringifying {@linkcode DataTransferItem.value} value. + */ asString(): Thenable; + + /** + * Try getting the {@link DataTransferFile file} associated with this data transfer item. + * + * Note that the file object is only valid for the scope of the drag and drop operation. + * + * @returns The file for the data transfer or `undefined` if the item is either not a file or the + * file data cannot be accessed. + */ + asFile(): DataTransferFile | undefined; + + /** + * Custom data stored on this item. + * + * You can use `value` to share data across operations. The original object can be retrieved so long as the extension that + * created the `DataTransferItem` runs in the same extension host. + */ readonly value: any; + + /** + * @param value Custom data stored on this item. Can be retrieved using {@linkcode DataTransferItem.value}. + */ constructor(value: any); } @@ -10076,30 +11247,39 @@ declare module 'vscode' { * data transfer. These additional mime types will only be included in the `handleDrop` when the the drag was initiated from * an element in the same drag and drop controller. */ - export class DataTransfer { + export class DataTransfer implements Iterable<[mimeType: string, item: DataTransferItem]> { /** * Retrieves the data transfer item for a given mime type. * * @param mimeType The mime type to get the data transfer item for, such as `text/plain` or `image/png`. + * Mimes type look ups are case-insensitive. * * Special mime types: - * - `text/uri-list` — A string with `toString()`ed Uris separated by newlines. To specify a cursor position in the file, + * - `text/uri-list` — A string with `toString()`ed Uris separated by `\r\n`. To specify a cursor position in the file, * set the Uri's fragment to `L3,5`, where 3 is the line number and 5 is the column number. */ get(mimeType: string): DataTransferItem | undefined; /** * Sets a mime type to data transfer item mapping. - * @param mimeType The mime type to set the data for. + * + * @param mimeType The mime type to set the data for. Mimes types stored in lower case, with case-insensitive looks up. * @param value The data transfer item for the given mime type. */ set(mimeType: string, value: DataTransferItem): void; /** * Allows iteration through the data transfer items. + * * @param callbackfn Callback for iteration through the data transfer items. + * @param thisArg The `this` context used when invoking the handler function. + */ + forEach(callbackfn: (item: DataTransferItem, mimeType: string, dataTransfer: DataTransfer) => void, thisArg?: any): void; + + /** + * Get a new iterator with the `[mime, item]` pairs for each element in this data transfer. */ - forEach(callbackfn: (value: DataTransferItem, key: string) => void): void; + [Symbol.iterator](): IterableIterator<[mimeType: string, item: DataTransferItem]>; } /** @@ -10115,6 +11295,8 @@ declare module 'vscode' { * This includes drops from within the same tree. * The mime type of a tree is recommended to be of the format `application/vnd.code.tree.`. * + * Use the special `files` mime type to support all types of dropped files {@link DataTransferFile files}, regardless of the file's actual mime type. + * * To learn the mime type of a dragged item: * 1. Set up your `DragAndDropController` * 2. Use the Developer: Set Log Level... command to set the level to "Debug" @@ -10141,7 +11323,7 @@ declare module 'vscode' { * tree objects in a data transfer. See the documentation for `DataTransferItem` for how best to take advantage of this. * * To add a data transfer item that can be dragged into the editor, use the application specific mime type "text/uri-list". - * The data for "text/uri-list" should be a string with `toString()`ed Uris separated by newlines. To specify a cursor position in the file, + * The data for "text/uri-list" should be a string with `toString()`ed Uris separated by `\r\n`. To specify a cursor position in the file, * set the Uri's fragment to `L3,5`, where 3 is the line number and 5 is the column number. * * @param source The source items for the drag and drop operation. @@ -10162,6 +11344,32 @@ declare module 'vscode' { handleDrop?(target: T | undefined, dataTransfer: DataTransfer, token: CancellationToken): Thenable | void; } + /** + * A badge presenting a value for a view + */ + export interface ViewBadge { + + /** + * A label to present in tooltip for the badge. + */ + readonly tooltip: string; + + /** + * The value to present in the badge. + */ + readonly value: number; + } + + /** + * An event describing the change in a tree item's checkbox state. + */ + export interface TreeCheckboxChangeEvent { + /** + * The items that were checked or unchecked. + */ + readonly items: ReadonlyArray<[T, TreeItemCheckboxState]>; + } + /** * Represents a Tree view */ @@ -10197,6 +11405,11 @@ declare module 'vscode' { */ readonly onDidChangeVisibility: Event; + /** + * An event to signal that an element or root has either been checked or unchecked. + */ + readonly onDidChangeCheckboxState: Event>; + /** * An optional human-readable message that will be rendered in the view. * Setting the message to null, undefined, or empty string will remove the message from the view. @@ -10215,6 +11428,12 @@ declare module 'vscode' { */ description?: string; + /** + * The badge to display for this TreeView. + * To remove the badge, set to undefined. + */ + badge?: ViewBadge | undefined; + /** * Reveals the given element in the tree view. * If the tree view is not visible then the tree view is shown and element is revealed. @@ -10223,11 +11442,24 @@ declare module 'vscode' { * In order to not to select, set the option `select` to `false`. * In order to focus, set the option `focus` to `true`. * In order to expand the revealed element, set the option `expand` to `true`. To expand recursively set `expand` to the number of levels to expand. - * **NOTE:** You can expand only to 3 levels maximum. * - * **NOTE:** The {@link TreeDataProvider} that the `TreeView` {@link window.createTreeView is registered with} with must implement {@link TreeDataProvider.getParent getParent} method to access this API. + * * *NOTE:* You can expand only to 3 levels maximum. + * * *NOTE:* The {@link TreeDataProvider} that the `TreeView` {@link window.createTreeView is registered with} with must implement {@link TreeDataProvider.getParent getParent} method to access this API. */ - reveal(element: T, options?: { select?: boolean; focus?: boolean; expand?: boolean | number }): Thenable; + reveal(element: T, options?: { + /** + * If true, then the element will be selected. + */ + select?: boolean; + /** + * If true, then the element will be focused. + */ + focus?: boolean; + /** + * If true, then the element will be expanded. If a number is passed, then up to that number of levels of children will be expanded + */ + expand?: boolean | number; + }): Thenable; } /** @@ -10245,7 +11477,7 @@ declare module 'vscode' { * Get {@link TreeItem} representation of the `element` * * @param element The element for which {@link TreeItem} representation is asked for. - * @return TreeItem representation of the element. + * @returns TreeItem representation of the element. */ getTreeItem(element: T): TreeItem | Thenable; @@ -10253,7 +11485,7 @@ declare module 'vscode' { * Get the children of `element` or root if no element is passed. * * @param element The element from which the provider gets children. Can be `undefined`. - * @return Children of `element` or root if no element is passed. + * @returns Children of `element` or root if no element is passed. */ getChildren(element?: T): ProviderResult; @@ -10264,7 +11496,7 @@ declare module 'vscode' { * **NOTE:** This method should be implemented in order to access {@link TreeView.reveal reveal} API. * * @param element The element for which the parent has to be returned. - * @return Parent of `element`. + * @returns Parent of `element`. */ getParent?(element: T): ProviderResult; @@ -10286,12 +11518,15 @@ declare module 'vscode' { * @param item Undefined properties of `item` should be set then `item` should be returned. * @param element The object associated with the TreeItem. * @param token A cancellation token. - * @return The resolved tree item or a thenable that resolves to such. It is OK to return the given + * @returns The resolved tree item or a thenable that resolves to such. It is OK to return the given * `item`. When no result is returned, the given `item` will be used. */ resolveTreeItem?(item: TreeItem, element: T, token: CancellationToken): ProviderResult; } + /** + * A tree item is an UI element of the tree. Tree items are created by the {@link TreeDataProvider data provider}. + */ export class TreeItem { /** * A human-readable string describing this item. When `falsy`, it is derived from {@link TreeItem.resourceUri resourceUri}. @@ -10310,7 +11545,16 @@ declare module 'vscode' { * When `falsy`, {@link ThemeIcon.Folder Folder Theme Icon} is assigned, if item is collapsible otherwise {@link ThemeIcon.File File Theme Icon}. * When a file or folder {@link ThemeIcon} is specified, icon is derived from the current file icon theme for the specified theme icon using {@link TreeItem.resourceUri resourceUri} (if provided). */ - iconPath?: string | Uri | { light: string | Uri; dark: string | Uri } | ThemeIcon; + iconPath?: string | Uri | { + /** + * The icon path for the light theme. + */ + light: string | Uri; + /** + * The icon path for the dark theme. + */ + dark: string | Uri; + } | ThemeIcon; /** * A human-readable string which is rendered less prominent. @@ -10372,6 +11616,25 @@ declare module 'vscode' { */ accessibilityInformation?: AccessibilityInformation; + /** + * {@link TreeItemCheckboxState TreeItemCheckboxState} of the tree item. + * {@link TreeDataProvider.onDidChangeTreeData onDidChangeTreeData} should be fired when {@link TreeItem.checkboxState checkboxState} changes. + */ + checkboxState?: TreeItemCheckboxState | { + /** + * The {@link TreeItemCheckboxState} of the tree item + */ + readonly state: TreeItemCheckboxState; + /** + * A tooltip for the checkbox + */ + readonly tooltip?: string; + /** + * Accessibility information used when screen readers interact with this checkbox + */ + readonly accessibilityInformation?: AccessibilityInformation; + }; + /** * @param label A human-readable string describing this item * @param collapsibleState {@link TreeItemCollapsibleState} of the tree item. Default is {@link TreeItemCollapsibleState.None} @@ -10420,6 +11683,20 @@ declare module 'vscode' { highlights?: [number, number][]; } + /** + * Checkbox state of the tree item + */ + export enum TreeItemCheckboxState { + /** + * Determines an item is unchecked + */ + Unchecked = 0, + /** + * Determines an item is checked + */ + Checked = 1 + } + /** * Value-object describing what options a terminal should use. */ @@ -10454,7 +11731,7 @@ declare module 'vscode' { * Whether the terminal process environment should be exactly as provided in * `TerminalOptions.env`. When this is false (default), the environment will be based on the * window's environment and also apply configured platform settings like - * `terminal.integrated.windows.env` on top. When this is true, the complete environment + * `terminal.integrated.env.windows` on top. When this is true, the complete environment * must be provided as nothing will be inherited from the process or any configuration. */ strictEnv?: boolean; @@ -10464,7 +11741,7 @@ declare module 'vscode' { * until `Terminal.show` is called. The typical usage for this is when you need to run * something that may need interactivity but only want to tell the user about it when * interaction is needed. Note that the terminals will still be exposed to all extensions - * as normal. + * as normal. The hidden terminals will not be restored when the workspace is next opened. */ hideFromUser?: boolean; @@ -10478,9 +11755,18 @@ declare module 'vscode' { /** * The icon path or {@link ThemeIcon} for the terminal. */ - iconPath?: Uri | { light: Uri; dark: Uri } | ThemeIcon; - - /** + iconPath?: Uri | { + /** + * The icon path for the light theme. + */ + light: Uri; + /** + * The icon path for the dark theme. + */ + dark: Uri; + } | ThemeIcon; + + /** * The icon {@link ThemeColor} for the terminal. * The `terminal.ansi*` theme keys are * recommended for the best contrast and consistency across themes. @@ -10517,7 +11803,16 @@ declare module 'vscode' { /** * The icon path or {@link ThemeIcon} for the terminal. */ - iconPath?: Uri | { light: Uri; dark: Uri } | ThemeIcon; + iconPath?: Uri | { + /** + * The icon path for the light theme. + */ + light: Uri; + /** + * The icon path for the dark theme. + */ + dark: Uri; + } | ThemeIcon; /** * The icon {@link ThemeColor} for the terminal. @@ -10612,7 +11907,7 @@ declare module 'vscode' { * **Example:** Exit the terminal when "y" is pressed, otherwise show a notification. * ```typescript * const writeEmitter = new vscode.EventEmitter(); - * const closeEmitter = new vscode.EventEmitter(); + * const closeEmitter = new vscode.EventEmitter(); * const pty: vscode.Pseudoterminal = { * onDidWrite: writeEmitter.event, * onDidClose: closeEmitter.event, @@ -10625,7 +11920,8 @@ declare module 'vscode' { * closeEmitter.fire(); * } * }; - * vscode.window.createTerminal({ name: 'Exit example', pty }); + * const terminal = vscode.window.createTerminal({ name: 'Exit example', pty }); + * terminal.show(true); * ``` */ onDidClose?: Event; @@ -10728,6 +12024,41 @@ declare module 'vscode' { * without providing an exit code. */ readonly code: number | undefined; + + /** + * The reason that triggered the exit of a terminal. + */ + readonly reason: TerminalExitReason; + } + + /** + * Terminal exit reason kind. + */ + export enum TerminalExitReason { + /** + * Unknown reason. + */ + Unknown = 0, + + /** + * The window closed/reloaded. + */ + Shutdown = 1, + + /** + * The shell process exited. + */ + Process = 2, + + /** + * The user closed the terminal. + */ + User = 3, + + /** + * An extension disposed the terminal. + */ + Extension = 4, } /** @@ -10748,6 +12079,23 @@ declare module 'vscode' { Prepend = 3 } + /** + * Options applied to the mutator. + */ + export interface EnvironmentVariableMutatorOptions { + /** + * Apply to the environment just before the process is created. Defaults to false. + */ + applyAtProcessCreation?: boolean; + + /** + * Apply to the environment in the shell integration script. Note that this _will not_ apply + * the mutator if shell integration is disabled or not working for some reason. Defaults to + * false. + */ + applyAtShellIntegration?: boolean; + } + /** * A type of mutation and its value to be applied to an environment variable. */ @@ -10761,12 +12109,17 @@ declare module 'vscode' { * The value to use for the variable. */ readonly value: string; + + /** + * Options applied to the mutator. + */ + readonly options: EnvironmentVariableMutatorOptions; } /** * A collection of mutations that an extension can apply to a process environment. */ - export interface EnvironmentVariableCollection { + export interface EnvironmentVariableCollection extends Iterable<[variable: string, mutator: EnvironmentVariableMutator]> { /** * Whether the collection should be cached for the workspace and applied to the terminal * across window reloads. When true the collection will be active immediately such when the @@ -10776,6 +12129,12 @@ declare module 'vscode' { */ persistent: boolean; + /** + * A description for the environment variable collection, this will be used to describe the + * changes in the UI. + */ + description: string | MarkdownString | undefined; + /** * Replace an environment variable with a value. * @@ -10784,8 +12143,10 @@ declare module 'vscode' { * * @param variable The variable to replace. * @param value The value to replace the variable with. + * @param options Options applied to the mutator, when no options are provided this will + * default to `{ applyAtProcessCreation: true }`. */ - replace(variable: string, value: string): void; + replace(variable: string, value: string, options?: EnvironmentVariableMutatorOptions): void; /** * Append a value to an environment variable. @@ -10795,8 +12156,10 @@ declare module 'vscode' { * * @param variable The variable to append to. * @param value The value to append to the variable. + * @param options Options applied to the mutator, when no options are provided this will + * default to `{ applyAtProcessCreation: true }`. */ - append(variable: string, value: string): void; + append(variable: string, value: string, options?: EnvironmentVariableMutatorOptions): void; /** * Prepend a value to an environment variable. @@ -10806,8 +12169,10 @@ declare module 'vscode' { * * @param variable The variable to prepend. * @param value The value to prepend to the variable. + * @param options Options applied to the mutator, when no options are provided this will + * default to `{ applyAtProcessCreation: true }`. */ - prepend(variable: string, value: string): void; + prepend(variable: string, value: string, options?: EnvironmentVariableMutatorOptions): void; /** * Gets the mutator that this collection applies to a variable, if any. @@ -10837,6 +12202,39 @@ declare module 'vscode' { clear(): void; } + /** + * A collection of mutations that an extension can apply to a process environment. Applies to all scopes. + */ + export interface GlobalEnvironmentVariableCollection extends EnvironmentVariableCollection { + /** + * Gets scope-specific environment variable collection for the extension. This enables alterations to + * terminal environment variables solely within the designated scope, and is applied in addition to (and + * after) the global collection. + * + * Each object obtained through this method is isolated and does not impact objects for other scopes, + * including the global collection. + * + * @param scope The scope to which the environment variable collection applies to. + * + * If a scope parameter is omitted, collection applicable to all relevant scopes for that parameter is + * returned. For instance, if the 'workspaceFolder' parameter is not specified, the collection that applies + * across all workspace folders will be returned. + * + * @returns Environment variable collection for the passed in scope. + */ + getScoped(scope: EnvironmentVariableScope): EnvironmentVariableCollection; + } + + /** + * The scope object to which the environment variable collection applies. + */ + export interface EnvironmentVariableScope { + /** + * Any specific workspace folder to get collection for. + */ + workspaceFolder?: WorkspaceFolder; + } + /** * A location in the editor at which progress information can be shown. It depends on the * location how progress is visually represented. @@ -10871,7 +12269,12 @@ declare module 'vscode' { /** * The location at which progress should show. */ - location: ProgressLocation | { viewId: string }; + location: ProgressLocation | { + /** + * The identifier of a view for which progress should be shown. + */ + viewId: string; + }; /** * A human-readable string which will be used to describe the @@ -10997,7 +12400,7 @@ declare module 'vscode' { value: string; /** - * Optional placeholder in the filter text. + * Optional placeholder shown in the filter textbox when no filter has been entered. */ placeholder: string | undefined; @@ -11048,7 +12451,7 @@ declare module 'vscode' { */ matchOnDetail: boolean; - /* + /** * An optional flag to maintain the scroll position of the quick pick when the quick pick items are updated. Defaults to false. */ keepScrollPosition?: boolean; @@ -11089,7 +12492,18 @@ declare module 'vscode' { value: string; /** - * Optional placeholder in the filter text. + * Selection range in the input value. Defined as tuple of two number where the + * first is the inclusive start index and the second the exclusive end index. When `undefined` the whole + * pre-filled value will be selected, when empty (start equals end) only the cursor will be set, + * otherwise the defined range will be selected. + * + * This property does not get updated when the user types or makes a selection, + * but it can be updated by the extension. + */ + valueSelection: readonly [number, number] | undefined; + + /** + * Optional placeholder shown when no value has been input. */ placeholder: string | undefined; @@ -11139,7 +12553,16 @@ declare module 'vscode' { /** * Icon for the button. */ - readonly iconPath: Uri | { light: Uri; dark: Uri } | ThemeIcon; + readonly iconPath: Uri | { + /** + * The icon path for the light theme. + */ + light: Uri; + /** + * The icon path for the dark theme. + */ + dark: Uri; + } | ThemeIcon; /** * An optional tooltip. @@ -11203,6 +12626,9 @@ declare module 'vscode' { readonly text: string; } + /** + * Reasons for why a text document has changed. + */ export enum TextDocumentChangeReason { /** The text change is caused by an undo operation. */ Undo = 1, @@ -11370,7 +12796,7 @@ declare module 'vscode' { * An event that is fired when files are going to be deleted. * * To make modifications to the workspace before the files are deleted, - * call the {@link FileWillCreateEvent.waitUntil `waitUntil}-function with a + * call the {@link FileWillCreateEvent.waitUntil `waitUntil`}-function with a * thenable that resolves to a {@link WorkspaceEdit workspace edit}. */ export interface FileWillDeleteEvent { @@ -11430,7 +12856,7 @@ declare module 'vscode' { * An event that is fired when files are going to be renamed. * * To make modifications to the workspace before the files are renamed, - * call the {@link FileWillCreateEvent.waitUntil `waitUntil}-function with a + * call the {@link FileWillCreateEvent.waitUntil `waitUntil`}-function with a * thenable that resolves to a {@link WorkspaceEdit workspace edit}. */ export interface FileWillRenameEvent { @@ -11443,7 +12869,16 @@ declare module 'vscode' { /** * The files that are going to be renamed. */ - readonly files: ReadonlyArray<{ readonly oldUri: Uri; readonly newUri: Uri }>; + readonly files: ReadonlyArray<{ + /** + * The old uri of a file. + */ + readonly oldUri: Uri; + /** + * The new uri of a file. + */ + readonly newUri: Uri; + }>; /** * Allows to pause the event and to apply a {@link WorkspaceEdit workspace edit}. @@ -11483,7 +12918,16 @@ declare module 'vscode' { /** * The files that got renamed. */ - readonly files: ReadonlyArray<{ readonly oldUri: Uri; readonly newUri: Uri }>; + readonly files: ReadonlyArray<{ + /** + * The old uri of a file. + */ + readonly oldUri: Uri; + /** + * The new uri of a file. + */ + readonly newUri: Uri; + }>; } /** @@ -11632,7 +13076,7 @@ declare module 'vscode' { * * returns the *input* when the given uri is a workspace folder itself * * @param uri An uri. - * @return A workspace folder or `undefined` + * @returns A workspace folder or `undefined` */ export function getWorkspaceFolder(uri: Uri): WorkspaceFolder | undefined; @@ -11646,7 +13090,7 @@ declare module 'vscode' { * @param includeWorkspaceFolder When `true` and when the given path is contained inside a * workspace folder the name of the workspace is prepended. Defaults to `true` when there are * multiple workspace folders and `false` otherwise. - * @return A path relative to the root or the input. + * @returns A path relative to the root or the input. */ export function asRelativePath(pathOrUri: string | Uri, includeWorkspaceFolder?: boolean): string; @@ -11655,9 +13099,11 @@ declare module 'vscode' { * by an optional set of `workspaceFoldersToAdd` on the `vscode.workspace.workspaceFolders` array. This "splice" * behavior can be used to add, remove and change workspace folders in a single operation. * - * If the first workspace folder is added, removed or changed, the currently executing extensions (including the - * one that called this method) will be terminated and restarted so that the (deprecated) `rootPath` property is - * updated to point to the first workspace folder. + * **Note:** in some cases calling this method may result in the currently executing extensions (including the + * one that called this method) to be terminated and restarted. For example when the first workspace folder is + * added, removed or changed the (deprecated) `rootPath` property is updated to point to the first workspace + * folder. Another case is when transitioning from an empty or single-folder workspace into a multi-folder + * workspace (see also: https://code.visualstudio.com/docs/editor/workspaces). * * Use the {@linkcode onDidChangeWorkspaceFolders onDidChangeWorkspaceFolders()} event to get notified when the * workspace folders have been updated. @@ -11688,10 +13134,19 @@ declare module 'vscode' { * @param deleteCount the optional number of workspace folders to remove. * @param workspaceFoldersToAdd the optional variable set of workspace folders to add in place of the deleted ones. * Each workspace is identified with a mandatory URI and an optional name. - * @return true if the operation was successfully started and false otherwise if arguments were used that would result + * @returns true if the operation was successfully started and false otherwise if arguments were used that would result * in invalid workspace folder state (e.g. 2 folders with the same URI). */ - export function updateWorkspaceFolders(start: number, deleteCount: number | undefined | null, ...workspaceFoldersToAdd: { readonly uri: Uri; readonly name?: string }[]): boolean; + export function updateWorkspaceFolders(start: number, deleteCount: number | undefined | null, ...workspaceFoldersToAdd: { + /** + * The uri of a workspace folder that's to be added. + */ + readonly uri: Uri; + /** + * The name of a workspace folder that's to be added. + */ + readonly name?: string; + }[]): boolean; /** * Creates a file system watcher that is notified on file events (create, change, delete) @@ -11701,17 +13156,12 @@ declare module 'vscode' { * for file changes recursively. * * Additional paths can be added for file watching by providing a {@link RelativePattern} with - * a `base` path to watch. If the `pattern` is complex (e.g. contains `**` or path segments), - * the path will be watched recursively and otherwise will be watched non-recursively (i.e. only - * changes to the first level of the path will be reported). - * - * *Note* that requests for recursive file watchers for a `base` path that is inside the opened - * workspace are ignored given all opened {@link workspace.workspaceFolders workspace folders} are - * watched for file changes recursively by default. Non-recursive file watchers however are always - * supported, even inside the opened workspace because they allow to bypass the configured settings - * for excludes (`files.watcherExclude`). If you need to watch in a location that is typically - * excluded (for example `node_modules` or `.git` folder), then you can use a non-recursive watcher - * in the workspace for this purpose. + * a `base` path to watch. If the path is a folder and the `pattern` is complex (e.g. contains + * `**` or path segments), it will be watched recursively and otherwise will be watched + * non-recursively (i.e. only changes to the first level of the path will be reported). + * + * *Note* that paths must exist in the file system to be watched. File watching may stop when + * the watched path is renamed or deleted. * * If possible, keep the use of recursive watchers to a minimum because recursive file watching * is quite resource intense. @@ -11782,7 +13232,7 @@ declare module 'vscode' { * If you want to monitor file events across all opened workspace folders: * * ```ts - * vscode.workspace.createFileSystemWatcher('**​/*.js')); + * vscode.workspace.createFileSystemWatcher('**​/*.js'); * ``` * * *Note:* the array of workspace folders can be empty if no workspace is opened (empty window). @@ -11812,7 +13262,7 @@ declare module 'vscode' { * @param ignoreCreateEvents Ignore when files have been created. * @param ignoreChangeEvents Ignore when files have been changed. * @param ignoreDeleteEvents Ignore when files have been deleted. - * @return A new file system watcher instance. Must be disposed when no longer needed. + * @returns A new file system watcher instance. Must be disposed when no longer needed. */ export function createFileSystemWatcher(globPattern: GlobPattern, ignoreCreateEvents?: boolean, ignoreChangeEvents?: boolean, ignoreDeleteEvents?: boolean): FileSystemWatcher; @@ -11830,16 +13280,39 @@ declare module 'vscode' { * but not `search.exclude`) will apply. When `null`, no excludes will apply. * @param maxResults An upper-bound for the result. * @param token A token that can be used to signal cancellation to the underlying search engine. - * @return A thenable that resolves to an array of resource identifiers. Will return no results if no + * @returns A thenable that resolves to an array of resource identifiers. Will return no results if no * {@link workspace.workspaceFolders workspace folders} are opened. */ export function findFiles(include: GlobPattern, exclude?: GlobPattern | null, maxResults?: number, token?: CancellationToken): Thenable; + /** + * Saves the editor identified by the given resource and returns the resulting resource or `undefined` + * if save was not successful or no editor with the given resource was found. + * + * **Note** that an editor with the provided resource must be opened in order to be saved. + * + * @param uri the associated uri for the opened editor to save. + * @returns A thenable that resolves when the save operation has finished. + */ + export function save(uri: Uri): Thenable; + + /** + * Saves the editor identified by the given resource to a new file name as provided by the user and + * returns the resulting resource or `undefined` if save was not successful or cancelled or no editor + * with the given resource was found. + * + * **Note** that an editor with the provided resource must be opened in order to be saved as. + * + * @param uri the associated uri for the opened editor to save as. + * @returns A thenable that resolves when the save-as operation has finished. + */ + export function saveAs(uri: Uri): Thenable; + /** * Save all dirty files. * * @param includeUntitled Also save files that have been created during this session. - * @return A thenable that resolves when the files have been saved. Will return `false` + * @returns A thenable that resolves when the files have been saved. Will return `false` * for any file that failed to save. */ export function saveAll(includeUntitled?: boolean): Thenable; @@ -11858,9 +13331,10 @@ declare module 'vscode' { * not be attempted, when a single edit fails. * * @param edit A workspace edit. - * @return A thenable that resolves when the edit could be applied. + * @param metadata Optional {@link WorkspaceEditMetadata metadata} for the edit. + * @returns A thenable that resolves when the edit could be applied. */ - export function applyEdit(edit: WorkspaceEdit): Thenable; + export function applyEdit(edit: WorkspaceEdit, metadata?: WorkspaceEditMetadata): Thenable; /** * All text documents currently known to the editor. @@ -11884,18 +13358,18 @@ declare module 'vscode' { * {@linkcode workspace.onDidCloseTextDocument onDidClose}-event can occur at any time after opening it. * * @param uri Identifies the resource to open. - * @return A promise that resolves to a {@link TextDocument document}. + * @returns A promise that resolves to a {@link TextDocument document}. */ export function openTextDocument(uri: Uri): Thenable; /** - * A short-hand for `openTextDocument(Uri.file(fileName))`. + * A short-hand for `openTextDocument(Uri.file(path))`. * * @see {@link workspace.openTextDocument} - * @param fileName A name of a file on disk. - * @return A promise that resolves to a {@link TextDocument document}. + * @param path A path of a file on disk. + * @returns A promise that resolves to a {@link TextDocument document}. */ - export function openTextDocument(fileName: string): Thenable; + export function openTextDocument(path: string): Thenable; /** * Opens an untitled text document. The editor will prompt the user for a file @@ -11903,9 +13377,18 @@ declare module 'vscode' { * specify the *language* and/or the *content* of the document. * * @param options Options to control how the document will be created. - * @return A promise that resolves to a {@link TextDocument document}. + * @returns A promise that resolves to a {@link TextDocument document}. */ - export function openTextDocument(options?: { language?: string; content?: string }): Thenable; + export function openTextDocument(options?: { + /** + * The {@link TextDocument.languageId language} of the document. + */ + language?: string; + /** + * The initial contents of the document. + */ + content?: string; + }): Thenable; /** * Register a text document content provider. @@ -11914,7 +13397,7 @@ declare module 'vscode' { * * @param scheme The uri-scheme to register for. * @param provider A content provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerTextDocumentContentProvider(scheme: string, provider: TextDocumentContentProvider): Disposable; @@ -11977,11 +13460,11 @@ declare module 'vscode' { export const notebookDocuments: readonly NotebookDocument[]; /** - * Open a notebook. Will return early if this notebook is already {@link notebook.notebookDocuments loaded}. Otherwise - * the notebook is loaded and the {@linkcode notebook.onDidOpenNotebookDocument onDidOpenNotebookDocument}-event fires. + * Open a notebook. Will return early if this notebook is already {@link notebookDocuments loaded}. Otherwise + * the notebook is loaded and the {@linkcode onDidOpenNotebookDocument}-event fires. * * *Note* that the lifecycle of the returned notebook is owned by the editor and not by the extension. That means an - * {@linkcode notebook.onDidCloseNotebookDocument onDidCloseNotebookDocument}-event can occur at any time after. + * {@linkcode onDidCloseNotebookDocument}-event can occur at any time after. * * *Note* that opening a notebook does not show a notebook editor. This function only returns a notebook document which * can be shown in a notebook editor but it can also be used for other things. @@ -12007,6 +13490,21 @@ declare module 'vscode' { */ export const onDidChangeNotebookDocument: Event; + /** + * An event that is emitted when a {@link NotebookDocument notebook document} will be saved to disk. + * + * *Note 1:* Subscribers can delay saving by registering asynchronous work. For the sake of data integrity the editor + * might save without firing this event. For instance when shutting down with dirty files. + * + * *Note 2:* Subscribers are called sequentially and they can {@link NotebookDocumentWillSaveEvent.waitUntil delay} saving + * by registering asynchronous work. Protection against misbehaving listeners is implemented as such: + * * there is an overall time budget that all listeners share and if that is exhausted no further listener is called + * * listeners that take a long time or produce errors frequently will not be called anymore + * + * The current thresholds are 1.5 seconds as overall time budget and a listener can misbehave 3 times before being ignored. + */ + export const onWillSaveNotebookDocument: Event; + /** * An event that is emitted when a {@link NotebookDocument notebook} is saved. */ @@ -12021,7 +13519,7 @@ declare module 'vscode' { * @param notebookType A notebook. * @param serializer A notebook serializer. * @param options Optional context options that define what parts of a notebook should be persisted - * @return A {@link Disposable} that unregisters this serializer when being disposed. + * @returns A {@link Disposable} that unregisters this serializer when being disposed. */ export function registerNotebookSerializer(notebookType: string, serializer: NotebookSerializer, options?: NotebookDocumentContentOptions): Disposable; @@ -12121,7 +13619,7 @@ declare module 'vscode' { * * @param section A dot-separated identifier. * @param scope A scope for which the configuration is asked for. - * @return The full configuration or a subset. + * @returns The full configuration or a subset. */ export function getConfiguration(section?: string, scope?: ConfigurationScope | null): WorkspaceConfiguration; @@ -12137,7 +13635,7 @@ declare module 'vscode' { * * @param type The task kind type this provider is registered for. * @param provider A task provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerTaskProvider(type: string, provider: TaskProvider): Disposable; @@ -12150,9 +13648,19 @@ declare module 'vscode' { * @param scheme The uri-{@link Uri.scheme scheme} the provider registers for. * @param provider The filesystem provider. * @param options Immutable metadata about the provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ - export function registerFileSystemProvider(scheme: string, provider: FileSystemProvider, options?: { readonly isCaseSensitive?: boolean; readonly isReadonly?: boolean }): Disposable; + export function registerFileSystemProvider(scheme: string, provider: FileSystemProvider, options?: { + /** + * Whether the file system provider use case sensitive compare for {@link Uri.path paths} + */ + readonly isCaseSensitive?: boolean; + /** + * Whether the file system provider is readonly, no modifications like write, delete, create are possible. + * If a {@link MarkdownString} is given, it will be shown as the reason why the file system is readonly. + */ + readonly isReadonly?: boolean | MarkdownString; + }): Disposable; /** * When true, the user has explicitly trusted the contents of the workspace. @@ -12171,7 +13679,16 @@ declare module 'vscode' { * a '{@link TextDocument}' or * a '{@link WorkspaceFolder}' */ - export type ConfigurationScope = Uri | TextDocument | WorkspaceFolder | { uri?: Uri; languageId: string }; + export type ConfigurationScope = Uri | TextDocument | WorkspaceFolder | { + /** + * The uri of a {@link TextDocument text document} + */ + uri?: Uri; + /** + * The language of a text document + */ + languageId: string; + }; /** * An event describing the change in Configuration @@ -12184,7 +13701,7 @@ declare module 'vscode' { * * @param section Configuration name, supports _dotted_ names. * @param scope A scope in which to check. - * @return `true` if the given section has changed. + * @returns `true` if the given section has changed. */ affectsConfiguration(section: string, scope?: ConfigurationScope): boolean; } @@ -12221,7 +13738,7 @@ declare module 'vscode' { /** * Return the identifiers of all known languages. - * @return Promise resolving to an array of identifier strings. + * @returns Promise resolving to an array of identifier strings. */ export function getLanguages(): Thenable; @@ -12281,7 +13798,7 @@ declare module 'vscode' { * * @param selector A document selector. * @param document A text document. - * @return A number `>0` when the selector matches and `0` when the selector does not match. + * @returns A number `>0` when the selector matches and `0` when the selector does not match. */ export function match(selector: DocumentSelector, document: TextDocument): number; @@ -12310,7 +13827,7 @@ declare module 'vscode' { * Create a diagnostics collection. * * @param name The {@link DiagnosticCollection.name name} of the collection. - * @return A new diagnostic collection. + * @returns A new diagnostic collection. */ export function createDiagnosticCollection(name?: string): DiagnosticCollection; @@ -12319,6 +13836,7 @@ declare module 'vscode' { * * @param id The identifier of the item. * @param selector The document selector that defines for what editors the item shows. + * @returns A new language status item. */ export function createLanguageStatusItem(id: string, selector: DocumentSelector): LanguageStatusItem; @@ -12339,7 +13857,7 @@ declare module 'vscode' { * @param selector A selector that defines the documents this provider is applicable to. * @param provider A completion provider. * @param triggerCharacters Trigger completion when the user types one of the characters. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerCompletionItemProvider(selector: DocumentSelector, provider: CompletionItemProvider, ...triggerCharacters: string[]): Disposable; @@ -12352,7 +13870,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider An inline completion provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerInlineCompletionItemProvider(selector: DocumentSelector, provider: InlineCompletionItemProvider): Disposable; @@ -12366,7 +13884,7 @@ declare module 'vscode' { * @param selector A selector that defines the documents this provider is applicable to. * @param provider A code action provider. * @param metadata Metadata about the kind of code actions the provider provides. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerCodeActionsProvider(selector: DocumentSelector, provider: CodeActionProvider, metadata?: CodeActionProviderMetadata): Disposable; @@ -12379,7 +13897,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A code lens provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerCodeLensProvider(selector: DocumentSelector, provider: CodeLensProvider): Disposable; @@ -12392,7 +13910,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A definition provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerDefinitionProvider(selector: DocumentSelector, provider: DefinitionProvider): Disposable; @@ -12405,7 +13923,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider An implementation provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerImplementationProvider(selector: DocumentSelector, provider: ImplementationProvider): Disposable; @@ -12418,7 +13936,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A type definition provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerTypeDefinitionProvider(selector: DocumentSelector, provider: TypeDefinitionProvider): Disposable; @@ -12431,7 +13949,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A declaration provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerDeclarationProvider(selector: DocumentSelector, provider: DeclarationProvider): Disposable; @@ -12444,7 +13962,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A hover provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerHoverProvider(selector: DocumentSelector, provider: HoverProvider): Disposable; @@ -12456,7 +13974,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider An evaluatable expression provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerEvaluatableExpressionProvider(selector: DocumentSelector, provider: EvaluatableExpressionProvider): Disposable; @@ -12471,7 +13989,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider An inline values provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerInlineValuesProvider(selector: DocumentSelector, provider: InlineValuesProvider): Disposable; @@ -12484,7 +14002,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A document highlight provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerDocumentHighlightProvider(selector: DocumentSelector, provider: DocumentHighlightProvider): Disposable; @@ -12498,7 +14016,7 @@ declare module 'vscode' { * @param selector A selector that defines the documents this provider is applicable to. * @param provider A document symbol provider. * @param metaData metadata about the provider - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerDocumentSymbolProvider(selector: DocumentSelector, provider: DocumentSymbolProvider, metaData?: DocumentSymbolProviderMetadata): Disposable; @@ -12510,7 +14028,7 @@ declare module 'vscode' { * a failure of the whole operation. * * @param provider A workspace symbol provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerWorkspaceSymbolProvider(provider: WorkspaceSymbolProvider): Disposable; @@ -12523,7 +14041,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A reference provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerReferenceProvider(selector: DocumentSelector, provider: ReferenceProvider): Disposable; @@ -12536,7 +14054,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A rename provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerRenameProvider(selector: DocumentSelector, provider: RenameProvider): Disposable; @@ -12549,7 +14067,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A document semantic tokens provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerDocumentSemanticTokensProvider(selector: DocumentSelector, provider: DocumentSemanticTokensProvider, legend: SemanticTokensLegend): Disposable; @@ -12568,7 +14086,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A document range semantic tokens provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerDocumentRangeSemanticTokensProvider(selector: DocumentSelector, provider: DocumentRangeSemanticTokensProvider, legend: SemanticTokensLegend): Disposable; @@ -12581,7 +14099,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A document formatting edit provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerDocumentFormattingEditProvider(selector: DocumentSelector, provider: DocumentFormattingEditProvider): Disposable; @@ -12598,7 +14116,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A document range formatting edit provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerDocumentRangeFormattingEditProvider(selector: DocumentSelector, provider: DocumentRangeFormattingEditProvider): Disposable; @@ -12613,7 +14131,7 @@ declare module 'vscode' { * @param provider An on type formatting edit provider. * @param firstTriggerCharacter A character on which formatting should be triggered, like `}`. * @param moreTriggerCharacter More trigger characters. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerOnTypeFormattingEditProvider(selector: DocumentSelector, provider: OnTypeFormattingEditProvider, firstTriggerCharacter: string, ...moreTriggerCharacter: string[]): Disposable; @@ -12627,10 +14145,18 @@ declare module 'vscode' { * @param selector A selector that defines the documents this provider is applicable to. * @param provider A signature help provider. * @param triggerCharacters Trigger signature help when the user types one of the characters, like `,` or `(`. - * @param metadata Information about the provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerSignatureHelpProvider(selector: DocumentSelector, provider: SignatureHelpProvider, ...triggerCharacters: string[]): Disposable; + + /** + * @see {@link languages.registerSignatureHelpProvider} + * + * @param selector A selector that defines the documents this provider is applicable to. + * @param provider A signature help provider. + * @param metadata Information about the provider. + * @returns A {@link Disposable} that unregisters this provider when being disposed. + */ export function registerSignatureHelpProvider(selector: DocumentSelector, provider: SignatureHelpProvider, metadata: SignatureHelpProviderMetadata): Disposable; /** @@ -12642,7 +14168,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A document link provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerDocumentLinkProvider(selector: DocumentSelector, provider: DocumentLinkProvider): Disposable; @@ -12655,7 +14181,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A color provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerColorProvider(selector: DocumentSelector, provider: DocumentColorProvider): Disposable; @@ -12668,7 +14194,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider An inlay hints provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerInlayHintsProvider(selector: DocumentSelector, provider: InlayHintsProvider): Disposable; @@ -12685,7 +14211,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A folding range provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerFoldingRangeProvider(selector: DocumentSelector, provider: FoldingRangeProvider): Disposable; @@ -12698,7 +14224,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A selection range provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerSelectionRangeProvider(selector: DocumentSelector, provider: SelectionRangeProvider): Disposable; @@ -12707,7 +14233,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A call hierarchy provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerCallHierarchyProvider(selector: DocumentSelector, provider: CallHierarchyProvider): Disposable; @@ -12716,7 +14242,7 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A type hierarchy provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerTypeHierarchyProvider(selector: DocumentSelector, provider: TypeHierarchyProvider): Disposable; @@ -12729,16 +14255,26 @@ declare module 'vscode' { * * @param selector A selector that defines the documents this provider is applicable to. * @param provider A linked editing range provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerLinkedEditingRangeProvider(selector: DocumentSelector, provider: LinkedEditingRangeProvider): Disposable; + /** + * Registers a new {@link DocumentDropEditProvider}. + * + * @param selector A selector that defines the documents this provider applies to. + * @param provider A drop provider. + * + * @returns A {@link Disposable} that unregisters this provider when disposed of. + */ + export function registerDocumentDropEditProvider(selector: DocumentSelector, provider: DocumentDropEditProvider): Disposable; + /** * Set a {@link LanguageConfiguration language configuration} for a language. * * @param language A language identifier like `typescript`. * @param configuration Language configuration. - * @return A {@link Disposable} that unsets this configuration. + * @returns A {@link Disposable} that unsets this configuration. */ export function setLanguageConfiguration(language: string, configuration: LanguageConfiguration): Disposable; } @@ -12820,7 +14356,13 @@ declare module 'vscode' { * An event that fires when a message is received from a renderer. */ readonly onDidReceiveMessage: Event<{ + /** + * The {@link NotebookEditor editor} that sent the message. + */ readonly editor: NotebookEditor; + /** + * The actual message. + */ readonly message: any; }>; @@ -12886,7 +14428,7 @@ declare module 'vscode' { /** * The metadata of this cell. Can be anything but must be JSON-stringifyable. */ - readonly metadata: { [key: string]: any }; + readonly metadata: { readonly [key: string]: any }; /** * The outputs of this cell. @@ -12956,7 +14498,7 @@ declare module 'vscode' { * Return the cell at the specified index. The index will be adjusted to the notebook. * * @param index - The index of the cell to retrieve. - * @return A {@link NotebookCell cell}. + * @returns A {@link NotebookCell cell}. */ cellAt(index: number): NotebookCell; @@ -12972,7 +14514,7 @@ declare module 'vscode' { /** * Save the document. The saving will be handled by the corresponding {@link NotebookSerializer serializer}. * - * @return A promise that will resolve to true when the document + * @returns A promise that will resolve to true when the document * has been saved. Will return false if the file was not dirty or when save failed. */ save(): Thenable; @@ -12986,7 +14528,7 @@ declare module 'vscode' { export interface NotebookDocumentCellChange { /** - * The affected notebook. + * The affected cell. */ readonly cell: NotebookCell; @@ -13066,6 +14608,61 @@ declare module 'vscode' { readonly cellChanges: readonly NotebookDocumentCellChange[]; } + /** + * An event that is fired when a {@link NotebookDocument notebook document} will be saved. + * + * To make modifications to the document before it is being saved, call the + * {@linkcode NotebookDocumentWillSaveEvent.waitUntil waitUntil}-function with a thenable + * that resolves to a {@link WorkspaceEdit workspace edit}. + */ + export interface NotebookDocumentWillSaveEvent { + /** + * A cancellation token. + */ + readonly token: CancellationToken; + + /** + * The {@link NotebookDocument notebook document} that will be saved. + */ + readonly notebook: NotebookDocument; + + /** + * The reason why save was triggered. + */ + readonly reason: TextDocumentSaveReason; + + /** + * Allows to pause the event loop and to apply {@link WorkspaceEdit workspace edit}. + * Edits of subsequent calls to this function will be applied in order. The + * edits will be *ignored* if concurrent modifications of the notebook document happened. + * + * *Note:* This function can only be called during event dispatch and not + * in an asynchronous manner: + * + * ```ts + * workspace.onWillSaveNotebookDocument(event => { + * // async, will *throw* an error + * setTimeout(() => event.waitUntil(promise)); + * + * // sync, OK + * event.waitUntil(promise); + * }) + * ``` + * + * @param thenable A thenable that resolves to {@link WorkspaceEdit workspace edit}. + */ + waitUntil(thenable: Thenable): void; + + /** + * Allows to pause the event loop until the provided thenable resolved. + * + * *Note:* This function can only be called during event dispatch. + * + * @param thenable A thenable that delays saving. + */ + waitUntil(thenable: Thenable): void; + } + /** * The summary of a notebook cell execution. */ @@ -13084,7 +14681,16 @@ declare module 'vscode' { /** * The times at which execution started and ended, as unix timestamps */ - readonly timing?: { readonly startTime: number; readonly endTime: number }; + readonly timing?: { + /** + * Execution start time. + */ + readonly startTime: number; + /** + * Execution end time. + */ + readonly endTime: number; + }; } /** @@ -13121,10 +14727,19 @@ declare module 'vscode' { * Derive a new range for this range. * * @param change An object that describes a change to this range. - * @return A range that reflects the given change. Will return `this` range if the change + * @returns A range that reflects the given change. Will return `this` range if the change * is not changing anything. */ - with(change: { start?: number; end?: number }): NotebookRange; + with(change: { + /** + * New start index, defaults to `this.start`. + */ + start?: number; + /** + * New end index, defaults to `this.end`. + */ + end?: number; + }): NotebookRange; } /** @@ -13332,7 +14947,7 @@ declare module 'vscode' { * * @param content Contents of a notebook file. * @param token A cancellation token. - * @return Notebook data or a thenable that resolves to such. + * @returns Notebook data or a thenable that resolves to such. */ deserializeNotebook(content: Uint8Array, token: CancellationToken): NotebookData | Thenable; @@ -13504,7 +15119,16 @@ declare module 'vscode' { * _Note_ that controller selection is persisted (by the controllers {@link NotebookController.id id}) and restored as soon as a * controller is re-created or as a notebook is {@link workspace.onDidOpenNotebookDocument opened}. */ - readonly onDidChangeSelectedNotebooks: Event<{ readonly notebook: NotebookDocument; readonly selected: boolean }>; + readonly onDidChangeSelectedNotebooks: Event<{ + /** + * The notebook for which the controller has been selected or un-selected. + */ + readonly notebook: NotebookDocument; + /** + * Whether the controller has been selected or un-selected. + */ + readonly selected: boolean; + }>; /** * A controller can set affinities for specific notebook documents. This allows a controller @@ -13573,7 +15197,7 @@ declare module 'vscode' { * * @param cell Cell for which output is cleared. Defaults to the {@link NotebookCellExecution.cell cell} of * this execution. - * @return A thenable that resolves when the operation finished. + * @returns A thenable that resolves when the operation finished. */ clearOutput(cell?: NotebookCell): Thenable; @@ -13583,7 +15207,7 @@ declare module 'vscode' { * @param out Output that replaces the current output. * @param cell Cell for which output is cleared. Defaults to the {@link NotebookCellExecution.cell cell} of * this execution. - * @return A thenable that resolves when the operation finished. + * @returns A thenable that resolves when the operation finished. */ replaceOutput(out: NotebookCellOutput | readonly NotebookCellOutput[], cell?: NotebookCell): Thenable; @@ -13593,7 +15217,7 @@ declare module 'vscode' { * @param out Output that is appended to the current output. * @param cell Cell for which output is cleared. Defaults to the {@link NotebookCellExecution.cell cell} of * this execution. - * @return A thenable that resolves when the operation finished. + * @returns A thenable that resolves when the operation finished. */ appendOutput(out: NotebookCellOutput | readonly NotebookCellOutput[], cell?: NotebookCell): Thenable; @@ -13602,7 +15226,7 @@ declare module 'vscode' { * * @param items Output items that replace the items of existing output. * @param output Output object that already exists. - * @return A thenable that resolves when the operation finished. + * @returns A thenable that resolves when the operation finished. */ replaceOutputItems(items: NotebookCellOutputItem | readonly NotebookCellOutputItem[], output: NotebookCellOutput): Thenable; @@ -13611,7 +15235,7 @@ declare module 'vscode' { * * @param items Output items that are append to existing output. * @param output Output object that already exists. - * @return A thenable that resolves when the operation finished. + * @returns A thenable that resolves when the operation finished. */ appendOutputItems(items: NotebookCellOutputItem | readonly NotebookCellOutputItem[], output: NotebookCellOutput): Thenable; } @@ -13692,7 +15316,7 @@ declare module 'vscode' { * The provider will be called when the cell scrolls into view, when its content, outputs, language, or metadata change, and when it changes execution state. * @param cell The cell for which to return items. * @param token A token triggered if this request should be cancelled. - * @return One or more {@link NotebookCellStatusBarItem cell statusbar items} + * @returns One or more {@link NotebookCellStatusBarItem cell statusbar items} */ provideCellStatusBarItems(cell: NotebookCell, token: CancellationToken): ProviderResult; } @@ -13715,6 +15339,7 @@ declare module 'vscode' { * @param notebookType A notebook type for which this controller is for. * @param label The label of the controller. * @param handler The execute-handler of the controller. + * @returns A new notebook controller. */ export function createNotebookController(id: string, notebookType: string, label: string, handler?: (cells: NotebookCell[], notebook: NotebookDocument, controller: NotebookController) => void | Thenable): NotebookController; @@ -13723,7 +15348,7 @@ declare module 'vscode' { * * @param notebookType The notebook type to register for. * @param provider A cell status bar provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerNotebookCellStatusBarItemProvider(notebookType: string, provider: NotebookCellStatusBarItemProvider): Disposable; @@ -13755,20 +15380,30 @@ declare module 'vscode' { */ placeholder: string; + /** + * Controls whether the input box is enabled (default is `true`). + */ + enabled: boolean; + /** * Controls whether the input box is visible (default is `true`). */ visible: boolean; } - interface QuickDiffProvider { + /** + * A quick diff provider provides a {@link Uri uri} to the original state of a + * modified resource. The editor will use this information to render ad'hoc diffs + * within the text. + */ + export interface QuickDiffProvider { /** * Provide a {@link Uri} to the original resource of any given resource uri. * * @param uri The uri of the resource open in a text editor. * @param token A cancellation token. - * @return A thenable that resolves to uri of the matching original resource. + * @returns A thenable that resolves to uri of the matching original resource. */ provideOriginalResource?(uri: Uri, token: CancellationToken): ProviderResult; } @@ -13974,6 +15609,9 @@ declare module 'vscode' { dispose(): void; } + /** + * Namespace for source control mangement. + */ export namespace scm { /** @@ -13990,7 +15628,7 @@ declare module 'vscode' { * @param id An `id` for the source control. Something short, e.g.: `git`. * @param label A human-readable string for the source control. E.g.: `Git`. * @param rootUri An optional Uri of the root of the source control. E.g.: `Uri.parse(workspaceRoot)`. - * @return An instance of {@link SourceControl source control}. + * @returns An instance of {@link SourceControl source control}. */ export function createSourceControl(id: string, label: string, rootUri?: Uri): SourceControl; } @@ -14091,7 +15729,7 @@ declare module 'vscode' { * If no DAP breakpoint exists (either because the editor breakpoint was not yet registered or because the debug adapter is not interested in the breakpoint), the value `undefined` is returned. * * @param breakpoint A {@link Breakpoint} in the editor. - * @return A promise that resolves to the Debug Adapter Protocol breakpoint or `undefined`. + * @returns A promise that resolves to the Debug Adapter Protocol breakpoint or `undefined`. */ getDebugProtocolBreakpoint(breakpoint: Breakpoint): Thenable; } @@ -14128,7 +15766,7 @@ declare module 'vscode' { * * @param folder The workspace folder for which the configurations are used or `undefined` for a folderless setup. * @param token A cancellation token. - * @return An array of {@link DebugConfiguration debug configurations}. + * @returns An array of {@link DebugConfiguration debug configurations}. */ provideDebugConfigurations?(folder: WorkspaceFolder | undefined, token?: CancellationToken): ProviderResult; @@ -14142,7 +15780,7 @@ declare module 'vscode' { * @param folder The workspace folder from which the configuration originates from or `undefined` for a folderless setup. * @param debugConfiguration The {@link DebugConfiguration debug configuration} to resolve. * @param token A cancellation token. - * @return The resolved debug configuration or undefined or null. + * @returns The resolved debug configuration or undefined or null. */ resolveDebugConfiguration?(folder: WorkspaceFolder | undefined, debugConfiguration: DebugConfiguration, token?: CancellationToken): ProviderResult; @@ -14157,7 +15795,7 @@ declare module 'vscode' { * @param folder The workspace folder from which the configuration originates from or `undefined` for a folderless setup. * @param debugConfiguration The {@link DebugConfiguration debug configuration} to resolve. * @param token A cancellation token. - * @return The resolved debug configuration or undefined or null. + * @returns The resolved debug configuration or undefined or null. */ resolveDebugConfigurationWithSubstitutedVariables?(folder: WorkspaceFolder | undefined, debugConfiguration: DebugConfiguration, token?: CancellationToken): ProviderResult; } @@ -14280,8 +15918,14 @@ declare module 'vscode' { constructor(implementation: DebugAdapter); } + /** + * Represents the different types of debug adapters + */ export type DebugAdapterDescriptor = DebugAdapterExecutable | DebugAdapterServer | DebugAdapterNamedPipeServer | DebugAdapterInlineImplementation; + /** + * A debug adaper factory that creates {@link DebugAdapterDescriptor debug adapter descriptors}. + */ export interface DebugAdapterDescriptorFactory { /** * 'createDebugAdapterDescriptor' is called at the start of a debug session to provide details about the debug adapter to use. @@ -14298,7 +15942,7 @@ declare module 'vscode' { * } * @param session The {@link DebugSession debug session} for which the debug adapter will be used. * @param executable The debug adapter's executable information as specified in the package.json (or undefined if no such information exists). - * @return a {@link DebugAdapterDescriptor debug adapter descriptor} or undefined. + * @returns a {@link DebugAdapterDescriptor debug adapter descriptor} or undefined. */ createDebugAdapterDescriptor(session: DebugSession, executable: DebugAdapterExecutable | undefined): ProviderResult; } @@ -14333,13 +15977,16 @@ declare module 'vscode' { onExit?(code: number | undefined, signal: string | undefined): void; } + /** + * A debug adaper factory that creates {@link DebugAdapterTracker debug adapter trackers}. + */ export interface DebugAdapterTrackerFactory { /** * The method 'createDebugAdapterTracker' is called at the start of a debug session in order * to return a "tracker" object that provides read-access to the communication between the editor and a debug adapter. * * @param session The {@link DebugSession debug session} for which the debug adapter tracker will be used. - * @return A {@link DebugAdapterTracker debug adapter tracker} or undefined. + * @returns A {@link DebugAdapterTracker debug adapter tracker} or undefined. */ createDebugAdapterTracker(session: DebugSession): ProviderResult; } @@ -14409,6 +16056,14 @@ declare module 'vscode' { */ readonly logMessage?: string | undefined; + /** + * Creates a new breakpoint + * + * @param enabled Is breakpoint enabled. + * @param condition Expression for conditional breakpoints + * @param hitCondition Expression that controls how many hits of the breakpoint are ignored + * @param logMessage Log message to display when breakpoint is hit + */ protected constructor(enabled?: boolean, condition?: string, hitCondition?: string, logMessage?: string); } @@ -14495,6 +16150,26 @@ declare module 'vscode' { * If compact is true, debug sessions with a single child are hidden in the CALL STACK view to make the tree more compact. */ compact?: boolean; + + /** + * When true, a save will not be triggered for open editors when starting a debug session, regardless of the value of the `debug.saveBeforeStart` setting. + */ + suppressSaveBeforeStart?: boolean; + + /** + * When true, the debug toolbar will not be shown for this session. + */ + suppressDebugToolbar?: boolean; + + /** + * When true, the window statusbar color will not be changed for this session. + */ + suppressDebugStatusbar?: boolean; + + /** + * When true, the debug viewlet will not be automatically revealed for this session. + */ + suppressDebugView?: boolean; } /** @@ -14575,8 +16250,8 @@ declare module 'vscode' { * * @param debugType The debug type for which the provider is registered. * @param provider The {@link DebugConfigurationProvider debug configuration provider} to register. - * @param triggerKind The {@link DebugConfigurationProviderTrigger trigger} for which the 'provideDebugConfiguration' method of the provider is registered. If `triggerKind` is missing, the value `DebugConfigurationProviderTriggerKind.Initial` is assumed. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @param triggerKind The {@link DebugConfigurationProviderTriggerKind trigger} for which the 'provideDebugConfiguration' method of the provider is registered. If `triggerKind` is missing, the value `DebugConfigurationProviderTriggerKind.Initial` is assumed. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerDebugConfigurationProvider(debugType: string, provider: DebugConfigurationProvider, triggerKind?: DebugConfigurationProviderTriggerKind): Disposable; @@ -14587,7 +16262,7 @@ declare module 'vscode' { * * @param debugType The debug type for which the factory is registered. * @param factory The {@link DebugAdapterDescriptorFactory debug adapter descriptor factory} to register. - * @return A {@link Disposable} that unregisters this factory when being disposed. + * @returns A {@link Disposable} that unregisters this factory when being disposed. */ export function registerDebugAdapterDescriptorFactory(debugType: string, factory: DebugAdapterDescriptorFactory): Disposable; @@ -14596,7 +16271,7 @@ declare module 'vscode' { * * @param debugType The debug type for which the factory is registered or '*' for matching all debug types. * @param factory The {@link DebugAdapterTrackerFactory debug adapter tracker factory} to register. - * @return A {@link Disposable} that unregisters this factory when being disposed. + * @returns A {@link Disposable} that unregisters this factory when being disposed. */ export function registerDebugAdapterTrackerFactory(debugType: string, factory: DebugAdapterTrackerFactory): Disposable; @@ -14609,13 +16284,15 @@ declare module 'vscode' { * @param folder The {@link WorkspaceFolder workspace folder} for looking up named configurations and resolving variables or `undefined` for a non-folder setup. * @param nameOrConfiguration Either the name of a debug or compound configuration or a {@link DebugConfiguration} object. * @param parentSessionOrOptions Debug session options. When passed a parent {@link DebugSession debug session}, assumes options with just this parent session. - * @return A thenable that resolves when debugging could be successfully started. + * @returns A thenable that resolves when debugging could be successfully started. */ export function startDebugging(folder: WorkspaceFolder | undefined, nameOrConfiguration: string | DebugConfiguration, parentSessionOrOptions?: DebugSession | DebugSessionOptions): Thenable; /** * Stop the given debug session or stop all debug sessions if session is omitted. + * * @param session The {@link DebugSession debug session} to stop; if omitted all sessions are stopped. + * @returns A thenable that resolves when the session(s) have been stopped. */ export function stopDebugging(session?: DebugSession): Thenable; @@ -14640,7 +16317,7 @@ declare module 'vscode' { * * @param source An object conforming to the [Source](https://microsoft.github.io/debug-adapter-protocol/specification#Types_Source) type defined in the Debug Adapter Protocol. * @param session An optional debug session that will be used when the source descriptor uses a reference number to load the contents from an active debug session. - * @return A uri that can be used to load the contents of the source. + * @returns A uri that can be used to load the contents of the source. */ export function asDebugSourceUri(source: DebugProtocolSource, session?: DebugSession): Uri; } @@ -14683,7 +16360,7 @@ declare module 'vscode' { * Get an extension by its full identifier in the form of: `publisher.name`. * * @param extensionId An extension identifier. - * @return An extension or `undefined`. + * @returns An extension or `undefined`. */ export function getExtension(extensionId: string): Extension | undefined; @@ -14729,6 +16406,20 @@ declare module 'vscode' { Preview = 1 } + /** + * The state of a comment thread. + */ + export enum CommentThreadState { + /** + * Unresolved thread state + */ + Unresolved = 0, + /** + * Resolved thread state + */ + Resolved = 1 + } + /** * A collection of {@link Comment comments} representing a conversation at a particular range in a document. */ @@ -14786,6 +16477,11 @@ declare module 'vscode' { */ label?: string; + /** + * The optional state of a comment thread, which may affect how the comment is displayed. + */ + state?: CommentThreadState; + /** * Dispose this comment thread. * @@ -14954,7 +16650,7 @@ declare module 'vscode' { /** * Optional commenting range provider. Provide a list {@link Range ranges} which support commenting to any given resource uri. * - * If not provided, users can leave comments in any document opened in the editor. + * If not provided, users cannot leave any comments. */ commentingRangeProvider?: CommentingRangeProvider; @@ -14988,7 +16684,7 @@ declare module 'vscode' { * * @param id An `id` for the comment controller. * @param label A human-readable string for the comment controller. - * @return An instance of {@link CommentController comment controller}. + * @returns An instance of {@link CommentController comment controller}. */ export function createCommentController(id: string, label: string): CommentController; } @@ -15034,18 +16730,35 @@ declare module 'vscode' { readonly label: string; } + /** + * Optional options to be used when calling {@link authentication.getSession} with the flag `forceNewSession`. + */ + export interface AuthenticationForceNewSessionOptions { + /** + * An optional message that will be displayed to the user when we ask to re-authenticate. Providing additional context + * as to why you are asking a user to re-authenticate can help increase the odds that they will accept. + */ + detail?: string; + } /** * Options to be used when getting an {@link AuthenticationSession} from an {@link AuthenticationProvider}. */ export interface AuthenticationGetSessionOptions { /** - * Whether the existing user session preference should be cleared. + * Whether the existing session preference should be cleared. * * For authentication providers that support being signed into multiple accounts at once, the user will be * prompted to select an account to use when {@link authentication.getSession getSession} is called. This preference * is remembered until {@link authentication.getSession getSession} is called with this flag. * + * Note: + * The preference is extension specific. So if one extension calls {@link authentication.getSession getSession}, it will not + * affect the session preference for another extension calling {@link authentication.getSession getSession}. Additionally, + * the preference is set for the current workspace and also globally. This means that new workspaces will use the "global" + * value at first and then when this flag is provided, a new value can be set for that workspace. This also means + * that pre-existing workspaces will not lose their preference if a new workspace sets this flag. + * * Defaults to false. */ clearSessionPreference?: boolean; @@ -15077,7 +16790,7 @@ declare module 'vscode' { * * This defaults to false. */ - forceNewSession?: boolean | { detail: string }; + forceNewSession?: boolean | AuthenticationForceNewSessionOptions; /** * Whether we should show the indication to sign in in the Accounts menu. @@ -15212,7 +16925,7 @@ declare module 'vscode' { * @param options The {@link AuthenticationGetSessionOptions} to use * @returns A thenable that resolves to an authentication session */ - export function getSession(providerId: string, scopes: readonly string[], options: AuthenticationGetSessionOptions & { createIfNone: true }): Thenable; + export function getSession(providerId: string, scopes: readonly string[], options: AuthenticationGetSessionOptions & { /** */createIfNone: true }): Thenable; /** * Get an authentication session matching the desired scopes. Rejects if a provider with providerId is not @@ -15227,7 +16940,7 @@ declare module 'vscode' { * @param options The {@link AuthenticationGetSessionOptions} to use * @returns A thenable that resolves to an authentication session */ - export function getSession(providerId: string, scopes: readonly string[], options: AuthenticationGetSessionOptions & { forceNewSession: true | { detail: string } }): Thenable; + export function getSession(providerId: string, scopes: readonly string[], options: AuthenticationGetSessionOptions & { /** literal-type defines return type */forceNewSession: true | AuthenticationForceNewSessionOptions }): Thenable; /** * Get an authentication session matching the desired scopes. Rejects if a provider with providerId is not @@ -15259,12 +16972,95 @@ declare module 'vscode' { * @param id The unique identifier of the provider. * @param label The human-readable name of the provider. * @param provider The authentication provider provider. - * @params options Additional options for the provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. + * @param options Additional options for the provider. + * @returns A {@link Disposable} that unregisters this provider when being disposed. */ export function registerAuthenticationProvider(id: string, label: string, provider: AuthenticationProvider, options?: AuthenticationProviderOptions): Disposable; } + /** + * Namespace for localization-related functionality in the extension API. To use this properly, + * you must have `l10n` defined in your extension manifest and have bundle.l10n..json files. + * For more information on how to generate bundle.l10n..json files, check out the + * [vscode-l10n repo](https://github.com/microsoft/vscode-l10n). + * + * Note: Built-in extensions (for example, Git, TypeScript Language Features, GitHub Authentication) + * are excluded from the `l10n` property requirement. In other words, they do not need to specify + * a `l10n` in the extension manifest because their translated strings come from Language Packs. + */ + export namespace l10n { + /** + * Marks a string for localization. If a localized bundle is available for the language specified by + * {@link env.language} and the bundle has a localized value for this message, then that localized + * value will be returned (with injected {@link args} values for any templated values). + * + * @param message - The message to localize. Supports index templating where strings like `{0}` and `{1}` are + * replaced by the item at that index in the {@link args} array. + * @param args - The arguments to be used in the localized string. The index of the argument is used to + * match the template placeholder in the localized string. + * @returns localized string with injected arguments. + * + * @example + * l10n.t('Hello {0}!', 'World'); + */ + export function t(message: string, ...args: Array): string; + + /** + * Marks a string for localization. If a localized bundle is available for the language specified by + * {@link env.language} and the bundle has a localized value for this message, then that localized + * value will be returned (with injected {@link args} values for any templated values). + * + * @param message The message to localize. Supports named templating where strings like `{foo}` and `{bar}` are + * replaced by the value in the Record for that key (foo, bar, etc). + * @param args The arguments to be used in the localized string. The name of the key in the record is used to + * match the template placeholder in the localized string. + * @returns localized string with injected arguments. + * + * @example + * l10n.t('Hello {name}', { name: 'Erich' }); + */ + export function t(message: string, args: Record): string; + /** + * Marks a string for localization. If a localized bundle is available for the language specified by + * {@link env.language} and the bundle has a localized value for this message, then that localized + * value will be returned (with injected args values for any templated values). + * + * @param options The options to use when localizing the message. + * @returns localized string with injected arguments. + */ + export function t(options: { + /** + * The message to localize. If {@link options.args args} is an array, this message supports index templating where strings like + * `{0}` and `{1}` are replaced by the item at that index in the {@link options.args args} array. If `args` is a `Record`, + * this supports named templating where strings like `{foo}` and `{bar}` are replaced by the value in + * the Record for that key (foo, bar, etc). + */ + message: string; + /** + * The arguments to be used in the localized string. As an array, the index of the argument is used to + * match the template placeholder in the localized string. As a Record, the key is used to match the template + * placeholder in the localized string. + */ + args?: Array | Record; + /** + * A comment to help translators understand the context of the message. + */ + comment: string | string[]; + }): string; + /** + * The bundle of localized strings that have been loaded for the extension. + * It's undefined if no bundle has been loaded. The bundle is typically not loaded if + * there was no bundle found or when we are running with the default language. + */ + export const bundle: { [key: string]: string } | undefined; + /** + * The URI of the localization bundle that has been loaded for the extension. + * It's undefined if no bundle has been loaded. The bundle is typically not loaded if + * there was no bundle found or when we are running with the default language. + */ + export const uri: Uri | undefined; + } + /** * Namespace for testing functionality. Tests are published by registering * {@link TestController} instances, then adding {@link TestItem TestItems}. @@ -15286,8 +17082,17 @@ declare module 'vscode' { * The kind of executions that {@link TestRunProfile TestRunProfiles} control. */ export enum TestRunProfileKind { + /** + * The `Run` test profile kind. + */ Run = 1, + /** + * The `Debug` test profile kind. + */ Debug = 2, + /** + * The `Coverage` test profile kind. + */ Coverage = 3, } @@ -15337,9 +17142,25 @@ declare module 'vscode' { * the generic "run all" button, then the default profile for * {@link TestRunProfileKind.Run} will be executed, although the * user can configure this. + * + * Changes the user makes in their default profiles will be reflected + * in this property after a {@link onDidChangeDefault} event. */ isDefault: boolean; + /** + * Fired when a user has changed whether this is a default profile. The + * event contains the new value of {@link isDefault} + */ + onDidChangeDefault: Event; + + /** + * Whether this profile supports continuous running of requests. If so, + * then {@link TestRunRequest.continuous} may be set to `true`. Defaults + * to false. + */ + supportsContinuousRun: boolean; + /** * Associated tag for the profile. If this is set, only {@link TestItem} * instances with the same tag will be eligible to execute in this profile. @@ -15360,6 +17181,11 @@ declare module 'vscode' { * associated with the request should be created before the function returns * or the returned promise is resolved. * + * If {@link supportsContinuousRun} is set, then {@link TestRunRequest.continuous} + * may be `true`. In this case, the profile should observe changes to + * source code and create new test runs by calling {@link TestController.createTestRun}, + * until the cancellation is requested on the `token`. + * * @param request Request information for the test run. * @param cancellationToken Token that signals the used asked to abort the * test run. If cancellation is requested on this token, all {@link TestRun} @@ -15368,6 +17194,17 @@ declare module 'vscode' { */ runHandler: (request: TestRunRequest, token: CancellationToken) => Thenable | void; + /** + * An extension-provided function that provides detailed statement and + * function-level coverage for a file. The editor will call this when more + * detail is needed for a file, such as when it's opened in an editor or + * expanded in the **Test Coverage** view. + * + * The {@link FileCoverage} object passed to this function is the same instance + * emitted on {@link TestRun.addCoverage} calls associated with this profile. + */ + loadDetailedCoverage?: (testRun: TestRun, fileCoverage: FileCoverage, token: CancellationToken) => Thenable; + /** * Deletes the run profile. */ @@ -15382,7 +17219,7 @@ declare module 'vscode' { */ export interface TestController { /** - * The id of the controller passed in {@link vscode.tests.createTestController}. + * The id of the controller passed in {@link tests.createTestController}. * This must be globally unique. */ readonly id: string; @@ -15398,7 +17235,7 @@ declare module 'vscode' { * "test tree." * * The extension controls when to add tests. For example, extensions should - * add tests for a file when {@link vscode.workspace.onDidOpenTextDocument} + * add tests for a file when {@link workspace.onDidOpenTextDocument} * fires in order for decorations for tests within a file to be visible. * * However, the editor may sometimes explicitly request children using the @@ -15414,16 +17251,17 @@ declare module 'vscode' { * @param runHandler Function called to start a test run. * @param isDefault Whether this is the default action for its kind. * @param tag Profile test tag. + * @param supportsContinuousRun Whether the profile supports continuous running. * @returns An instance of a {@link TestRunProfile}, which is automatically * associated with this controller. */ - createRunProfile(label: string, kind: TestRunProfileKind, runHandler: (request: TestRunRequest, token: CancellationToken) => Thenable | void, isDefault?: boolean, tag?: TestTag): TestRunProfile; + createRunProfile(label: string, kind: TestRunProfileKind, runHandler: (request: TestRunRequest, token: CancellationToken) => Thenable | void, isDefault?: boolean, tag?: TestTag, supportsContinuousRun?: boolean): TestRunProfile; /** * A function provided by the extension that the editor may call to request * children of a test item, if the {@link TestItem.canResolveChildren} is * `true`. When called, the item should discover children and call - * {@link vscode.tests.createTestItem} as children are discovered. + * {@link TestController.createTestItem} as children are discovered. * * Generally the extension manages the lifecycle of test items, but under * certain conditions the editor may request the children of a specific @@ -15487,6 +17325,24 @@ declare module 'vscode' { */ createTestItem(id: string, label: string, uri?: Uri): TestItem; + /** + * Marks an item's results as being outdated. This is commonly called when + * code or configuration changes and previous results should no longer + * be considered relevant. The same logic used to mark results as outdated + * may be used to drive {@link TestRunRequest.continuous continuous test runs}. + * + * If an item is passed to this method, test results for the item and all of + * its children will be marked as outdated. If no item is passed, then all + * test owned by the TestController will be marked as outdated. + * + * Any test runs started before the moment this method is called, including + * runs which may still be ongoing, will be marked as outdated and deprioritized + * in the editor's UI. + * + * @param item Item to mark as outdated. If undefined, all the controller's items are marked outdated. + */ + invalidateTestResults(items?: TestItem | readonly TestItem[]): void; + /** * Unregisters the test controller, disposing of its associated tests * and unpersisted results. @@ -15496,9 +17352,9 @@ declare module 'vscode' { /** * A TestRunRequest is a precursor to a {@link TestRun}, which in turn is - * created by passing a request to {@link tests.runTests}. The TestRunRequest - * contains information about which tests should be run, which should not be - * run, and how they are run (via the {@link TestRunRequest.profile profile}). + * created by passing a request to {@link TestController.createTestRun}. The + * TestRunRequest contains information about which tests should be run, which + * should not be run, and how they are run (via the {@link TestRunRequest.profile profile}). * * In general, TestRunRequests are created by the editor and pass to * {@link TestRunProfile.runHandler}, however you can also create test @@ -15532,16 +17388,24 @@ declare module 'vscode' { */ readonly profile: TestRunProfile | undefined; + /** + * Whether the profile should run continuously as source code changes. Only + * relevant for profiles that set {@link TestRunProfile.supportsContinuousRun}. + */ + readonly continuous?: boolean; + /** * @param include Array of specific tests to run, or undefined to run all tests * @param exclude An array of tests to exclude from the run. * @param profile The run profile used for this request. + * @param continuous Whether to run tests continuously as source changes. */ - constructor(include?: readonly TestItem[], exclude?: readonly TestItem[], profile?: TestRunProfile); + constructor(include?: readonly TestItem[], exclude?: readonly TestItem[], profile?: TestRunProfile, continuous?: boolean); } /** - * Options given to {@link TestController.runTests} + * A TestRun represents an in-progress or completed test run and + * provides methods to report the state of individual tests in the run. */ export interface TestRun { /** @@ -15610,7 +17474,8 @@ declare module 'vscode' { /** * Appends raw output from the test runner. On the user's request, the * output will be displayed in a terminal. ANSI escape sequences, - * such as colors and text styles, are supported. + * such as colors and text styles, are supported. New lines must be given + * as CRLF (`\r\n`) rather than LF (`\n`). * * @param output Output text to append. * @param location Indicate that the output was logged at the given @@ -15620,17 +17485,28 @@ declare module 'vscode' { appendOutput(output: string, location?: Location, test?: TestItem): void; /** - * Signals that the end of the test run. Any tests included in the run whose + * Adds coverage for a file in the run. + */ + addCoverage(fileCoverage: FileCoverage): void; + + /** + * Signals the end of the test run. Any tests included in the run whose * states have not been updated will have their state reset. */ end(): void; + + /** + * An event fired when the editor is no longer interested in data + * associated with the test run. + */ + onDidDispose: Event; } /** * Collection of test items, found in {@link TestItem.children} and * {@link TestController.items}. */ - export interface TestItemCollection { + export interface TestItemCollection extends Iterable<[id: string, testItem: TestItem]> { /** * Gets the number of items in the collection. */ @@ -15648,7 +17524,7 @@ declare module 'vscode' { * @param callback Function to execute for each entry. * @param thisArg The `this` context used when invoking the handler function. */ - forEach(callback: (item: TestItem, collection: TestItemCollection) => unknown, thisArg?: unknown): void; + forEach(callback: (item: TestItem, collection: TestItemCollection) => unknown, thisArg?: any): void; /** * Adds the test item to the children. If an item with the same ID already @@ -15706,7 +17582,7 @@ declare module 'vscode' { /** * Tags associated with this test item. May be used in combination with - * {@link TestRunProfile.tags}, or simply as an organizational feature. + * {@link TestRunProfile.tag tags}, or simply as an organizational feature. */ tags: readonly TestTag[]; @@ -15787,6 +17663,37 @@ declare module 'vscode' { */ location?: Location; + /** + * Context value of the test item. This can be used to contribute message- + * specific actions to the test peek view. The value set here can be found + * in the `testMessage` property of the following `menus` contribution points: + * + * - `testing/message/context` - context menu for the message in the results tree + * - `testing/message/content` - a prominent button overlaying editor content where + * the message is displayed. + * + * For example: + * + * ```json + * "contributes": { + * "menus": { + * "testing/message/content": [ + * { + * "command": "extension.deleteCommentThread", + * "when": "testMessage == canApplyRichDiff" + * } + * ] + * } + * } + * ``` + * + * The command will be called with an object containing: + * - `test`: the {@link TestItem} the message is associated with, *if* it + * is still present in the {@link TestController.items} collection. + * - `message`: the {@link TestMessage} instance. + */ + contextValue?: string; + /** * Creates a new TestMessage that will present as a diff in the editor. * @param message Message to display to the user. @@ -15802,6 +17709,177 @@ declare module 'vscode' { constructor(message: string | MarkdownString); } + /** + * A class that contains information about a covered resource. A count can + * be give for lines, branches, and declarations in a file. + */ + export class TestCoverageCount { + /** + * Number of items covered in the file. + */ + covered: number; + /** + * Total number of covered items in the file. + */ + total: number; + + /** + * @param covered Value for {@link TestCoverageCount.covered} + * @param total Value for {@link TestCoverageCount.total} + */ + constructor(covered: number, total: number); + } + + /** + * Contains coverage metadata for a file. + */ + export class FileCoverage { + /** + * File URI. + */ + readonly uri: Uri; + + /** + * Statement coverage information. If the reporter does not provide statement + * coverage information, this can instead be used to represent line coverage. + */ + statementCoverage: TestCoverageCount; + + /** + * Branch coverage information. + */ + branchCoverage?: TestCoverageCount; + + /** + * Declaration coverage information. Depending on the reporter and + * language, this may be types such as functions, methods, or namespaces. + */ + declarationCoverage?: TestCoverageCount; + + /** + * Creates a {@link FileCoverage} instance with counts filled in from + * the coverage details. + * @param uri Covered file URI + * @param detailed Detailed coverage information + */ + static fromDetails(uri: Uri, details: readonly FileCoverageDetail[]): FileCoverage; + + /** + * @param uri Covered file URI + * @param statementCoverage Statement coverage information. If the reporter + * does not provide statement coverage information, this can instead be + * used to represent line coverage. + * @param branchCoverage Branch coverage information + * @param declarationCoverage Declaration coverage information + */ + constructor( + uri: Uri, + statementCoverage: TestCoverageCount, + branchCoverage?: TestCoverageCount, + declarationCoverage?: TestCoverageCount, + ); + } + + /** + * Contains coverage information for a single statement or line. + */ + export class StatementCoverage { + /** + * The number of times this statement was executed, or a boolean indicating + * whether it was executed if the exact count is unknown. If zero or false, + * the statement will be marked as un-covered. + */ + executed: number | boolean; + + /** + * Statement location. + */ + location: Position | Range; + + /** + * Coverage from branches of this line or statement. If it's not a + * conditional, this will be empty. + */ + branches: BranchCoverage[]; + + /** + * @param location The statement position. + * @param executed The number of times this statement was executed, or a + * boolean indicating whether it was executed if the exact count is + * unknown. If zero or false, the statement will be marked as un-covered. + * @param branches Coverage from branches of this line. If it's not a + * conditional, this should be omitted. + */ + constructor(executed: number | boolean, location: Position | Range, branches?: BranchCoverage[]); + } + + /** + * Contains coverage information for a branch of a {@link StatementCoverage}. + */ + export class BranchCoverage { + /** + * The number of times this branch was executed, or a boolean indicating + * whether it was executed if the exact count is unknown. If zero or false, + * the branch will be marked as un-covered. + */ + executed: number | boolean; + + /** + * Branch location. + */ + location?: Position | Range; + + /** + * Label for the branch, used in the context of "the ${label} branch was + * not taken," for example. + */ + label?: string; + + /** + * @param executed The number of times this branch was executed, or a + * boolean indicating whether it was executed if the exact count is + * unknown. If zero or false, the branch will be marked as un-covered. + * @param location The branch position. + */ + constructor(executed: number | boolean, location?: Position | Range, label?: string); + } + + /** + * Contains coverage information for a declaration. Depending on the reporter + * and language, this may be types such as functions, methods, or namespaces. + */ + export class DeclarationCoverage { + /** + * Name of the declaration. + */ + name: string; + + /** + * The number of times this declaration was executed, or a boolean + * indicating whether it was executed if the exact count is unknown. If + * zero or false, the declaration will be marked as un-covered. + */ + executed: number | boolean; + + /** + * Declaration location. + */ + location: Position | Range; + + /** + * @param executed The number of times this declaration was executed, or a + * boolean indicating whether it was executed if the exact count is + * unknown. If zero or false, the declaration will be marked as un-covered. + * @param location The declaration position. + */ + constructor(name: string, executed: number | boolean, location: Position | Range); + } + + /** + * Coverage details returned from {@link TestRunProfile.loadDetailedCoverage}. + */ + export type FileCoverageDetail = StatementCoverage | DeclarationCoverage; + /** * The tab represents a single text based resource. */ @@ -16019,7 +18097,7 @@ declare module 'vscode' { * Whether or not the group is currently active. * * *Note* that only one tab group is active at a time, but that multiple tab - * groups can have an {@link TabGroup.aciveTab active tab}. + * groups can have an {@link activeTab active tab}. * * @see {@link Tab.isActive} */ @@ -16046,7 +18124,7 @@ declare module 'vscode' { } /** - * Represents the main editor area which consists of multple groups which contain tabs. + * Represents the main editor area which consists of multiple groups which contain tabs. */ export interface TabGroups { /** @@ -16089,6 +18167,153 @@ declare module 'vscode' { */ close(tabGroup: TabGroup | readonly TabGroup[], preserveFocus?: boolean): Thenable; } + + /** + * A special value wrapper denoting a value that is safe to not clean. + * This is to be used when you can guarantee no identifiable information is contained in the value and the cleaning is improperly redacting it. + */ + export class TelemetryTrustedValue { + + /** + * The value that is trusted to not contain PII. + */ + readonly value: T; + + /** + * Creates a new telementry trusted value. + * + * @param value A value to trust + */ + constructor(value: T); + } + + /** + * A telemetry logger which can be used by extensions to log usage and error telementry. + * + * A logger wraps around an {@link TelemetrySender sender} but it guarantees that + * - user settings to disable or tweak telemetry are respected, and that + * - potential sensitive data is removed + * + * It also enables an "echo UI" that prints whatever data is send and it allows the editor + * to forward unhandled errors to the respective extensions. + * + * To get an instance of a `TelemetryLogger`, use + * {@link env.createTelemetryLogger `createTelemetryLogger`}. + */ + export interface TelemetryLogger { + + /** + * An {@link Event} which fires when the enablement state of usage or error telemetry changes. + */ + readonly onDidChangeEnableStates: Event; + + /** + * Whether or not usage telemetry is enabled for this logger. + */ + readonly isUsageEnabled: boolean; + + /** + * Whether or not error telemetry is enabled for this logger. + */ + readonly isErrorsEnabled: boolean; + + /** + * Log a usage event. + * + * After completing cleaning, telemetry setting checks, and data mix-in calls `TelemetrySender.sendEventData` to log the event. + * Automatically supports echoing to extension telemetry output channel. + * @param eventName The event name to log + * @param data The data to log + */ + logUsage(eventName: string, data?: Record): void; + + /** + * Log an error event. + * + * After completing cleaning, telemetry setting checks, and data mix-in calls `TelemetrySender.sendEventData` to log the event. Differs from `logUsage` in that it will log the event if the telemetry setting is Error+. + * Automatically supports echoing to extension telemetry output channel. + * @param eventName The event name to log + * @param data The data to log + */ + logError(eventName: string, data?: Record): void; + + /** + * Log an error event. + * + * Calls `TelemetrySender.sendErrorData`. Does cleaning, telemetry checks, and data mix-in. + * Automatically supports echoing to extension telemetry output channel. + * Will also automatically log any exceptions thrown within the extension host process. + * @param error The error object which contains the stack trace cleaned of PII + * @param data Additional data to log alongside the stack trace + */ + logError(error: Error, data?: Record): void; + + /** + * Dispose this object and free resources. + */ + dispose(): void; + } + + /** + * The telemetry sender is the contract between a telemetry logger and some telemetry service. **Note** that extensions must NOT + * call the methods of their sender directly as the logger provides extra guards and cleaning. + * + * ```js + * const sender: vscode.TelemetrySender = {...}; + * const logger = vscode.env.createTelemetryLogger(sender); + * + * // GOOD - uses the logger + * logger.logUsage('myEvent', { myData: 'myValue' }); + * + * // BAD - uses the sender directly: no data cleansing, ignores user settings, no echoing to the telemetry output channel etc + * sender.logEvent('myEvent', { myData: 'myValue' }); + * ``` + */ + export interface TelemetrySender { + /** + * Function to send event data without a stacktrace. Used within a {@link TelemetryLogger} + * + * @param eventName The name of the event which you are logging + * @param data A serializable key value pair that is being logged + */ + sendEventData(eventName: string, data?: Record): void; + + /** + * Function to send an error. Used within a {@link TelemetryLogger} + * + * @param error The error being logged + * @param data Any additional data to be collected with the exception + */ + sendErrorData(error: Error, data?: Record): void; + + /** + * Optional flush function which will give this sender a chance to send any remaining events + * as its {@link TelemetryLogger} is being disposed + */ + flush?(): void | Thenable; + } + + /** + * Options for creating a {@link TelemetryLogger} + */ + export interface TelemetryLoggerOptions { + /** + * Whether or not you want to avoid having the built-in common properties such as os, extension name, etc injected into the data object. + * Defaults to `false` if not defined. + */ + readonly ignoreBuiltInCommonProperties?: boolean; + + /** + * Whether or not unhandled errors on the extension host caused by your extension should be logged to your sender. + * Defaults to `false` if not defined. + */ + readonly ignoreUnhandledErrors?: boolean; + + /** + * Any additional common properties which should be injected into the data object. + */ + readonly additionalCommonProperties?: Record; + } } /** @@ -16097,13 +18322,4 @@ declare module 'vscode' { * enables reusing existing code without migrating to a specific promise implementation. Still, * we recommend the use of native promises which are available in this editor. */ -interface Thenable { - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Thenable; - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => void): Thenable; -} +interface Thenable extends PromiseLike { }