Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vscode-dts/vscode.d.ts
5238 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
declare module 'vscode' {
7
8
/**
9
* The version of the editor.
10
*/
11
export const version: string;
12
13
/**
14
* Represents a reference to a command. Provides a title which
15
* will be used to represent a command in the UI and, optionally,
16
* an array of arguments which will be passed to the command handler
17
* function when invoked.
18
*/
19
export interface Command {
20
/**
21
* Title of the command, like `save`.
22
*/
23
title: string;
24
25
/**
26
* The identifier of the actual command handler.
27
* @see {@link commands.registerCommand}
28
*/
29
command: string;
30
31
/**
32
* A tooltip for the command, when represented in the UI.
33
*/
34
tooltip?: string;
35
36
/**
37
* Arguments that the command handler should be
38
* invoked with.
39
*/
40
arguments?: any[];
41
}
42
43
/**
44
* Represents a line of text, such as a line of source code.
45
*
46
* TextLine objects are __immutable__. When a {@link TextDocument document} changes,
47
* previously retrieved lines will not represent the latest state.
48
*/
49
export interface TextLine {
50
51
/**
52
* The zero-based line number.
53
*/
54
readonly lineNumber: number;
55
56
/**
57
* The text of this line without the line separator characters.
58
*/
59
readonly text: string;
60
61
/**
62
* The range this line covers without the line separator characters.
63
*/
64
readonly range: Range;
65
66
/**
67
* The range this line covers with the line separator characters.
68
*/
69
readonly rangeIncludingLineBreak: Range;
70
71
/**
72
* The offset of the first character which is not a whitespace character as defined
73
* by `/\s/`. **Note** that if a line is all whitespace the length of the line is returned.
74
*/
75
readonly firstNonWhitespaceCharacterIndex: number;
76
77
/**
78
* Whether this line is whitespace only, shorthand
79
* for {@link TextLine.firstNonWhitespaceCharacterIndex} === {@link TextLine.text TextLine.text.length}.
80
*/
81
readonly isEmptyOrWhitespace: boolean;
82
}
83
84
/**
85
* Represents a text document, such as a source file. Text documents have
86
* {@link TextLine lines} and knowledge about an underlying resource like a file.
87
*/
88
export interface TextDocument {
89
90
/**
91
* The associated uri for this document.
92
*
93
* *Note* that most documents use the `file`-scheme, which means they are files on disk. However, **not** all documents are
94
* saved on disk and therefore the `scheme` must be checked before trying to access the underlying file or siblings on disk.
95
*
96
* @see {@link FileSystemProvider}
97
* @see {@link TextDocumentContentProvider}
98
*/
99
readonly uri: Uri;
100
101
/**
102
* The file system path of the associated resource. Shorthand
103
* notation for {@link TextDocument.uri TextDocument.uri.fsPath}. Independent of the uri scheme.
104
*/
105
readonly fileName: string;
106
107
/**
108
* Is this document representing an untitled file which has never been saved yet. *Note* that
109
* this does not mean the document will be saved to disk, use {@linkcode Uri.scheme}
110
* to figure out where a document will be {@link FileSystemProvider saved}, e.g. `file`, `ftp` etc.
111
*/
112
readonly isUntitled: boolean;
113
114
/**
115
* The identifier of the language associated with this document.
116
*/
117
readonly languageId: string;
118
119
/**
120
* The file encoding of this document that will be used when the document is saved.
121
*
122
* Use the {@link workspace.onDidChangeTextDocument onDidChangeTextDocument}-event to
123
* get notified when the document encoding changes.
124
*
125
* Note that the possible encoding values are currently defined as any of the following:
126
* 'utf8', 'utf8bom', 'utf16le', 'utf16be', 'windows1252', 'iso88591', 'iso88593',
127
* 'iso885915', 'macroman', 'cp437', 'windows1256', 'iso88596', 'windows1257',
128
* 'iso88594', 'iso885914', 'windows1250', 'iso88592', 'cp852', 'windows1251',
129
* 'cp866', 'cp1125', 'iso88595', 'koi8r', 'koi8u', 'iso885913', 'windows1253',
130
* 'iso88597', 'windows1255', 'iso88598', 'iso885910', 'iso885916', 'windows1254',
131
* 'iso88599', 'windows1258', 'gbk', 'gb18030', 'cp950', 'big5hkscs', 'shiftjis',
132
* 'eucjp', 'euckr', 'windows874', 'iso885911', 'koi8ru', 'koi8t', 'gb2312',
133
* 'cp865', 'cp850'.
134
*/
135
readonly encoding: string;
136
137
/**
138
* The version number of this document (it will strictly increase after each
139
* change, including undo/redo).
140
*/
141
readonly version: number;
142
143
/**
144
* `true` if there are unpersisted changes.
145
*/
146
readonly isDirty: boolean;
147
148
/**
149
* `true` if the document has been closed. A closed document isn't synchronized anymore
150
* and won't be re-used when the same resource is opened again.
151
*/
152
readonly isClosed: boolean;
153
154
/**
155
* Save the underlying file.
156
*
157
* @returns A promise that will resolve to `true` when the file
158
* has been saved. If the save failed, will return `false`.
159
*/
160
save(): Thenable<boolean>;
161
162
/**
163
* The {@link EndOfLine end of line} sequence that is predominately
164
* used in this document.
165
*/
166
readonly eol: EndOfLine;
167
168
/**
169
* The number of lines in this document.
170
*/
171
readonly lineCount: number;
172
173
/**
174
* Returns a text line denoted by the line number. Note
175
* that the returned object is *not* live and changes to the
176
* document are not reflected.
177
*
178
* @param line A line number in `[0, lineCount)`.
179
* @returns A {@link TextLine line}.
180
*/
181
lineAt(line: number): TextLine;
182
183
/**
184
* Returns a text line denoted by the position. Note
185
* that the returned object is *not* live and changes to the
186
* document are not reflected.
187
*
188
* The position will be {@link TextDocument.validatePosition adjusted}.
189
*
190
* @see {@link TextDocument.lineAt}
191
*
192
* @param position A position.
193
* @returns A {@link TextLine line}.
194
*/
195
lineAt(position: Position): TextLine;
196
197
/**
198
* Converts the position to a zero-based offset.
199
*
200
* The position will be {@link TextDocument.validatePosition adjusted}.
201
*
202
* @param position A position.
203
* @returns A valid zero-based offset in UTF-16 [code units](https://developer.mozilla.org/en-US/docs/Glossary/Code_unit).
204
*/
205
offsetAt(position: Position): number;
206
207
/**
208
* Converts a zero-based offset to a position.
209
*
210
* @param offset A zero-based offset into the document. This offset is in UTF-16 [code units](https://developer.mozilla.org/en-US/docs/Glossary/Code_unit).
211
* @returns A valid {@link Position}.
212
*/
213
positionAt(offset: number): Position;
214
215
/**
216
* Get the text of this document. A substring can be retrieved by providing
217
* a range. The range will be {@link TextDocument.validateRange adjusted}.
218
*
219
* @param range Include only the text included by the range.
220
* @returns The text inside the provided range or the entire text.
221
*/
222
getText(range?: Range): string;
223
224
/**
225
* Get a word-range at the given position. By default words are defined by
226
* common separators, like space, -, _, etc. In addition, per language custom
227
* [word definitions] can be defined. It
228
* is also possible to provide a custom regular expression.
229
*
230
* * *Note 1:* A custom regular expression must not match the empty string and
231
* if it does, it will be ignored.
232
* * *Note 2:* A custom regular expression will fail to match multiline strings
233
* and in the name of speed regular expressions should not match words with
234
* spaces. Use {@linkcode TextLine.text} for more complex, non-wordy, scenarios.
235
*
236
* The position will be {@link TextDocument.validatePosition adjusted}.
237
*
238
* @param position A position.
239
* @param regex Optional regular expression that describes what a word is.
240
* @returns A range spanning a word, or `undefined`.
241
*/
242
getWordRangeAtPosition(position: Position, regex?: RegExp): Range | undefined;
243
244
/**
245
* Ensure a range is completely contained in this document.
246
*
247
* @param range A range.
248
* @returns The given range or a new, adjusted range.
249
*/
250
validateRange(range: Range): Range;
251
252
/**
253
* Ensure a position is contained in the range of this document.
254
*
255
* @param position A position.
256
* @returns The given position or a new, adjusted position.
257
*/
258
validatePosition(position: Position): Position;
259
}
260
261
/**
262
* Represents a line and character position, such as
263
* the position of the cursor.
264
*
265
* Position objects are __immutable__. Use the {@link Position.with with} or
266
* {@link Position.translate translate} methods to derive new positions
267
* from an existing position.
268
*/
269
export class Position {
270
271
/**
272
* The zero-based line value.
273
*/
274
readonly line: number;
275
276
/**
277
* The zero-based character value.
278
*
279
* Character offsets are expressed using UTF-16 [code units](https://developer.mozilla.org/en-US/docs/Glossary/Code_unit).
280
*/
281
readonly character: number;
282
283
/**
284
* @param line A zero-based line value.
285
* @param character A zero-based character value.
286
*/
287
constructor(line: number, character: number);
288
289
/**
290
* Check if this position is before `other`.
291
*
292
* @param other A position.
293
* @returns `true` if position is on a smaller line
294
* or on the same line on a smaller character.
295
*/
296
isBefore(other: Position): boolean;
297
298
/**
299
* Check if this position is before or equal to `other`.
300
*
301
* @param other A position.
302
* @returns `true` if position is on a smaller line
303
* or on the same line on a smaller or equal character.
304
*/
305
isBeforeOrEqual(other: Position): boolean;
306
307
/**
308
* Check if this position is after `other`.
309
*
310
* @param other A position.
311
* @returns `true` if position is on a greater line
312
* or on the same line on a greater character.
313
*/
314
isAfter(other: Position): boolean;
315
316
/**
317
* Check if this position is after or equal to `other`.
318
*
319
* @param other A position.
320
* @returns `true` if position is on a greater line
321
* or on the same line on a greater or equal character.
322
*/
323
isAfterOrEqual(other: Position): boolean;
324
325
/**
326
* Check if this position is equal to `other`.
327
*
328
* @param other A position.
329
* @returns `true` if the line and character of the given position are equal to
330
* the line and character of this position.
331
*/
332
isEqual(other: Position): boolean;
333
334
/**
335
* Compare this to `other`.
336
*
337
* @param other A position.
338
* @returns A number smaller than zero if this position is before the given position,
339
* a number greater than zero if this position is after the given position, or zero when
340
* this and the given position are equal.
341
*/
342
compareTo(other: Position): number;
343
344
/**
345
* Create a new position relative to this position.
346
*
347
* @param lineDelta Delta value for the line value, default is `0`.
348
* @param characterDelta Delta value for the character value, default is `0`.
349
* @returns A position which line and character is the sum of the current line and
350
* character and the corresponding deltas.
351
*/
352
translate(lineDelta?: number, characterDelta?: number): Position;
353
354
/**
355
* Derived a new position relative to this position.
356
*
357
* @param change An object that describes a delta to this position.
358
* @returns A position that reflects the given delta. Will return `this` position if the change
359
* is not changing anything.
360
*/
361
translate(change: {
362
/**
363
* Delta value for the line value, default is `0`.
364
*/
365
lineDelta?: number;
366
/**
367
* Delta value for the character value, default is `0`.
368
*/
369
characterDelta?: number;
370
}): Position;
371
372
/**
373
* Create a new position derived from this position.
374
*
375
* @param line Value that should be used as line value, default is the {@link Position.line existing value}
376
* @param character Value that should be used as character value, default is the {@link Position.character existing value}
377
* @returns A position where line and character are replaced by the given values.
378
*/
379
with(line?: number, character?: number): Position;
380
381
/**
382
* Derived a new position from this position.
383
*
384
* @param change An object that describes a change to this position.
385
* @returns A position that reflects the given change. Will return `this` position if the change
386
* is not changing anything.
387
*/
388
with(change: {
389
/**
390
* New line value, defaults the line value of `this`.
391
*/
392
line?: number;
393
/**
394
* New character value, defaults the character value of `this`.
395
*/
396
character?: number;
397
}): Position;
398
}
399
400
/**
401
* A range represents an ordered pair of two positions.
402
* It is guaranteed that {@link Range.start start}.isBeforeOrEqual({@link Range.end end})
403
*
404
* Range objects are __immutable__. Use the {@link Range.with with},
405
* {@link Range.intersection intersection}, or {@link Range.union union} methods
406
* to derive new ranges from an existing range.
407
*/
408
export class Range {
409
410
/**
411
* The start position. It is before or equal to {@link Range.end end}.
412
*/
413
readonly start: Position;
414
415
/**
416
* The end position. It is after or equal to {@link Range.start start}.
417
*/
418
readonly end: Position;
419
420
/**
421
* Create a new range from two positions. If `start` is not
422
* before or equal to `end`, the values will be swapped.
423
*
424
* @param start A position.
425
* @param end A position.
426
*/
427
constructor(start: Position, end: Position);
428
429
/**
430
* Create a new range from number coordinates. It is a shorter equivalent of
431
* using `new Range(new Position(startLine, startCharacter), new Position(endLine, endCharacter))`
432
*
433
* @param startLine A zero-based line value.
434
* @param startCharacter A zero-based character value.
435
* @param endLine A zero-based line value.
436
* @param endCharacter A zero-based character value.
437
*/
438
constructor(startLine: number, startCharacter: number, endLine: number, endCharacter: number);
439
440
/**
441
* `true` if `start` and `end` are equal.
442
*/
443
isEmpty: boolean;
444
445
/**
446
* `true` if `start.line` and `end.line` are equal.
447
*/
448
isSingleLine: boolean;
449
450
/**
451
* Check if a position or a range is contained in this range.
452
*
453
* @param positionOrRange A position or a range.
454
* @returns `true` if the position or range is inside or equal
455
* to this range.
456
*/
457
contains(positionOrRange: Position | Range): boolean;
458
459
/**
460
* Check if `other` equals this range.
461
*
462
* @param other A range.
463
* @returns `true` when start and end are {@link Position.isEqual equal} to
464
* start and end of this range.
465
*/
466
isEqual(other: Range): boolean;
467
468
/**
469
* Intersect `range` with this range and returns a new range or `undefined`
470
* if the ranges have no overlap.
471
*
472
* @param range A range.
473
* @returns A range of the greater start and smaller end positions. Will
474
* return undefined when there is no overlap.
475
*/
476
intersection(range: Range): Range | undefined;
477
478
/**
479
* Compute the union of `other` with this range.
480
*
481
* @param other A range.
482
* @returns A range of smaller start position and the greater end position.
483
*/
484
union(other: Range): Range;
485
486
/**
487
* Derived a new range from this range.
488
*
489
* @param start A position that should be used as start. The default value is the {@link Range.start current start}.
490
* @param end A position that should be used as end. The default value is the {@link Range.end current end}.
491
* @returns A range derived from this range with the given start and end position.
492
* If start and end are not different `this` range will be returned.
493
*/
494
with(start?: Position, end?: Position): Range;
495
496
/**
497
* Derived a new range from this range.
498
*
499
* @param change An object that describes a change to this range.
500
* @returns A range that reflects the given change. Will return `this` range if the change
501
* is not changing anything.
502
*/
503
with(change: {
504
/**
505
* New start position, defaults to {@link Range.start current start}
506
*/
507
start?: Position;
508
/**
509
* New end position, defaults to {@link Range.end current end}
510
*/
511
end?: Position;
512
}): Range;
513
}
514
515
/**
516
* Represents a text selection in an editor.
517
*/
518
export class Selection extends Range {
519
520
/**
521
* The position at which the selection starts.
522
* This position might be before or after {@link Selection.active active}.
523
*/
524
readonly anchor: Position;
525
526
/**
527
* The position of the cursor.
528
* This position might be before or after {@link Selection.anchor anchor}.
529
*/
530
readonly active: Position;
531
532
/**
533
* Create a selection from two positions.
534
*
535
* @param anchor A position.
536
* @param active A position.
537
*/
538
constructor(anchor: Position, active: Position);
539
540
/**
541
* Create a selection from four coordinates.
542
*
543
* @param anchorLine A zero-based line value.
544
* @param anchorCharacter A zero-based character value.
545
* @param activeLine A zero-based line value.
546
* @param activeCharacter A zero-based character value.
547
*/
548
constructor(anchorLine: number, anchorCharacter: number, activeLine: number, activeCharacter: number);
549
550
/**
551
* A selection is reversed if its {@link Selection.anchor anchor} is the {@link Selection.end end} position.
552
*/
553
readonly isReversed: boolean;
554
}
555
556
/**
557
* Represents sources that can cause {@link window.onDidChangeTextEditorSelection selection change events}.
558
*/
559
export enum TextEditorSelectionChangeKind {
560
/**
561
* Selection changed due to typing in the editor.
562
*/
563
Keyboard = 1,
564
/**
565
* Selection change due to clicking in the editor.
566
*/
567
Mouse = 2,
568
/**
569
* Selection changed because a command ran.
570
*/
571
Command = 3
572
}
573
574
/**
575
* Represents an event describing the change in a {@link TextEditor.selections text editor's selections}.
576
*/
577
export interface TextEditorSelectionChangeEvent {
578
/**
579
* The {@link TextEditor text editor} for which the selections have changed.
580
*/
581
readonly textEditor: TextEditor;
582
/**
583
* The new value for the {@link TextEditor.selections text editor's selections}.
584
*/
585
readonly selections: readonly Selection[];
586
/**
587
* The {@link TextEditorSelectionChangeKind change kind} which has triggered this
588
* event. Can be `undefined`.
589
*/
590
readonly kind: TextEditorSelectionChangeKind | undefined;
591
}
592
593
/**
594
* Represents an event describing the change in a {@link TextEditor.visibleRanges text editor's visible ranges}.
595
*/
596
export interface TextEditorVisibleRangesChangeEvent {
597
/**
598
* The {@link TextEditor text editor} for which the visible ranges have changed.
599
*/
600
readonly textEditor: TextEditor;
601
/**
602
* The new value for the {@link TextEditor.visibleRanges text editor's visible ranges}.
603
*/
604
readonly visibleRanges: readonly Range[];
605
}
606
607
/**
608
* Represents an event describing the change in a {@link TextEditor.options text editor's options}.
609
*/
610
export interface TextEditorOptionsChangeEvent {
611
/**
612
* The {@link TextEditor text editor} for which the options have changed.
613
*/
614
readonly textEditor: TextEditor;
615
/**
616
* The new value for the {@link TextEditor.options text editor's options}.
617
*/
618
readonly options: TextEditorOptions;
619
}
620
621
/**
622
* Represents an event describing the change of a {@link TextEditor.viewColumn text editor's view column}.
623
*/
624
export interface TextEditorViewColumnChangeEvent {
625
/**
626
* The {@link TextEditor text editor} for which the view column has changed.
627
*/
628
readonly textEditor: TextEditor;
629
/**
630
* The new value for the {@link TextEditor.viewColumn text editor's view column}.
631
*/
632
readonly viewColumn: ViewColumn;
633
}
634
635
/**
636
* Rendering style of the cursor.
637
*/
638
export enum TextEditorCursorStyle {
639
/**
640
* Render the cursor as a vertical thick line.
641
*/
642
Line = 1,
643
/**
644
* Render the cursor as a block filled.
645
*/
646
Block = 2,
647
/**
648
* Render the cursor as a thick horizontal line.
649
*/
650
Underline = 3,
651
/**
652
* Render the cursor as a vertical thin line.
653
*/
654
LineThin = 4,
655
/**
656
* Render the cursor as a block outlined.
657
*/
658
BlockOutline = 5,
659
/**
660
* Render the cursor as a thin horizontal line.
661
*/
662
UnderlineThin = 6
663
}
664
665
/**
666
* Rendering style of the line numbers.
667
*/
668
export enum TextEditorLineNumbersStyle {
669
/**
670
* Do not render the line numbers.
671
*/
672
Off = 0,
673
/**
674
* Render the line numbers.
675
*/
676
On = 1,
677
/**
678
* Render the line numbers with values relative to the primary cursor location.
679
*/
680
Relative = 2,
681
/**
682
* Render the line numbers on every 10th line number.
683
*/
684
Interval = 3,
685
}
686
687
/**
688
* Represents a {@link TextEditor text editor}'s {@link TextEditor.options options}.
689
*/
690
export interface TextEditorOptions {
691
692
/**
693
* The size in spaces a tab takes. This is used for two purposes:
694
* - the rendering width of a tab character;
695
* - the number of spaces to insert when {@link TextEditorOptions.insertSpaces insertSpaces} is true
696
* and `indentSize` is set to `"tabSize"`.
697
*
698
* When getting a text editor's options, this property will always be a number (resolved).
699
* When setting a text editor's options, this property is optional and it can be a number or `"auto"`.
700
*/
701
tabSize?: number | string;
702
703
/**
704
* The number of spaces to insert when {@link TextEditorOptions.insertSpaces insertSpaces} is true.
705
*
706
* When getting a text editor's options, this property will always be a number (resolved).
707
* When setting a text editor's options, this property is optional and it can be a number or `"tabSize"`.
708
*/
709
indentSize?: number | string;
710
711
/**
712
* When pressing Tab insert {@link TextEditorOptions.tabSize n} spaces.
713
* When getting a text editor's options, this property will always be a boolean (resolved).
714
* When setting a text editor's options, this property is optional and it can be a boolean or `"auto"`.
715
*/
716
insertSpaces?: boolean | string;
717
718
/**
719
* The rendering style of the cursor in this editor.
720
* When getting a text editor's options, this property will always be present.
721
* When setting a text editor's options, this property is optional.
722
*/
723
cursorStyle?: TextEditorCursorStyle;
724
725
/**
726
* Render relative line numbers w.r.t. the current line number.
727
* When getting a text editor's options, this property will always be present.
728
* When setting a text editor's options, this property is optional.
729
*/
730
lineNumbers?: TextEditorLineNumbersStyle;
731
}
732
733
/**
734
* Represents a handle to a set of decorations
735
* sharing the same {@link DecorationRenderOptions styling options} in a {@link TextEditor text editor}.
736
*
737
* To get an instance of a `TextEditorDecorationType` use
738
* {@link window.createTextEditorDecorationType createTextEditorDecorationType}.
739
*/
740
export interface TextEditorDecorationType {
741
742
/**
743
* Internal representation of the handle.
744
*/
745
readonly key: string;
746
747
/**
748
* Remove this decoration type and all decorations on all text editors using it.
749
*/
750
dispose(): void;
751
}
752
753
/**
754
* Represents different {@link TextEditor.revealRange reveal} strategies in a text editor.
755
*/
756
export enum TextEditorRevealType {
757
/**
758
* The range will be revealed with as little scrolling as possible.
759
*/
760
Default = 0,
761
/**
762
* The range will always be revealed in the center of the viewport.
763
*/
764
InCenter = 1,
765
/**
766
* If the range is outside the viewport, it will be revealed in the center of the viewport.
767
* Otherwise, it will be revealed with as little scrolling as possible.
768
*/
769
InCenterIfOutsideViewport = 2,
770
/**
771
* The range will always be revealed at the top of the viewport.
772
*/
773
AtTop = 3
774
}
775
776
/**
777
* Represents different positions for rendering a decoration in an {@link DecorationRenderOptions.overviewRulerLane overview ruler}.
778
* The overview ruler supports three lanes.
779
*/
780
export enum OverviewRulerLane {
781
/**
782
* The left lane of the overview ruler.
783
*/
784
Left = 1,
785
/**
786
* The center lane of the overview ruler.
787
*/
788
Center = 2,
789
/**
790
* The right lane of the overview ruler.
791
*/
792
Right = 4,
793
/**
794
* All lanes of the overview ruler.
795
*/
796
Full = 7
797
}
798
799
/**
800
* Describes the behavior of decorations when typing/editing at their edges.
801
*/
802
export enum DecorationRangeBehavior {
803
/**
804
* The decoration's range will widen when edits occur at the start or end.
805
*/
806
OpenOpen = 0,
807
/**
808
* The decoration's range will not widen when edits occur at the start or end.
809
*/
810
ClosedClosed = 1,
811
/**
812
* The decoration's range will widen when edits occur at the start, but not at the end.
813
*/
814
OpenClosed = 2,
815
/**
816
* The decoration's range will widen when edits occur at the end, but not at the start.
817
*/
818
ClosedOpen = 3
819
}
820
821
/**
822
* Represents options to configure the behavior of showing a {@link TextDocument document} in an {@link TextEditor editor}.
823
*/
824
export interface TextDocumentShowOptions {
825
/**
826
* An optional view column in which the {@link TextEditor editor} should be shown.
827
* The default is the {@link ViewColumn.Active active}. Columns that do not exist
828
* will be created as needed up to the maximum of {@linkcode ViewColumn.Nine}.
829
* Use {@linkcode ViewColumn.Beside} to open the editor to the side of the currently
830
* active one.
831
*/
832
viewColumn?: ViewColumn;
833
834
/**
835
* An optional flag that when `true` will stop the {@link TextEditor editor} from taking focus.
836
*/
837
preserveFocus?: boolean;
838
839
/**
840
* An optional flag that controls if an {@link TextEditor editor}-tab shows as preview. Preview tabs will
841
* be replaced and reused until set to stay - either explicitly or through editing.
842
*
843
* *Note* that the flag is ignored if a user has disabled preview editors in settings.
844
*/
845
preview?: boolean;
846
847
/**
848
* An optional selection to apply for the document in the {@link TextEditor editor}.
849
*/
850
selection?: Range;
851
}
852
853
/**
854
* Represents an event describing the change in a {@link NotebookEditor.selections notebook editor's selections}.
855
*/
856
export interface NotebookEditorSelectionChangeEvent {
857
/**
858
* The {@link NotebookEditor notebook editor} for which the selections have changed.
859
*/
860
readonly notebookEditor: NotebookEditor;
861
862
/**
863
* The new value for the {@link NotebookEditor.selections notebook editor's selections}.
864
*/
865
readonly selections: readonly NotebookRange[];
866
}
867
868
/**
869
* Represents an event describing the change in a {@link NotebookEditor.visibleRanges notebook editor's visibleRanges}.
870
*/
871
export interface NotebookEditorVisibleRangesChangeEvent {
872
/**
873
* The {@link NotebookEditor notebook editor} for which the visible ranges have changed.
874
*/
875
readonly notebookEditor: NotebookEditor;
876
877
/**
878
* The new value for the {@link NotebookEditor.visibleRanges notebook editor's visibleRanges}.
879
*/
880
readonly visibleRanges: readonly NotebookRange[];
881
}
882
883
/**
884
* Represents options to configure the behavior of showing a {@link NotebookDocument notebook document} in an {@link NotebookEditor notebook editor}.
885
*/
886
export interface NotebookDocumentShowOptions {
887
/**
888
* An optional view column in which the {@link NotebookEditor notebook editor} should be shown.
889
* The default is the {@link ViewColumn.Active active}. Columns that do not exist
890
* will be created as needed up to the maximum of {@linkcode ViewColumn.Nine}.
891
* Use {@linkcode ViewColumn.Beside} to open the editor to the side of the currently
892
* active one.
893
*/
894
readonly viewColumn?: ViewColumn;
895
896
/**
897
* An optional flag that when `true` will stop the {@link NotebookEditor notebook editor} from taking focus.
898
*/
899
readonly preserveFocus?: boolean;
900
901
/**
902
* An optional flag that controls if an {@link NotebookEditor notebook editor}-tab shows as preview. Preview tabs will
903
* be replaced and reused until set to stay - either explicitly or through editing. The default behaviour depends
904
* on the `workbench.editor.enablePreview`-setting.
905
*/
906
readonly preview?: boolean;
907
908
/**
909
* An optional selection to apply for the document in the {@link NotebookEditor notebook editor}.
910
*/
911
readonly selections?: readonly NotebookRange[];
912
}
913
914
/**
915
* A reference to one of the workbench colors as defined in https://code.visualstudio.com/api/references/theme-color.
916
* Using a theme color is preferred over a custom color as it gives theme authors and users the possibility to change the color.
917
*/
918
export class ThemeColor {
919
920
/**
921
* The id of this color.
922
*/
923
readonly id: string;
924
925
/**
926
* Creates a reference to a theme color.
927
* @param id of the color. The available colors are listed in https://code.visualstudio.com/api/references/theme-color.
928
*/
929
constructor(id: string);
930
}
931
932
/**
933
* A reference to a named icon. Currently, {@link ThemeIcon.File File}, {@link ThemeIcon.Folder Folder},
934
* and [ThemeIcon ids](https://code.visualstudio.com/api/references/icons-in-labels#icon-listing) are supported.
935
* Using a theme icon is preferred over a custom icon as it gives product theme authors the possibility to change the icons.
936
*
937
* *Note* that theme icons can also be rendered inside labels and descriptions. Places that support theme icons spell this out
938
* and they use the `$(<name>)`-syntax, for instance `quickPick.label = "Hello World $(globe)"`.
939
*/
940
export class ThemeIcon {
941
/**
942
* Reference to an icon representing a file. The icon is taken from the current file icon theme or a placeholder icon is used.
943
*/
944
static readonly File: ThemeIcon;
945
946
/**
947
* Reference to an icon representing a folder. The icon is taken from the current file icon theme or a placeholder icon is used.
948
*/
949
static readonly Folder: ThemeIcon;
950
951
/**
952
* The id of the icon. The available icons are listed in https://code.visualstudio.com/api/references/icons-in-labels#icon-listing.
953
*/
954
readonly id: string;
955
956
/**
957
* The optional ThemeColor of the icon. The color is currently only used in {@link TreeItem}.
958
*/
959
readonly color?: ThemeColor | undefined;
960
961
/**
962
* Creates a reference to a theme icon.
963
* @param id id of the icon. The available icons are listed in https://code.visualstudio.com/api/references/icons-in-labels#icon-listing.
964
* @param color optional `ThemeColor` for the icon. The color is currently only used in {@link TreeItem}.
965
*/
966
constructor(id: string, color?: ThemeColor);
967
}
968
969
/**
970
* Represents an icon in the UI. This is either an uri, separate uris for the light- and dark-themes,
971
* or a {@link ThemeIcon theme icon}.
972
*/
973
export type IconPath = Uri | {
974
/**
975
* The icon path for the light theme.
976
*/
977
light: Uri;
978
/**
979
* The icon path for the dark theme.
980
*/
981
dark: Uri;
982
} | ThemeIcon;
983
984
/**
985
* Represents theme specific rendering styles for a {@link TextEditorDecorationType text editor decoration}.
986
*/
987
export interface ThemableDecorationRenderOptions {
988
/**
989
* Background color of the decoration. Use rgba() and define transparent background colors to play well with other decorations.
990
* Alternatively a color from the color registry can be {@link ThemeColor referenced}.
991
*/
992
backgroundColor?: string | ThemeColor;
993
994
/**
995
* CSS styling property that will be applied to text enclosed by a decoration.
996
*/
997
outline?: string;
998
999
/**
1000
* CSS styling property that will be applied to text enclosed by a decoration.
1001
* Better use 'outline' for setting one or more of the individual outline properties.
1002
*/
1003
outlineColor?: string | ThemeColor;
1004
1005
/**
1006
* CSS styling property that will be applied to text enclosed by a decoration.
1007
* Better use 'outline' for setting one or more of the individual outline properties.
1008
*/
1009
outlineStyle?: string;
1010
1011
/**
1012
* CSS styling property that will be applied to text enclosed by a decoration.
1013
* Better use 'outline' for setting one or more of the individual outline properties.
1014
*/
1015
outlineWidth?: string;
1016
1017
/**
1018
* CSS styling property that will be applied to text enclosed by a decoration.
1019
*/
1020
border?: string;
1021
1022
/**
1023
* CSS styling property that will be applied to text enclosed by a decoration.
1024
* Better use 'border' for setting one or more of the individual border properties.
1025
*/
1026
borderColor?: string | ThemeColor;
1027
1028
/**
1029
* CSS styling property that will be applied to text enclosed by a decoration.
1030
* Better use 'border' for setting one or more of the individual border properties.
1031
*/
1032
borderRadius?: string;
1033
1034
/**
1035
* CSS styling property that will be applied to text enclosed by a decoration.
1036
* Better use 'border' for setting one or more of the individual border properties.
1037
*/
1038
borderSpacing?: string;
1039
1040
/**
1041
* CSS styling property that will be applied to text enclosed by a decoration.
1042
* Better use 'border' for setting one or more of the individual border properties.
1043
*/
1044
borderStyle?: string;
1045
1046
/**
1047
* CSS styling property that will be applied to text enclosed by a decoration.
1048
* Better use 'border' for setting one or more of the individual border properties.
1049
*/
1050
borderWidth?: string;
1051
1052
/**
1053
* CSS styling property that will be applied to text enclosed by a decoration.
1054
*/
1055
fontStyle?: string;
1056
1057
/**
1058
* CSS styling property that will be applied to text enclosed by a decoration.
1059
*/
1060
fontWeight?: string;
1061
1062
/**
1063
* CSS styling property that will be applied to text enclosed by a decoration.
1064
*/
1065
textDecoration?: string;
1066
1067
/**
1068
* CSS styling property that will be applied to text enclosed by a decoration.
1069
*/
1070
cursor?: string;
1071
1072
/**
1073
* CSS styling property that will be applied to text enclosed by a decoration.
1074
*/
1075
color?: string | ThemeColor;
1076
1077
/**
1078
* CSS styling property that will be applied to text enclosed by a decoration.
1079
*/
1080
opacity?: string;
1081
1082
/**
1083
* CSS styling property that will be applied to text enclosed by a decoration.
1084
*/
1085
letterSpacing?: string;
1086
1087
/**
1088
* An **absolute path** or an URI to an image to be rendered in the gutter.
1089
*/
1090
gutterIconPath?: string | Uri;
1091
1092
/**
1093
* Specifies the size of the gutter icon.
1094
* Available values are 'auto', 'contain', 'cover' and any percentage value.
1095
* For further information: https://msdn.microsoft.com/en-us/library/jj127316(v=vs.85).aspx
1096
*/
1097
gutterIconSize?: string;
1098
1099
/**
1100
* The color of the decoration in the overview ruler. Use rgba() and define transparent colors to play well with other decorations.
1101
*/
1102
overviewRulerColor?: string | ThemeColor;
1103
1104
/**
1105
* Defines the rendering options of the attachment that is inserted before the decorated text.
1106
*/
1107
before?: ThemableDecorationAttachmentRenderOptions;
1108
1109
/**
1110
* Defines the rendering options of the attachment that is inserted after the decorated text.
1111
*/
1112
after?: ThemableDecorationAttachmentRenderOptions;
1113
}
1114
1115
/**
1116
* Represents theme specific rendering styles for {@link ThemableDecorationRenderOptions.before before} and
1117
* {@link ThemableDecorationRenderOptions.after after} the content of text decorations.
1118
*/
1119
export interface ThemableDecorationAttachmentRenderOptions {
1120
/**
1121
* Defines a text content that is shown in the attachment. Either an icon or a text can be shown, but not both.
1122
*/
1123
contentText?: string;
1124
/**
1125
* An **absolute path** or an URI to an image to be rendered in the attachment. Either an icon
1126
* or a text can be shown, but not both.
1127
*/
1128
contentIconPath?: string | Uri;
1129
/**
1130
* CSS styling property that will be applied to the decoration attachment.
1131
*/
1132
border?: string;
1133
/**
1134
* CSS styling property that will be applied to text enclosed by a decoration.
1135
*/
1136
borderColor?: string | ThemeColor;
1137
/**
1138
* CSS styling property that will be applied to the decoration attachment.
1139
*/
1140
fontStyle?: string;
1141
/**
1142
* CSS styling property that will be applied to the decoration attachment.
1143
*/
1144
fontWeight?: string;
1145
/**
1146
* CSS styling property that will be applied to the decoration attachment.
1147
*/
1148
textDecoration?: string;
1149
/**
1150
* CSS styling property that will be applied to the decoration attachment.
1151
*/
1152
color?: string | ThemeColor;
1153
/**
1154
* CSS styling property that will be applied to the decoration attachment.
1155
*/
1156
backgroundColor?: string | ThemeColor;
1157
/**
1158
* CSS styling property that will be applied to the decoration attachment.
1159
*/
1160
margin?: string;
1161
/**
1162
* CSS styling property that will be applied to the decoration attachment.
1163
*/
1164
width?: string;
1165
/**
1166
* CSS styling property that will be applied to the decoration attachment.
1167
*/
1168
height?: string;
1169
}
1170
1171
/**
1172
* Represents rendering styles for a {@link TextEditorDecorationType text editor decoration}.
1173
*/
1174
export interface DecorationRenderOptions extends ThemableDecorationRenderOptions {
1175
/**
1176
* Should the decoration be rendered also on the whitespace after the line text.
1177
* Defaults to `false`.
1178
*/
1179
isWholeLine?: boolean;
1180
1181
/**
1182
* Customize the growing behavior of the decoration when edits occur at the edges of the decoration's range.
1183
* Defaults to `DecorationRangeBehavior.OpenOpen`.
1184
*/
1185
rangeBehavior?: DecorationRangeBehavior;
1186
1187
/**
1188
* The position in the overview ruler where the decoration should be rendered.
1189
*/
1190
overviewRulerLane?: OverviewRulerLane;
1191
1192
/**
1193
* Overwrite options for light themes.
1194
*/
1195
light?: ThemableDecorationRenderOptions;
1196
1197
/**
1198
* Overwrite options for dark themes.
1199
*/
1200
dark?: ThemableDecorationRenderOptions;
1201
}
1202
1203
/**
1204
* Represents options for a specific decoration in a {@link TextEditorDecorationType decoration set}.
1205
*/
1206
export interface DecorationOptions {
1207
1208
/**
1209
* Range to which this decoration is applied. The range must not be empty.
1210
*/
1211
range: Range;
1212
1213
/**
1214
* A message that should be rendered when hovering over the decoration.
1215
*/
1216
hoverMessage?: MarkdownString | MarkedString | Array<MarkdownString | MarkedString>;
1217
1218
/**
1219
* Render options applied to the current decoration. For performance reasons, keep the
1220
* number of decoration specific options small, and use decoration types wherever possible.
1221
*/
1222
renderOptions?: DecorationInstanceRenderOptions;
1223
}
1224
1225
/**
1226
* Represents themable render options for decoration instances.
1227
*/
1228
export interface ThemableDecorationInstanceRenderOptions {
1229
/**
1230
* Defines the rendering options of the attachment that is inserted before the decorated text.
1231
*/
1232
before?: ThemableDecorationAttachmentRenderOptions;
1233
1234
/**
1235
* Defines the rendering options of the attachment that is inserted after the decorated text.
1236
*/
1237
after?: ThemableDecorationAttachmentRenderOptions;
1238
}
1239
1240
/**
1241
* Represents render options for decoration instances. See {@link DecorationOptions.renderOptions}.
1242
*/
1243
export interface DecorationInstanceRenderOptions extends ThemableDecorationInstanceRenderOptions {
1244
/**
1245
* Overwrite options for light themes.
1246
*/
1247
light?: ThemableDecorationInstanceRenderOptions;
1248
1249
/**
1250
* Overwrite options for dark themes.
1251
*/
1252
dark?: ThemableDecorationInstanceRenderOptions;
1253
}
1254
1255
/**
1256
* Represents an editor that is attached to a {@link TextDocument document}.
1257
*/
1258
export interface TextEditor {
1259
1260
/**
1261
* The document associated with this text editor. The document will be the same for the entire lifetime of this text editor.
1262
*/
1263
readonly document: TextDocument;
1264
1265
/**
1266
* The primary selection on this text editor. Shorthand for `TextEditor.selections[0]`.
1267
*/
1268
selection: Selection;
1269
1270
/**
1271
* The selections in this text editor. The primary selection is always at index 0.
1272
*/
1273
selections: readonly Selection[];
1274
1275
/**
1276
* The current visible ranges in the editor (vertically).
1277
* This accounts only for vertical scrolling, and not for horizontal scrolling.
1278
*/
1279
readonly visibleRanges: readonly Range[];
1280
1281
/**
1282
* Text editor options.
1283
*/
1284
options: TextEditorOptions;
1285
1286
/**
1287
* The column in which this editor shows. Will be `undefined` in case this
1288
* isn't one of the main editors, e.g. an embedded editor, or when the editor
1289
* column is larger than three.
1290
*/
1291
readonly viewColumn: ViewColumn | undefined;
1292
1293
/**
1294
* Perform an edit on the document associated with this text editor.
1295
*
1296
* The given callback-function is invoked with an {@link TextEditorEdit edit-builder} which must
1297
* be used to make edits. Note that the edit-builder is only valid while the
1298
* callback executes.
1299
*
1300
* @param callback A function which can create edits using an {@link TextEditorEdit edit-builder}.
1301
* @param options The undo/redo behavior around this edit. By default, undo stops will be created before and after this edit.
1302
* @returns A promise that resolves with a value indicating if the edits could be applied.
1303
*/
1304
edit(callback: (editBuilder: TextEditorEdit) => void, options?: {
1305
/**
1306
* Add undo stop before making the edits.
1307
*/
1308
readonly undoStopBefore: boolean;
1309
/**
1310
* Add undo stop after making the edits.
1311
*/
1312
readonly undoStopAfter: boolean;
1313
}): Thenable<boolean>;
1314
1315
/**
1316
* Insert a {@link SnippetString snippet} and put the editor into snippet mode. "Snippet mode"
1317
* means the editor adds placeholders and additional cursors so that the user can complete
1318
* or accept the snippet.
1319
*
1320
* @param snippet The snippet to insert in this edit.
1321
* @param location Position or range at which to insert the snippet, defaults to the current editor selection or selections.
1322
* @param options The undo/redo behavior around this edit. By default, undo stops will be created before and after this edit.
1323
* @returns A promise that resolves with a value indicating if the snippet could be inserted. Note that the promise does not signal
1324
* that the snippet is completely filled-in or accepted.
1325
*/
1326
insertSnippet(snippet: SnippetString, location?: Position | Range | readonly Position[] | readonly Range[], options?: {
1327
/**
1328
* Add undo stop before making the edits.
1329
*/
1330
readonly undoStopBefore: boolean;
1331
/**
1332
* Add undo stop after making the edits.
1333
*/
1334
readonly undoStopAfter: boolean;
1335
/**
1336
* Keep whitespace of the {@link SnippetString.value} as is.
1337
*/
1338
readonly keepWhitespace?: boolean;
1339
}): Thenable<boolean>;
1340
1341
/**
1342
* Adds a set of decorations to the text editor. If a set of decorations already exists with
1343
* the given {@link TextEditorDecorationType decoration type}, they will be replaced. If
1344
* `rangesOrOptions` is empty, the existing decorations with the given {@link TextEditorDecorationType decoration type}
1345
* will be removed.
1346
*
1347
* @see {@link window.createTextEditorDecorationType createTextEditorDecorationType}.
1348
*
1349
* @param decorationType A decoration type.
1350
* @param rangesOrOptions Either {@link Range ranges} or more detailed {@link DecorationOptions options}.
1351
*/
1352
setDecorations(decorationType: TextEditorDecorationType, rangesOrOptions: readonly Range[] | readonly DecorationOptions[]): void;
1353
1354
/**
1355
* Scroll as indicated by `revealType` in order to reveal the given range.
1356
*
1357
* @param range A range.
1358
* @param revealType The scrolling strategy for revealing `range`.
1359
*/
1360
revealRange(range: Range, revealType?: TextEditorRevealType): void;
1361
1362
/**
1363
* Show the text editor.
1364
*
1365
* @deprecated Use {@link window.showTextDocument} instead.
1366
*
1367
* @param column The {@link ViewColumn column} in which to show this editor.
1368
* This method shows unexpected behavior and will be removed in the next major update.
1369
*/
1370
show(column?: ViewColumn): void;
1371
1372
/**
1373
* Hide the text editor.
1374
*
1375
* @deprecated Use the command `workbench.action.closeActiveEditor` instead.
1376
* This method shows unexpected behavior and will be removed in the next major update.
1377
*/
1378
hide(): void;
1379
}
1380
1381
/**
1382
* Represents an end of line character sequence in a {@link TextDocument document}.
1383
*/
1384
export enum EndOfLine {
1385
/**
1386
* The line feed `\n` character.
1387
*/
1388
LF = 1,
1389
/**
1390
* The carriage return line feed `\r\n` sequence.
1391
*/
1392
CRLF = 2
1393
}
1394
1395
/**
1396
* A complex edit that will be applied in one transaction on a TextEditor.
1397
* This holds a description of the edits and if the edits are valid (i.e. no overlapping regions, document was not changed in the meantime, etc.)
1398
* they can be applied on a {@link TextDocument document} associated with a {@link TextEditor text editor}.
1399
*/
1400
export interface TextEditorEdit {
1401
/**
1402
* Replace a certain text region with a new value.
1403
* You can use `\r\n` or `\n` in `value` and they will be normalized to the current {@link TextDocument document}.
1404
*
1405
* @param location The range this operation should remove.
1406
* @param value The new text this operation should insert after removing `location`.
1407
*/
1408
replace(location: Position | Range | Selection, value: string): void;
1409
1410
/**
1411
* Insert text at a location.
1412
* You can use `\r\n` or `\n` in `value` and they will be normalized to the current {@link TextDocument document}.
1413
* Although the equivalent text edit can be made with {@link TextEditorEdit.replace replace}, `insert` will produce a different resulting selection (it will get moved).
1414
*
1415
* @param location The position where the new text should be inserted.
1416
* @param value The new text this operation should insert.
1417
*/
1418
insert(location: Position, value: string): void;
1419
1420
/**
1421
* Delete a certain text region.
1422
*
1423
* @param location The range this operation should remove.
1424
*/
1425
delete(location: Range | Selection): void;
1426
1427
/**
1428
* Set the end of line sequence.
1429
*
1430
* @param endOfLine The new end of line for the {@link TextDocument document}.
1431
*/
1432
setEndOfLine(endOfLine: EndOfLine): void;
1433
}
1434
1435
/**
1436
* A universal resource identifier representing either a file on disk
1437
* or another resource, like untitled resources.
1438
*/
1439
export class Uri {
1440
1441
/**
1442
* Create an URI from a string, e.g. `http://www.example.com/some/path`,
1443
* `file:///usr/home`, or `scheme:with/path`.
1444
*
1445
* *Note* that for a while uris without a `scheme` were accepted. That is not correct
1446
* as all uris should have a scheme. To avoid breakage of existing code the optional
1447
* `strict`-argument has been added. We *strongly* advise to use it, e.g. `Uri.parse('my:uri', true)`
1448
*
1449
* @see {@link Uri.toString}
1450
* @param value The string value of an Uri.
1451
* @param strict Throw an error when `value` is empty or when no `scheme` can be parsed.
1452
* @returns A new Uri instance.
1453
*/
1454
static parse(value: string, strict?: boolean): Uri;
1455
1456
/**
1457
* Create an URI from a file system path. The {@link Uri.scheme scheme}
1458
* will be `file`.
1459
*
1460
* The *difference* between {@link Uri.parse} and {@link Uri.file} is that the latter treats the argument
1461
* as path, not as stringified-uri. E.g. `Uri.file(path)` is *not* the same as
1462
* `Uri.parse('file://' + path)` because the path might contain characters that are
1463
* interpreted (# and ?). See the following sample:
1464
* ```ts
1465
* const good = URI.file('/coding/c#/project1');
1466
* good.scheme === 'file';
1467
* good.path === '/coding/c#/project1';
1468
* good.fragment === '';
1469
*
1470
* const bad = URI.parse('file://' + '/coding/c#/project1');
1471
* bad.scheme === 'file';
1472
* bad.path === '/coding/c'; // path is now broken
1473
* bad.fragment === '/project1';
1474
* ```
1475
*
1476
* @param path A file system or UNC path.
1477
* @returns A new Uri instance.
1478
*/
1479
static file(path: string): Uri;
1480
1481
/**
1482
* Create a new uri which path is the result of joining
1483
* the path of the base uri with the provided path segments.
1484
*
1485
* - Note 1: `joinPath` only affects the path component
1486
* and all other components (scheme, authority, query, and fragment) are
1487
* left as they are.
1488
* - Note 2: The base uri must have a path; an error is thrown otherwise.
1489
*
1490
* The path segments are normalized in the following ways:
1491
* - sequences of path separators (`/` or `\`) are replaced with a single separator
1492
* - for `file`-uris on windows, the backslash-character (`\`) is considered a path-separator
1493
* - the `..`-segment denotes the parent segment, the `.` denotes the current segment
1494
* - paths have a root which always remains, for instance on windows drive-letters are roots
1495
* so that is true: `joinPath(Uri.file('file:///c:/root'), '../../other').fsPath === 'c:/other'`
1496
*
1497
* @param base An uri. Must have a path.
1498
* @param pathSegments One more more path fragments
1499
* @returns A new uri which path is joined with the given fragments
1500
*/
1501
static joinPath(base: Uri, ...pathSegments: string[]): Uri;
1502
1503
/**
1504
* Create an URI from its component parts
1505
*
1506
* @see {@link Uri.toString}
1507
* @param components The component parts of an Uri.
1508
* @returns A new Uri instance.
1509
*/
1510
static from(components: {
1511
/**
1512
* The scheme of the uri
1513
*/
1514
readonly scheme: string;
1515
/**
1516
* The authority of the uri
1517
*/
1518
readonly authority?: string;
1519
/**
1520
* The path of the uri
1521
*/
1522
readonly path?: string;
1523
/**
1524
* The query string of the uri
1525
*/
1526
readonly query?: string;
1527
/**
1528
* The fragment identifier of the uri
1529
*/
1530
readonly fragment?: string;
1531
}): Uri;
1532
1533
/**
1534
* Use the `file` and `parse` factory functions to create new `Uri` objects.
1535
*/
1536
private constructor(scheme: string, authority: string, path: string, query: string, fragment: string);
1537
1538
/**
1539
* Scheme is the `http` part of `http://www.example.com/some/path?query#fragment`.
1540
* The part before the first colon.
1541
*/
1542
readonly scheme: string;
1543
1544
/**
1545
* Authority is the `www.example.com` part of `http://www.example.com/some/path?query#fragment`.
1546
* The part between the first double slashes and the next slash.
1547
*/
1548
readonly authority: string;
1549
1550
/**
1551
* Path is the `/some/path` part of `http://www.example.com/some/path?query#fragment`.
1552
*/
1553
readonly path: string;
1554
1555
/**
1556
* Query is the `query` part of `http://www.example.com/some/path?query#fragment`.
1557
*/
1558
readonly query: string;
1559
1560
/**
1561
* Fragment is the `fragment` part of `http://www.example.com/some/path?query#fragment`.
1562
*/
1563
readonly fragment: string;
1564
1565
/**
1566
* The string representing the corresponding file system path of this Uri.
1567
*
1568
* Will handle UNC paths and normalize windows drive letters to lower-case. Also
1569
* uses the platform specific path separator.
1570
*
1571
* * Will *not* validate the path for invalid characters and semantics.
1572
* * Will *not* look at the scheme of this Uri.
1573
* * The resulting string shall *not* be used for display purposes but
1574
* for disk operations, like `readFile` et al.
1575
*
1576
* The *difference* to the {@linkcode Uri.path path}-property is the use of the platform specific
1577
* path separator and the handling of UNC paths. The sample below outlines the difference:
1578
* ```ts
1579
* const u = URI.parse('file://server/c$/folder/file.txt')
1580
* u.authority === 'server'
1581
* u.path === '/c$/folder/file.txt'
1582
* u.fsPath === '\\server\c$\folder\file.txt'
1583
* ```
1584
*/
1585
readonly fsPath: string;
1586
1587
/**
1588
* Derive a new Uri from this Uri.
1589
*
1590
* ```ts
1591
* let file = Uri.parse('before:some/file/path');
1592
* let other = file.with({ scheme: 'after' });
1593
* assert.ok(other.toString() === 'after:some/file/path');
1594
* ```
1595
*
1596
* @param change An object that describes a change to this Uri. To unset components use `null` or
1597
* the empty string.
1598
* @returns A new Uri that reflects the given change. Will return `this` Uri if the change
1599
* is not changing anything.
1600
*/
1601
with(change: {
1602
/**
1603
* The new scheme, defaults to this Uri's scheme.
1604
*/
1605
scheme?: string;
1606
/**
1607
* The new authority, defaults to this Uri's authority.
1608
*/
1609
authority?: string;
1610
/**
1611
* The new path, defaults to this Uri's path.
1612
*/
1613
path?: string;
1614
/**
1615
* The new query, defaults to this Uri's query.
1616
*/
1617
query?: string;
1618
/**
1619
* The new fragment, defaults to this Uri's fragment.
1620
*/
1621
fragment?: string;
1622
}): Uri;
1623
1624
/**
1625
* Returns a string representation of this Uri. The representation and normalization
1626
* of a URI depends on the scheme.
1627
*
1628
* * The resulting string can be safely used with {@link Uri.parse}.
1629
* * The resulting string shall *not* be used for display purposes.
1630
*
1631
* *Note* that the implementation will encode _aggressive_ which often leads to unexpected,
1632
* but not incorrect, results. For instance, colons are encoded to `%3A` which might be unexpected
1633
* in file-uri. Also `&` and `=` will be encoded which might be unexpected for http-uris. For stability
1634
* reasons this cannot be changed anymore. If you suffer from too aggressive encoding you should use
1635
* the `skipEncoding`-argument: `uri.toString(true)`.
1636
*
1637
* @param skipEncoding Do not percentage-encode the result, defaults to `false`. Note that
1638
* the `#` and `?` characters occurring in the path will always be encoded.
1639
* @returns A string representation of this Uri.
1640
*/
1641
toString(skipEncoding?: boolean): string;
1642
1643
/**
1644
* Returns a JSON representation of this Uri.
1645
*
1646
* @returns An object.
1647
*/
1648
toJSON(): any;
1649
}
1650
1651
/**
1652
* A cancellation token is passed to an asynchronous or long running
1653
* operation to request cancellation, like cancelling a request
1654
* for completion items because the user continued to type.
1655
*
1656
* To get an instance of a `CancellationToken` use a
1657
* {@link CancellationTokenSource}.
1658
*/
1659
export interface CancellationToken {
1660
1661
/**
1662
* Is `true` when the token has been cancelled, `false` otherwise.
1663
*/
1664
isCancellationRequested: boolean;
1665
1666
/**
1667
* An {@link Event} which fires upon cancellation.
1668
*/
1669
readonly onCancellationRequested: Event<any>;
1670
}
1671
1672
/**
1673
* A cancellation source creates and controls a {@link CancellationToken cancellation token}.
1674
*/
1675
export class CancellationTokenSource {
1676
1677
/**
1678
* The cancellation token of this source.
1679
*/
1680
token: CancellationToken;
1681
1682
/**
1683
* Signal cancellation on the token.
1684
*/
1685
cancel(): void;
1686
1687
/**
1688
* Dispose object and free resources.
1689
*/
1690
dispose(): void;
1691
}
1692
1693
/**
1694
* An error type that should be used to signal cancellation of an operation.
1695
*
1696
* This type can be used in response to a {@link CancellationToken cancellation token}
1697
* being cancelled or when an operation is being cancelled by the
1698
* executor of that operation.
1699
*/
1700
export class CancellationError extends Error {
1701
1702
/**
1703
* Creates a new cancellation error.
1704
*/
1705
constructor();
1706
}
1707
1708
/**
1709
* Represents a type which can release resources, such
1710
* as event listening or a timer.
1711
*/
1712
export class Disposable {
1713
1714
/**
1715
* Combine many disposable-likes into one. You can use this method when having objects with
1716
* a dispose function which aren't instances of `Disposable`.
1717
*
1718
* @param disposableLikes Objects that have at least a `dispose`-function member. Note that asynchronous
1719
* dispose-functions aren't awaited.
1720
* @returns Returns a new disposable which, upon dispose, will
1721
* dispose all provided disposables.
1722
*/
1723
static from(...disposableLikes: {
1724
/**
1725
* Function to clean up resources.
1726
*/
1727
dispose: () => any;
1728
}[]): Disposable;
1729
1730
/**
1731
* Creates a new disposable that calls the provided function
1732
* on dispose.
1733
*
1734
* *Note* that an asynchronous function is not awaited.
1735
*
1736
* @param callOnDispose Function that disposes something.
1737
*/
1738
constructor(callOnDispose: () => any);
1739
1740
/**
1741
* Dispose this object.
1742
*/
1743
dispose(): any;
1744
}
1745
1746
/**
1747
* Represents a typed event.
1748
*
1749
* A function that represents an event to which you subscribe by calling it with
1750
* a listener function as argument.
1751
*
1752
* @example
1753
* item.onDidChange(function(event) { console.log("Event happened: " + event); });
1754
*/
1755
export interface Event<T> {
1756
1757
/**
1758
* A function that represents an event to which you subscribe by calling it with
1759
* a listener function as argument.
1760
*
1761
* @param listener The listener function will be called when the event happens.
1762
* @param thisArgs The `this`-argument which will be used when calling the event listener.
1763
* @param disposables An array to which a {@link Disposable} will be added.
1764
* @returns A disposable which unsubscribes the event listener.
1765
*/
1766
(listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]): Disposable;
1767
}
1768
1769
/**
1770
* An event emitter can be used to create and manage an {@link Event} for others
1771
* to subscribe to. One emitter always owns one event.
1772
*
1773
* Use this class if you want to provide event from within your extension, for instance
1774
* inside a {@link TextDocumentContentProvider} or when providing
1775
* API to other extensions.
1776
*/
1777
export class EventEmitter<T> {
1778
1779
/**
1780
* The event listeners can subscribe to.
1781
*/
1782
event: Event<T>;
1783
1784
/**
1785
* Notify all subscribers of the {@link EventEmitter.event event}. Failure
1786
* of one or more listener will not fail this function call.
1787
*
1788
* @param data The event object.
1789
*/
1790
fire(data: T): void;
1791
1792
/**
1793
* Dispose this object and free resources.
1794
*/
1795
dispose(): void;
1796
}
1797
1798
/**
1799
* A file system watcher notifies about changes to files and folders
1800
* on disk or from other {@link FileSystemProvider FileSystemProviders}.
1801
*
1802
* To get an instance of a `FileSystemWatcher` use
1803
* {@link workspace.createFileSystemWatcher createFileSystemWatcher}.
1804
*/
1805
export interface FileSystemWatcher extends Disposable {
1806
1807
/**
1808
* true if this file system watcher has been created such that
1809
* it ignores creation file system events.
1810
*/
1811
readonly ignoreCreateEvents: boolean;
1812
1813
/**
1814
* true if this file system watcher has been created such that
1815
* it ignores change file system events.
1816
*/
1817
readonly ignoreChangeEvents: boolean;
1818
1819
/**
1820
* true if this file system watcher has been created such that
1821
* it ignores delete file system events.
1822
*/
1823
readonly ignoreDeleteEvents: boolean;
1824
1825
/**
1826
* An event which fires on file/folder creation.
1827
*/
1828
readonly onDidCreate: Event<Uri>;
1829
1830
/**
1831
* An event which fires on file/folder change.
1832
*/
1833
readonly onDidChange: Event<Uri>;
1834
1835
/**
1836
* An event which fires on file/folder deletion.
1837
*/
1838
readonly onDidDelete: Event<Uri>;
1839
}
1840
1841
/**
1842
* A text document content provider allows to add readonly documents
1843
* to the editor, such as source from a dll or generated html from md.
1844
*
1845
* Content providers are {@link workspace.registerTextDocumentContentProvider registered}
1846
* for a {@link Uri.scheme uri-scheme}. When a uri with that scheme is to
1847
* be {@link workspace.openTextDocument loaded} the content provider is
1848
* asked.
1849
*/
1850
export interface TextDocumentContentProvider {
1851
1852
/**
1853
* An event to signal a resource has changed.
1854
*/
1855
onDidChange?: Event<Uri>;
1856
1857
/**
1858
* Provide textual content for a given uri.
1859
*
1860
* The editor will use the returned string-content to create a readonly
1861
* {@link TextDocument document}. Resources allocated should be released when
1862
* the corresponding document has been {@link workspace.onDidCloseTextDocument closed}.
1863
*
1864
* **Note**: The contents of the created {@link TextDocument document} might not be
1865
* identical to the provided text due to end-of-line-sequence normalization.
1866
*
1867
* @param uri An uri which scheme matches the scheme this provider was {@link workspace.registerTextDocumentContentProvider registered} for.
1868
* @param token A cancellation token.
1869
* @returns A string or a thenable that resolves to such.
1870
*/
1871
provideTextDocumentContent(uri: Uri, token: CancellationToken): ProviderResult<string>;
1872
}
1873
1874
/**
1875
* Defines the kind of {@link QuickPickItem quick pick item}.
1876
*/
1877
export enum QuickPickItemKind {
1878
/**
1879
* A separator item that provides a visual grouping.
1880
*
1881
* When a {@link QuickPickItem} has a kind of {@link Separator}, the item is just a visual separator
1882
* and does not represent a selectable item. The only property that applies is
1883
* {@link QuickPickItem.label label}. All other properties on {@link QuickPickItem} will be ignored
1884
* and have no effect.
1885
*/
1886
Separator = -1,
1887
/**
1888
* The default kind for an item that can be selected in the quick pick.
1889
*/
1890
Default = 0,
1891
}
1892
1893
/**
1894
* Represents an item that can be selected from a list of items.
1895
*/
1896
export interface QuickPickItem {
1897
1898
/**
1899
* A human-readable string which is rendered prominently.
1900
*
1901
* Supports rendering of {@link ThemeIcon theme icons} via the `$(<name>)`-syntax.
1902
*
1903
* **Note:** When {@link QuickPickItem.kind kind} is set to {@link QuickPickItemKind.Default} (so a regular
1904
* item instead of a separator), it supports rendering of {@link ThemeIcon theme icons} via the
1905
* `$(<name>)`-syntax.
1906
*/
1907
label: string;
1908
1909
/**
1910
* The kind of this item that determines how it is rendered in the quick pick.
1911
*
1912
* When not specified, the default is {@link QuickPickItemKind.Default}.
1913
*/
1914
kind?: QuickPickItemKind;
1915
1916
/**
1917
* The icon for the item.
1918
*/
1919
iconPath?: IconPath;
1920
1921
/**
1922
* A human-readable string which is rendered less prominently in the same line.
1923
*
1924
* Supports rendering of {@link ThemeIcon theme icons} via the `$(<name>)`-syntax.
1925
*
1926
* **Note:** This property is ignored when {@link QuickPickItem.kind kind} is set to
1927
* {@link QuickPickItemKind.Separator}.
1928
*/
1929
description?: string;
1930
1931
/**
1932
* A human-readable string which is rendered less prominently in a separate line.
1933
*
1934
* Supports rendering of {@link ThemeIcon theme icons} via the `$(<name>)`-syntax.
1935
*
1936
* **Note:** This property is ignored when {@link QuickPickItem.kind kind} is set to
1937
* {@link QuickPickItemKind.Separator}.
1938
*/
1939
detail?: string;
1940
1941
/**
1942
* A {@link Uri} representing the resource associated with this item.
1943
*
1944
* When set, this property is used to automatically derive several item properties if they are not explicitly provided:
1945
* - **Label**: Derived from the resource's file name when {@link QuickPickItem.label label} is not provided or is empty.
1946
* - **Description**: Derived from the resource's path when {@link QuickPickItem.description description} is not provided or is empty.
1947
* - **Icon**: Derived from the current file icon theme when {@link QuickPickItem.iconPath iconPath} is set to
1948
* {@link ThemeIcon.File} or {@link ThemeIcon.Folder}.
1949
*/
1950
resourceUri?: Uri;
1951
1952
/**
1953
* Optional flag indicating if this item is initially selected.
1954
*
1955
* This is only honored when using the {@link window.showQuickPick showQuickPick} API. To do the same
1956
* thing with the {@link window.createQuickPick createQuickPick} API, simply set the
1957
* {@link QuickPick.selectedItems selectedItems} to the items you want selected initially.
1958
*
1959
* **Note:** This is only honored when the picker allows multiple selections.
1960
*
1961
* @see {@link QuickPickOptions.canPickMany}
1962
*
1963
* **Note:** This property is ignored when {@link QuickPickItem.kind kind} is set to
1964
* {@link QuickPickItemKind.Separator}.
1965
*/
1966
picked?: boolean;
1967
1968
/**
1969
* Determines if this item is always shown, even when filtered out by the user's input.
1970
*
1971
* **Note:** This property is ignored when {@link QuickPickItem.kind kind} is set to
1972
* {@link QuickPickItemKind.Separator}.
1973
*/
1974
alwaysShow?: boolean;
1975
1976
/**
1977
* Optional buttons that will be rendered on this particular item.
1978
*
1979
* These buttons will trigger an {@link QuickPickItemButtonEvent} when pressed. Buttons are only rendered
1980
* when using a quick pick created by the {@link window.createQuickPick createQuickPick} API. Buttons are
1981
* not rendered when using the {@link window.showQuickPick showQuickPick} API.
1982
*
1983
* **Note:** This property is ignored when {@link QuickPickItem.kind kind} is set to
1984
* {@link QuickPickItemKind.Separator}.
1985
*/
1986
buttons?: readonly QuickInputButton[];
1987
}
1988
1989
/**
1990
* Options to configure the behavior of the quick pick UI.
1991
*/
1992
export interface QuickPickOptions {
1993
1994
/**
1995
* An optional title for the quick pick.
1996
*/
1997
title?: string;
1998
1999
/**
2000
* Determines if the {@link QuickPickItem.description description} should be included when filtering items. Defaults to `false`.
2001
*/
2002
matchOnDescription?: boolean;
2003
2004
/**
2005
* Determines if the {@link QuickPickItem.detail detail} should be included when filtering items. Defaults to `false`.
2006
*/
2007
matchOnDetail?: boolean;
2008
2009
/**
2010
* An optional string to show as placeholder in the input box to guide the user.
2011
*/
2012
placeHolder?: string;
2013
2014
/**
2015
* Optional text that provides instructions or context to the user.
2016
*
2017
* The prompt is displayed below the input box and above the list of items.
2018
*/
2019
prompt?: string;
2020
2021
/**
2022
* Set to `true` to keep the picker open when focus moves to another part of the editor or to another window.
2023
* This setting is ignored on iPad and is always `false`.
2024
*/
2025
ignoreFocusOut?: boolean;
2026
2027
/**
2028
* Determines if the picker allows multiple selections. When `true`, the result is an array of picks.
2029
*/
2030
canPickMany?: boolean;
2031
2032
/**
2033
* An optional function that is invoked whenever an item is selected.
2034
*/
2035
onDidSelectItem?(item: QuickPickItem | string): any;
2036
}
2037
2038
/**
2039
* Options to configure the behavior of the {@link WorkspaceFolder workspace folder} pick UI.
2040
*/
2041
export interface WorkspaceFolderPickOptions {
2042
2043
/**
2044
* An optional string to show as placeholder in the input box to guide the user.
2045
*/
2046
placeHolder?: string;
2047
2048
/**
2049
* Set to `true` to keep the picker open when focus moves to another part of the editor or to another window.
2050
* This setting is ignored on iPad and is always `false`.
2051
*/
2052
ignoreFocusOut?: boolean;
2053
}
2054
2055
/**
2056
* Options to configure the behavior of a file open dialog.
2057
*
2058
* * Note 1: On Windows and Linux, a file dialog cannot be both a file selector and a folder selector, so if you
2059
* set both `canSelectFiles` and `canSelectFolders` to `true` on these platforms, a folder selector will be shown.
2060
* * Note 2: Explicitly setting `canSelectFiles` and `canSelectFolders` to `false` is futile
2061
* and the editor then silently adjusts the options to select files.
2062
*/
2063
export interface OpenDialogOptions {
2064
/**
2065
* The resource the dialog shows when opened.
2066
*/
2067
defaultUri?: Uri;
2068
2069
/**
2070
* A human-readable string for the open button.
2071
*/
2072
openLabel?: string;
2073
2074
/**
2075
* Allow to select files, defaults to `true`.
2076
*/
2077
canSelectFiles?: boolean;
2078
2079
/**
2080
* Allow to select folders, defaults to `false`.
2081
*/
2082
canSelectFolders?: boolean;
2083
2084
/**
2085
* Allow to select many files or folders.
2086
*/
2087
canSelectMany?: boolean;
2088
2089
/**
2090
* A set of file filters that are used by the dialog. Each entry is a human-readable label,
2091
* like "TypeScript", and an array of extensions, for example:
2092
* ```ts
2093
* {
2094
* 'Images': ['png', 'jpg'],
2095
* 'TypeScript': ['ts', 'tsx']
2096
* }
2097
* ```
2098
*/
2099
filters?: { [name: string]: string[] };
2100
2101
/**
2102
* Dialog title.
2103
*
2104
* This parameter might be ignored, as not all operating systems display a title on open dialogs
2105
* (for example, macOS).
2106
*/
2107
title?: string;
2108
}
2109
2110
/**
2111
* Options to configure the behaviour of a file save dialog.
2112
*/
2113
export interface SaveDialogOptions {
2114
/**
2115
* The resource the dialog shows when opened.
2116
*/
2117
defaultUri?: Uri;
2118
2119
/**
2120
* A human-readable string for the save button.
2121
*/
2122
saveLabel?: string;
2123
2124
/**
2125
* A set of file filters that are used by the dialog. Each entry is a human-readable label,
2126
* like "TypeScript", and an array of extensions, for example:
2127
* ```ts
2128
* {
2129
* 'Images': ['png', 'jpg'],
2130
* 'TypeScript': ['ts', 'tsx']
2131
* }
2132
* ```
2133
*/
2134
filters?: { [name: string]: string[] };
2135
2136
/**
2137
* Dialog title.
2138
*
2139
* This parameter might be ignored, as not all operating systems display a title on save dialogs
2140
* (for example, macOS).
2141
*/
2142
title?: string;
2143
}
2144
2145
/**
2146
* Represents an action that is shown with an information, warning, or
2147
* error message.
2148
*
2149
* @see {@link window.showInformationMessage showInformationMessage}
2150
* @see {@link window.showWarningMessage showWarningMessage}
2151
* @see {@link window.showErrorMessage showErrorMessage}
2152
*/
2153
export interface MessageItem {
2154
2155
/**
2156
* A short title like 'Retry', 'Open Log' etc.
2157
*/
2158
title: string;
2159
2160
/**
2161
* A hint for modal dialogs that the item should be triggered
2162
* when the user cancels the dialog (e.g. by pressing the ESC
2163
* key).
2164
*
2165
* Note: this option is ignored for non-modal messages.
2166
*/
2167
isCloseAffordance?: boolean;
2168
}
2169
2170
/**
2171
* Options to configure the behavior of the message.
2172
*
2173
* @see {@link window.showInformationMessage showInformationMessage}
2174
* @see {@link window.showWarningMessage showWarningMessage}
2175
* @see {@link window.showErrorMessage showErrorMessage}
2176
*/
2177
export interface MessageOptions {
2178
2179
/**
2180
* Indicates that this message should be modal.
2181
*/
2182
modal?: boolean;
2183
2184
/**
2185
* Human-readable detail message that is rendered less prominent. _Note_ that detail
2186
* is only shown for {@link MessageOptions.modal modal} messages.
2187
*/
2188
detail?: string;
2189
}
2190
2191
/**
2192
* Severity levels for input box validation messages.
2193
*/
2194
export enum InputBoxValidationSeverity {
2195
/**
2196
* Indicates an informational message that does not prevent input acceptance.
2197
*/
2198
Info = 1,
2199
/**
2200
* Indicates a warning message that does not prevent input acceptance.
2201
*/
2202
Warning = 2,
2203
/**
2204
* Indicates an error message that prevents the user from accepting the input.
2205
*/
2206
Error = 3
2207
}
2208
2209
/**
2210
* Represents a validation message for an {@link InputBox}.
2211
*/
2212
export interface InputBoxValidationMessage {
2213
/**
2214
* The validation message to display to the user.
2215
*/
2216
readonly message: string;
2217
2218
/**
2219
* The severity level of the validation message.
2220
*
2221
* **Note:** When using {@link InputBoxValidationSeverity.Error}, the user will not be able to accept
2222
* the input (e.g., by pressing Enter). {@link InputBoxValidationSeverity.Info Info} and
2223
* {@link InputBoxValidationSeverity.Warning Warning} severities will still allow the input to be accepted.
2224
*/
2225
readonly severity: InputBoxValidationSeverity;
2226
}
2227
2228
/**
2229
* Options to configure the behavior of the input box UI.
2230
*/
2231
export interface InputBoxOptions {
2232
2233
/**
2234
* An optional string that represents the title of the input box.
2235
*/
2236
title?: string;
2237
2238
/**
2239
* The value to pre-fill in the input box.
2240
*/
2241
value?: string;
2242
2243
/**
2244
* Selection of the pre-filled {@linkcode InputBoxOptions.value value}. Defined as tuple of two number where the
2245
* first is the inclusive start index and the second the exclusive end index. When `undefined` the whole
2246
* pre-filled value will be selected, when empty (start equals end) only the cursor will be set,
2247
* otherwise the defined range will be selected.
2248
*/
2249
valueSelection?: [number, number];
2250
2251
/**
2252
* The text to display underneath the input box.
2253
*/
2254
prompt?: string;
2255
2256
/**
2257
* An optional string to show as placeholder in the input box to guide the user what to type.
2258
*/
2259
placeHolder?: string;
2260
2261
/**
2262
* Controls if a password input is shown. Password input hides the typed text.
2263
*/
2264
password?: boolean;
2265
2266
/**
2267
* Set to `true` to keep the input box open when focus moves to another part of the editor or to another window.
2268
* This setting is ignored on iPad and is always false.
2269
*/
2270
ignoreFocusOut?: boolean;
2271
2272
/**
2273
* An optional function that will be called to validate input and to give a hint
2274
* to the user.
2275
*
2276
* @param value The current value of the input box.
2277
* @returns Either a human-readable string which is presented as an error message or an {@link InputBoxValidationMessage}
2278
* which can provide a specific message severity. Return `undefined`, `null`, or the empty string when 'value' is valid.
2279
*/
2280
validateInput?(value: string): string | InputBoxValidationMessage | undefined | null |
2281
Thenable<string | InputBoxValidationMessage | undefined | null>;
2282
}
2283
2284
/**
2285
* A relative pattern is a helper to construct glob patterns that are matched
2286
* relatively to a base file path. The base path can either be an absolute file
2287
* path as string or uri or a {@link WorkspaceFolder workspace folder}, which is the
2288
* preferred way of creating the relative pattern.
2289
*/
2290
export class RelativePattern {
2291
2292
/**
2293
* A base file path to which this pattern will be matched against relatively. The
2294
* file path must be absolute, should not have any trailing path separators and
2295
* not include any relative segments (`.` or `..`).
2296
*/
2297
baseUri: Uri;
2298
2299
/**
2300
* A base file path to which this pattern will be matched against relatively.
2301
*
2302
* This matches the `fsPath` value of {@link RelativePattern.baseUri}.
2303
*
2304
* *Note:* updating this value will update {@link RelativePattern.baseUri} to
2305
* be a uri with `file` scheme.
2306
*
2307
* @deprecated This property is deprecated, please use {@link RelativePattern.baseUri} instead.
2308
*/
2309
base: string;
2310
2311
/**
2312
* A file glob pattern like `*.{ts,js}` that will be matched on file paths
2313
* relative to the base path.
2314
*
2315
* Example: Given a base of `/home/work/folder` and a file path of `/home/work/folder/index.js`,
2316
* the file glob pattern will match on `index.js`.
2317
*/
2318
pattern: string;
2319
2320
/**
2321
* Creates a new relative pattern object with a base file path and pattern to match. This pattern
2322
* will be matched on file paths relative to the base.
2323
*
2324
* Example:
2325
* ```ts
2326
* const folder = vscode.workspace.workspaceFolders?.[0];
2327
* if (folder) {
2328
*
2329
* // Match any TypeScript file in the root of this workspace folder
2330
* const pattern1 = new vscode.RelativePattern(folder, '*.ts');
2331
*
2332
* // Match any TypeScript file in `someFolder` inside this workspace folder
2333
* const pattern2 = new vscode.RelativePattern(folder, 'someFolder/*.ts');
2334
* }
2335
* ```
2336
*
2337
* @param base A base to which this pattern will be matched against relatively. It is recommended
2338
* to pass in a {@link WorkspaceFolder workspace folder} if the pattern should match inside the workspace.
2339
* Otherwise, a uri or string should only be used if the pattern is for a file path outside the workspace.
2340
* @param pattern A file glob pattern like `*.{ts,js}` that will be matched on paths relative to the base.
2341
*/
2342
constructor(base: WorkspaceFolder | Uri | string, pattern: string);
2343
}
2344
2345
/**
2346
* A file glob pattern to match file paths against. This can either be a glob pattern string
2347
* (like `**​/*.{ts,js}` or `*.{ts,js}`) or a {@link RelativePattern relative pattern}.
2348
*
2349
* Glob patterns can have the following syntax:
2350
* * `*` to match zero or more characters in a path segment
2351
* * `?` to match on one character in a path segment
2352
* * `**` to match any number of path segments, including none
2353
* * `{}` to group conditions (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files)
2354
* * `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)
2355
* * `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)
2356
*
2357
* Note: a backslash (`\`) is not valid within a glob pattern. If you have an existing file
2358
* path to match against, consider to use the {@link RelativePattern relative pattern} support
2359
* that takes care of converting any backslash into slash. Otherwise, make sure to convert
2360
* any backslash to slash when creating the glob pattern.
2361
*/
2362
export type GlobPattern = string | RelativePattern;
2363
2364
/**
2365
* A document filter denotes a document by different properties like
2366
* the {@link TextDocument.languageId language}, the {@link Uri.scheme scheme} of
2367
* its resource, or a glob-pattern that is applied to the {@link TextDocument.fileName path}.
2368
*
2369
* @example <caption>A language filter that applies to typescript files on disk</caption>
2370
* { language: 'typescript', scheme: 'file' }
2371
*
2372
* @example <caption>A language filter that applies to all package.json paths</caption>
2373
* { language: 'json', pattern: '**​/package.json' }
2374
*/
2375
export interface DocumentFilter {
2376
2377
/**
2378
* A language id, like `typescript`.
2379
*/
2380
readonly language?: string;
2381
2382
/**
2383
* The {@link NotebookDocument.notebookType type} of a notebook, like `jupyter-notebook`. This allows
2384
* to narrow down on the type of a notebook that a {@link NotebookCell.document cell document} belongs to.
2385
*
2386
* *Note* that setting the `notebookType`-property changes how `scheme` and `pattern` are interpreted. When set
2387
* they are evaluated against the {@link NotebookDocument.uri notebook uri}, not the document uri.
2388
*
2389
* @example <caption>Match python document inside jupyter notebook that aren't stored yet (`untitled`)</caption>
2390
* { language: 'python', notebookType: 'jupyter-notebook', scheme: 'untitled' }
2391
*/
2392
readonly notebookType?: string;
2393
2394
/**
2395
* A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.
2396
*/
2397
readonly scheme?: string;
2398
2399
/**
2400
* A {@link GlobPattern glob pattern} that is matched on the absolute path of the document. Use a {@link RelativePattern relative pattern}
2401
* to filter documents to a {@link WorkspaceFolder workspace folder}.
2402
*/
2403
readonly pattern?: GlobPattern;
2404
}
2405
2406
/**
2407
* A language selector is the combination of one or many language identifiers
2408
* and {@link DocumentFilter language filters}.
2409
*
2410
* *Note* that a document selector that is just a language identifier selects *all*
2411
* documents, even those that are not saved on disk. Only use such selectors when
2412
* a feature works without further context, e.g. without the need to resolve related
2413
* 'files'.
2414
*
2415
* @example
2416
* let sel:DocumentSelector = { scheme: 'file', language: 'typescript' };
2417
*/
2418
export type DocumentSelector = DocumentFilter | string | ReadonlyArray<DocumentFilter | string>;
2419
2420
/**
2421
* A provider result represents the values a provider, like the {@linkcode HoverProvider},
2422
* may return. For once this is the actual result type `T`, like `Hover`, or a thenable that resolves
2423
* to that type `T`. In addition, `null` and `undefined` can be returned - either directly or from a
2424
* thenable.
2425
*
2426
* The snippets below are all valid implementations of the {@linkcode HoverProvider}:
2427
*
2428
* ```ts
2429
* let a: HoverProvider = {
2430
* provideHover(doc, pos, token): ProviderResult<Hover> {
2431
* return new Hover('Hello World');
2432
* }
2433
* }
2434
*
2435
* let b: HoverProvider = {
2436
* provideHover(doc, pos, token): ProviderResult<Hover> {
2437
* return new Promise(resolve => {
2438
* resolve(new Hover('Hello World'));
2439
* });
2440
* }
2441
* }
2442
*
2443
* let c: HoverProvider = {
2444
* provideHover(doc, pos, token): ProviderResult<Hover> {
2445
* return; // undefined
2446
* }
2447
* }
2448
* ```
2449
*/
2450
export type ProviderResult<T> = T | undefined | null | Thenable<T | undefined | null>;
2451
2452
/**
2453
* Kind of a code action.
2454
*
2455
* Kinds are a hierarchical list of identifiers separated by `.`, e.g. `"refactor.extract.function"`.
2456
*
2457
* Code action kinds are used by the editor for UI elements such as the refactoring context menu. Users
2458
* can also trigger code actions with a specific kind with the `editor.action.codeAction` command.
2459
*/
2460
export class CodeActionKind {
2461
/**
2462
* Empty kind.
2463
*/
2464
static readonly Empty: CodeActionKind;
2465
2466
/**
2467
* Base kind for quickfix actions: `quickfix`.
2468
*
2469
* Quick fix actions address a problem in the code and are shown in the normal code action context menu.
2470
*/
2471
static readonly QuickFix: CodeActionKind;
2472
2473
/**
2474
* Base kind for refactoring actions: `refactor`
2475
*
2476
* Refactoring actions are shown in the refactoring context menu.
2477
*/
2478
static readonly Refactor: CodeActionKind;
2479
2480
/**
2481
* Base kind for refactoring extraction actions: `refactor.extract`
2482
*
2483
* Example extract actions:
2484
*
2485
* - Extract method
2486
* - Extract function
2487
* - Extract variable
2488
* - Extract interface from class
2489
* - ...
2490
*/
2491
static readonly RefactorExtract: CodeActionKind;
2492
2493
/**
2494
* Base kind for refactoring inline actions: `refactor.inline`
2495
*
2496
* Example inline actions:
2497
*
2498
* - Inline function
2499
* - Inline variable
2500
* - Inline constant
2501
* - ...
2502
*/
2503
static readonly RefactorInline: CodeActionKind;
2504
2505
/**
2506
* Base kind for refactoring move actions: `refactor.move`
2507
*
2508
* Example move actions:
2509
*
2510
* - Move a function to a new file
2511
* - Move a property between classes
2512
* - Move method to base class
2513
* - ...
2514
*/
2515
static readonly RefactorMove: CodeActionKind;
2516
2517
/**
2518
* Base kind for refactoring rewrite actions: `refactor.rewrite`
2519
*
2520
* Example rewrite actions:
2521
*
2522
* - Convert JavaScript function to class
2523
* - Add or remove parameter
2524
* - Encapsulate field
2525
* - Make method static
2526
* - ...
2527
*/
2528
static readonly RefactorRewrite: CodeActionKind;
2529
2530
/**
2531
* Base kind for source actions: `source`
2532
*
2533
* Source code actions apply to the entire file. They must be explicitly requested and will not show in the
2534
* normal [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) menu. Source actions
2535
* can be run on save using `editor.codeActionsOnSave` and are also shown in the `source` context menu.
2536
*/
2537
static readonly Source: CodeActionKind;
2538
2539
/**
2540
* Base kind for an organize imports source action: `source.organizeImports`.
2541
*/
2542
static readonly SourceOrganizeImports: CodeActionKind;
2543
2544
/**
2545
* Base kind for auto-fix source actions: `source.fixAll`.
2546
*
2547
* Fix all actions automatically fix errors that have a clear fix that do not require user input.
2548
* They should not suppress errors or perform unsafe fixes such as generating new types or classes.
2549
*/
2550
static readonly SourceFixAll: CodeActionKind;
2551
2552
/**
2553
* Base kind for all code actions applying to the entire notebook's scope. CodeActionKinds using
2554
* this should always begin with `notebook.`
2555
*
2556
* This requires that new CodeActions be created for it and contributed via extensions.
2557
* Pre-existing kinds can not just have the new `notebook.` prefix added to them, as the functionality
2558
* is unique to the full-notebook scope.
2559
*
2560
* Notebook CodeActionKinds can be initialized as either of the following (both resulting in `notebook.source.xyz`):
2561
* - `const newKind = CodeActionKind.Notebook.append(CodeActionKind.Source.append('xyz').value)`
2562
* - `const newKind = CodeActionKind.Notebook.append('source.xyz')`
2563
*
2564
* Example Kinds/Actions:
2565
* - `notebook.source.organizeImports` (might move all imports to a new top cell)
2566
* - `notebook.source.normalizeVariableNames` (might rename all variables to a standardized casing format)
2567
*/
2568
static readonly Notebook: CodeActionKind;
2569
2570
/**
2571
* Private constructor, use static `CodeActionKind.XYZ` to derive from an existing code action kind.
2572
*
2573
* @param value The value of the kind, such as `refactor.extract.function`.
2574
*/
2575
private constructor(value: string);
2576
2577
/**
2578
* String value of the kind, e.g. `"refactor.extract.function"`.
2579
*/
2580
readonly value: string;
2581
2582
/**
2583
* Create a new kind by appending a more specific selector to the current kind.
2584
*
2585
* Does not modify the current kind.
2586
*/
2587
append(parts: string): CodeActionKind;
2588
2589
/**
2590
* Checks if this code action kind intersects `other`.
2591
*
2592
* The kind `"refactor.extract"` for example intersects `refactor`, `"refactor.extract"` and `"refactor.extract.function"`,
2593
* but not `"unicorn.refactor.extract"`, or `"refactor.extractAll"`.
2594
*
2595
* @param other Kind to check.
2596
*/
2597
intersects(other: CodeActionKind): boolean;
2598
2599
/**
2600
* Checks if `other` is a sub-kind of this `CodeActionKind`.
2601
*
2602
* The kind `"refactor.extract"` for example contains `"refactor.extract"` and ``"refactor.extract.function"`,
2603
* but not `"unicorn.refactor.extract"`, or `"refactor.extractAll"` or `refactor`.
2604
*
2605
* @param other Kind to check.
2606
*/
2607
contains(other: CodeActionKind): boolean;
2608
}
2609
2610
/**
2611
* The reason why code actions were requested.
2612
*/
2613
export enum CodeActionTriggerKind {
2614
/**
2615
* Code actions were explicitly requested by the user or by an extension.
2616
*/
2617
Invoke = 1,
2618
2619
/**
2620
* Code actions were requested automatically.
2621
*
2622
* This typically happens when current selection in a file changes, but can
2623
* also be triggered when file content changes.
2624
*/
2625
Automatic = 2,
2626
}
2627
2628
/**
2629
* Contains additional diagnostic information about the context in which
2630
* a {@link CodeActionProvider.provideCodeActions code action} is run.
2631
*/
2632
export interface CodeActionContext {
2633
/**
2634
* The reason why code actions were requested.
2635
*/
2636
readonly triggerKind: CodeActionTriggerKind;
2637
2638
/**
2639
* An array of diagnostics.
2640
*/
2641
readonly diagnostics: readonly Diagnostic[];
2642
2643
/**
2644
* Requested kind of actions to return.
2645
*
2646
* Actions not of this kind are filtered out before being shown by the [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action).
2647
*/
2648
readonly only: CodeActionKind | undefined;
2649
}
2650
2651
/**
2652
* A code action represents a change that can be performed in code, e.g. to fix a problem or
2653
* to refactor code.
2654
*
2655
* A CodeAction must set either {@linkcode CodeAction.edit edit} and/or a {@linkcode CodeAction.command command}. If both are supplied, the `edit` is applied first, then the command is executed.
2656
*/
2657
export class CodeAction {
2658
2659
/**
2660
* A short, human-readable, title for this code action.
2661
*/
2662
title: string;
2663
2664
/**
2665
* A {@link WorkspaceEdit workspace edit} this code action performs.
2666
*/
2667
edit?: WorkspaceEdit;
2668
2669
/**
2670
* {@link Diagnostic Diagnostics} that this code action resolves.
2671
*/
2672
diagnostics?: Diagnostic[];
2673
2674
/**
2675
* A {@link Command} this code action executes.
2676
*
2677
* If this command throws an exception, the editor displays the exception message to users in the editor at the
2678
* current cursor position.
2679
*/
2680
command?: Command;
2681
2682
/**
2683
* {@link CodeActionKind Kind} of the code action.
2684
*
2685
* Used to filter code actions.
2686
*/
2687
kind?: CodeActionKind;
2688
2689
/**
2690
* Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted
2691
* by keybindings.
2692
*
2693
* A quick fix should be marked preferred if it properly addresses the underlying error.
2694
* A refactoring should be marked preferred if it is the most reasonable choice of actions to take.
2695
*/
2696
isPreferred?: boolean;
2697
2698
/**
2699
* Marks that the code action cannot currently be applied.
2700
*
2701
* - Disabled code actions are not shown in automatic [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action)
2702
* code action menu.
2703
*
2704
* - Disabled actions are shown as faded out in the code action menu when the user request a more specific type
2705
* of code action, such as refactorings.
2706
*
2707
* - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions)
2708
* that auto applies a code action and only a disabled code actions are returned, the editor will show the user an
2709
* error message with `reason` in the editor.
2710
*/
2711
disabled?: {
2712
/**
2713
* Human readable description of why the code action is currently disabled.
2714
*
2715
* This is displayed in the code actions UI.
2716
*/
2717
readonly reason: string;
2718
};
2719
2720
/**
2721
* Creates a new code action.
2722
*
2723
* A code action must have at least a {@link CodeAction.title title} and {@link CodeAction.edit edits}
2724
* and/or a {@link CodeAction.command command}.
2725
*
2726
* @param title The title of the code action.
2727
* @param kind The kind of the code action.
2728
*/
2729
constructor(title: string, kind?: CodeActionKind);
2730
}
2731
2732
/**
2733
* Provides contextual actions for code. Code actions typically either fix problems or beautify/refactor code.
2734
*
2735
* Code actions are surfaced to users in a few different ways:
2736
*
2737
* - The [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature, which shows
2738
* a list of code actions at the current cursor position. The lightbulb's list of actions includes both quick fixes
2739
* and refactorings.
2740
* - As commands that users can run, such as `Refactor`. Users can run these from the command palette or with keybindings.
2741
* - As source actions, such `Organize Imports`.
2742
* - {@link CodeActionKind.QuickFix Quick fixes} are shown in the problems view.
2743
* - Change applied on save by the `editor.codeActionsOnSave` setting.
2744
*/
2745
export interface CodeActionProvider<T extends CodeAction = CodeAction> {
2746
/**
2747
* Get code actions for a given range in a document.
2748
*
2749
* Only return code actions that are relevant to user for the requested range. Also keep in mind how the
2750
* returned code actions will appear in the UI. The lightbulb widget and `Refactor` commands for instance show
2751
* returned code actions as a list, so do not return a large number of code actions that will overwhelm the user.
2752
*
2753
* @param document The document in which the command was invoked.
2754
* @param range The selector or range for which the command was invoked. This will always be a
2755
* {@link Selection selection} if the actions are being requested in the currently active editor.
2756
* @param context Provides additional information about what code actions are being requested. You can use this
2757
* to see what specific type of code actions are being requested by the editor in order to return more relevant
2758
* actions and avoid returning irrelevant code actions that the editor will discard.
2759
* @param token A cancellation token.
2760
*
2761
* @returns An array of code actions, such as quick fixes or refactorings. The lack of a result can be signaled
2762
* by returning `undefined`, `null`, or an empty array.
2763
*
2764
* We also support returning `Command` for legacy reasons, however all new extensions should return
2765
* `CodeAction` object instead.
2766
*/
2767
provideCodeActions(document: TextDocument, range: Range | Selection, context: CodeActionContext, token: CancellationToken): ProviderResult<Array<Command | T>>;
2768
2769
/**
2770
* Given a code action fill in its {@linkcode CodeAction.edit edit}-property. Changes to
2771
* all other properties, like title, are ignored. A code action that has an edit
2772
* will not be resolved.
2773
*
2774
* *Note* that a code action provider that returns commands, not code actions, cannot successfully
2775
* implement this function. Returning commands is deprecated and instead code actions should be
2776
* returned.
2777
*
2778
* @param codeAction A code action.
2779
* @param token A cancellation token.
2780
* @returns The resolved code action or a thenable that resolves to such. It is OK to return the given
2781
* `item`. When no result is returned, the given `item` will be used.
2782
*/
2783
resolveCodeAction?(codeAction: T, token: CancellationToken): ProviderResult<T>;
2784
}
2785
2786
/**
2787
* Metadata about the type of code actions that a {@link CodeActionProvider} provides.
2788
*/
2789
export interface CodeActionProviderMetadata {
2790
/**
2791
* List of {@link CodeActionKind CodeActionKinds} that a {@link CodeActionProvider} may return.
2792
*
2793
* This list is used to determine if a given `CodeActionProvider` should be invoked or not.
2794
* To avoid unnecessary computation, every `CodeActionProvider` should list use `providedCodeActionKinds`. The
2795
* list of kinds may either be generic, such as `[CodeActionKind.Refactor]`, or list out every kind provided,
2796
* such as `[CodeActionKind.Refactor.Extract.append('function'), CodeActionKind.Refactor.Extract.append('constant'), ...]`.
2797
*/
2798
readonly providedCodeActionKinds?: readonly CodeActionKind[];
2799
2800
/**
2801
* Static documentation for a class of code actions.
2802
*
2803
* Documentation from the provider is shown in the code actions menu if either:
2804
*
2805
* - Code actions of `kind` are requested by the editor. In this case, the editor will show the documentation that
2806
* most closely matches the requested code action kind. For example, if a provider has documentation for
2807
* both `Refactor` and `RefactorExtract`, when the user requests code actions for `RefactorExtract`,
2808
* the editor will use the documentation for `RefactorExtract` instead of the documentation for `Refactor`.
2809
*
2810
* - Any code actions of `kind` are returned by the provider.
2811
*
2812
* At most one documentation entry will be shown per provider.
2813
*/
2814
readonly documentation?: ReadonlyArray<{
2815
/**
2816
* The kind of the code action being documented.
2817
*
2818
* If the kind is generic, such as `CodeActionKind.Refactor`, the documentation will be shown whenever any
2819
* refactorings are returned. If the kind if more specific, such as `CodeActionKind.RefactorExtract`, the
2820
* documentation will only be shown when extract refactoring code actions are returned.
2821
*/
2822
readonly kind: CodeActionKind;
2823
2824
/**
2825
* Command that displays the documentation to the user.
2826
*
2827
* This can display the documentation directly in the editor or open a website using {@linkcode env.openExternal};
2828
*
2829
* The title of this documentation code action is taken from {@linkcode Command.title}
2830
*/
2831
readonly command: Command;
2832
}>;
2833
}
2834
2835
/**
2836
* A code lens represents a {@link Command} that should be shown along with
2837
* source text, like the number of references, a way to run tests, etc.
2838
*
2839
* A code lens is _unresolved_ when no command is associated to it. For performance
2840
* reasons the creation of a code lens and resolving should be done to two stages.
2841
*
2842
* @see {@link CodeLensProvider.provideCodeLenses}
2843
* @see {@link CodeLensProvider.resolveCodeLens}
2844
*/
2845
export class CodeLens {
2846
2847
/**
2848
* The range in which this code lens is valid. Should only span a single line.
2849
*/
2850
range: Range;
2851
2852
/**
2853
* The command this code lens represents.
2854
*/
2855
command?: Command;
2856
2857
/**
2858
* `true` when there is a command associated.
2859
*/
2860
readonly isResolved: boolean;
2861
2862
/**
2863
* Creates a new code lens object.
2864
*
2865
* @param range The range to which this code lens applies.
2866
* @param command The command associated to this code lens.
2867
*/
2868
constructor(range: Range, command?: Command);
2869
}
2870
2871
/**
2872
* A code lens provider adds {@link Command commands} to source text. The commands will be shown
2873
* as dedicated horizontal lines in between the source text.
2874
*/
2875
export interface CodeLensProvider<T extends CodeLens = CodeLens> {
2876
2877
/**
2878
* An optional event to signal that the code lenses from this provider have changed.
2879
*/
2880
onDidChangeCodeLenses?: Event<void>;
2881
2882
/**
2883
* Compute a list of {@link CodeLens lenses}. This call should return as fast as possible and if
2884
* computing the commands is expensive implementors should only return code lens objects with the
2885
* range set and implement {@link CodeLensProvider.resolveCodeLens resolve}.
2886
*
2887
* @param document The document in which the command was invoked.
2888
* @param token A cancellation token.
2889
* @returns An array of code lenses or a thenable that resolves to such. The lack of a result can be
2890
* signaled by returning `undefined`, `null`, or an empty array.
2891
*/
2892
provideCodeLenses(document: TextDocument, token: CancellationToken): ProviderResult<T[]>;
2893
2894
/**
2895
* This function will be called for each visible code lens, usually when scrolling and after
2896
* calls to {@link CodeLensProvider.provideCodeLenses compute}-lenses.
2897
*
2898
* @param codeLens Code lens that must be resolved.
2899
* @param token A cancellation token.
2900
* @returns The given, resolved code lens or thenable that resolves to such.
2901
*/
2902
resolveCodeLens?(codeLens: T, token: CancellationToken): ProviderResult<T>;
2903
}
2904
2905
/**
2906
* Information about where a symbol is defined.
2907
*
2908
* Provides additional metadata over normal {@link Location} definitions, including the range of
2909
* the defining symbol
2910
*/
2911
export type DefinitionLink = LocationLink;
2912
2913
/**
2914
* The definition of a symbol represented as one or many {@link Location locations}.
2915
* For most programming languages there is only one location at which a symbol is
2916
* defined.
2917
*/
2918
export type Definition = Location | Location[];
2919
2920
/**
2921
* The definition provider interface defines the contract between extensions and
2922
* the [go to definition](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-definition)
2923
* and peek definition features.
2924
*/
2925
export interface DefinitionProvider {
2926
2927
/**
2928
* Provide the definition of the symbol at the given position and document.
2929
*
2930
* @param document The document in which the command was invoked.
2931
* @param position The position at which the command was invoked.
2932
* @param token A cancellation token.
2933
* @returns A definition or a thenable that resolves to such. The lack of a result can be
2934
* signaled by returning `undefined` or `null`.
2935
*/
2936
provideDefinition(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Definition | DefinitionLink[]>;
2937
}
2938
2939
/**
2940
* The implementation provider interface defines the contract between extensions and
2941
* the go to implementation feature.
2942
*/
2943
export interface ImplementationProvider {
2944
2945
/**
2946
* Provide the implementations of the symbol at the given position and document.
2947
*
2948
* @param document The document in which the command was invoked.
2949
* @param position The position at which the command was invoked.
2950
* @param token A cancellation token.
2951
* @returns A definition or a thenable that resolves to such. The lack of a result can be
2952
* signaled by returning `undefined` or `null`.
2953
*/
2954
provideImplementation(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Definition | DefinitionLink[]>;
2955
}
2956
2957
/**
2958
* The type definition provider defines the contract between extensions and
2959
* the go to type definition feature.
2960
*/
2961
export interface TypeDefinitionProvider {
2962
2963
/**
2964
* Provide the type definition of the symbol at the given position and document.
2965
*
2966
* @param document The document in which the command was invoked.
2967
* @param position The position at which the command was invoked.
2968
* @param token A cancellation token.
2969
* @returns A definition or a thenable that resolves to such. The lack of a result can be
2970
* signaled by returning `undefined` or `null`.
2971
*/
2972
provideTypeDefinition(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Definition | DefinitionLink[]>;
2973
}
2974
2975
/**
2976
* The declaration of a symbol representation as one or many {@link Location locations}
2977
* or {@link LocationLink location links}.
2978
*/
2979
export type Declaration = Location | Location[] | LocationLink[];
2980
2981
/**
2982
* The declaration provider interface defines the contract between extensions and
2983
* the go to declaration feature.
2984
*/
2985
export interface DeclarationProvider {
2986
2987
/**
2988
* Provide the declaration of the symbol at the given position and document.
2989
*
2990
* @param document The document in which the command was invoked.
2991
* @param position The position at which the command was invoked.
2992
* @param token A cancellation token.
2993
* @returns A declaration or a thenable that resolves to such. The lack of a result can be
2994
* signaled by returning `undefined` or `null`.
2995
*/
2996
provideDeclaration(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Declaration>;
2997
}
2998
2999
/**
3000
* Human-readable text that supports formatting via the [markdown syntax](https://commonmark.org).
3001
*
3002
* Rendering of {@link ThemeIcon theme icons} via the `$(<name>)`-syntax is supported
3003
* when the {@linkcode supportThemeIcons} is set to `true`.
3004
*
3005
* Rendering of embedded html is supported when {@linkcode supportHtml} is set to `true`.
3006
*/
3007
export class MarkdownString {
3008
3009
/**
3010
* The markdown string.
3011
*/
3012
value: string;
3013
3014
/**
3015
* Indicates that this markdown string is from a trusted source. Only *trusted*
3016
* markdown supports links that execute commands, e.g. `[Run it](command:myCommandId)`.
3017
*
3018
* Defaults to `false` (commands are disabled).
3019
*/
3020
isTrusted?: boolean | {
3021
/**
3022
* A set of commend ids that are allowed to be executed by this markdown string.
3023
*/
3024
readonly enabledCommands: readonly string[];
3025
};
3026
3027
/**
3028
* Indicates that this markdown string can contain {@link ThemeIcon ThemeIcons}, e.g. `$(zap)`.
3029
*/
3030
supportThemeIcons?: boolean;
3031
3032
/**
3033
* Indicates that this markdown string can contain raw html tags. Defaults to `false`.
3034
*
3035
* When `supportHtml` is false, the markdown renderer will strip out any raw html tags
3036
* that appear in the markdown text. This means you can only use markdown syntax for rendering.
3037
*
3038
* When `supportHtml` is true, the markdown render will also allow a safe subset of html tags
3039
* and attributes to be rendered. See https://github.com/microsoft/vscode/blob/6d2920473c6f13759c978dd89104c4270a83422d/src/vs/base/browser/markdownRenderer.ts#L296
3040
* for a list of all supported tags and attributes.
3041
*/
3042
supportHtml?: boolean;
3043
3044
/**
3045
* Uri that relative paths are resolved relative to.
3046
*
3047
* If the `baseUri` ends with `/`, it is considered a directory and relative paths in the markdown are resolved relative to that directory:
3048
*
3049
* ```ts
3050
* const md = new vscode.MarkdownString(`[link](./file.js)`);
3051
* md.baseUri = vscode.Uri.file('/path/to/dir/');
3052
* // Here 'link' in the rendered markdown resolves to '/path/to/dir/file.js'
3053
* ```
3054
*
3055
* If the `baseUri` is a file, relative paths in the markdown are resolved relative to the parent dir of that file:
3056
*
3057
* ```ts
3058
* const md = new vscode.MarkdownString(`[link](./file.js)`);
3059
* md.baseUri = vscode.Uri.file('/path/to/otherFile.js');
3060
* // Here 'link' in the rendered markdown resolves to '/path/to/file.js'
3061
* ```
3062
*/
3063
baseUri?: Uri;
3064
3065
/**
3066
* Creates a new markdown string with the given value.
3067
*
3068
* @param value Optional, initial value.
3069
* @param supportThemeIcons Optional, Specifies whether {@link ThemeIcon ThemeIcons} are supported within the {@linkcode MarkdownString}.
3070
*/
3071
constructor(value?: string, supportThemeIcons?: boolean);
3072
3073
/**
3074
* Appends and escapes the given string to this markdown string.
3075
* @param value Plain text.
3076
*/
3077
appendText(value: string): MarkdownString;
3078
3079
/**
3080
* Appends the given string 'as is' to this markdown string. When {@linkcode MarkdownString.supportThemeIcons supportThemeIcons} is `true`, {@link ThemeIcon ThemeIcons} in the `value` will be iconified.
3081
* @param value Markdown string.
3082
*/
3083
appendMarkdown(value: string): MarkdownString;
3084
3085
/**
3086
* Appends the given string as codeblock using the provided language.
3087
* @param value A code snippet.
3088
* @param language An optional {@link languages.getLanguages language identifier}.
3089
*/
3090
appendCodeblock(value: string, language?: string): MarkdownString;
3091
}
3092
3093
/**
3094
* MarkedString can be used to render human-readable text. It is either a markdown string
3095
* or a code-block that provides a language and a code snippet. Note that
3096
* markdown strings will be sanitized - that means html will be escaped.
3097
*
3098
* @deprecated This type is deprecated, please use {@linkcode MarkdownString} instead.
3099
*/
3100
export type MarkedString = string | {
3101
/**
3102
* The language of a markdown code block
3103
* @deprecated please use {@linkcode MarkdownString} instead
3104
*/
3105
language: string;
3106
/**
3107
* The code snippet of a markdown code block.
3108
* @deprecated please use {@linkcode MarkdownString} instead
3109
*/
3110
value: string;
3111
};
3112
3113
/**
3114
* A hover represents additional information for a symbol or word. Hovers are
3115
* rendered in a tooltip-like widget.
3116
*/
3117
export class Hover {
3118
3119
/**
3120
* The contents of this hover.
3121
*/
3122
contents: Array<MarkdownString | MarkedString>;
3123
3124
/**
3125
* The range to which this hover applies. When missing, the
3126
* editor will use the range at the current position or the
3127
* current position itself.
3128
*/
3129
range?: Range;
3130
3131
/**
3132
* Creates a new hover object.
3133
*
3134
* @param contents The contents of the hover.
3135
* @param range The range to which the hover applies.
3136
*/
3137
constructor(contents: MarkdownString | MarkedString | Array<MarkdownString | MarkedString>, range?: Range);
3138
}
3139
3140
/**
3141
* The hover provider interface defines the contract between extensions and
3142
* the [hover](https://code.visualstudio.com/docs/editor/intellisense)-feature.
3143
*/
3144
export interface HoverProvider {
3145
3146
/**
3147
* Provide a hover for the given position and document. Multiple hovers at the same
3148
* position will be merged by the editor. A hover can have a range which defaults
3149
* to the word range at the position when omitted.
3150
*
3151
* @param document The document in which the command was invoked.
3152
* @param position The position at which the command was invoked.
3153
* @param token A cancellation token.
3154
* @returns A hover or a thenable that resolves to such. The lack of a result can be
3155
* signaled by returning `undefined` or `null`.
3156
*/
3157
provideHover(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Hover>;
3158
}
3159
3160
/**
3161
* An EvaluatableExpression represents an expression in a document that can be evaluated by an active debugger or runtime.
3162
* The result of this evaluation is shown in a tooltip-like widget.
3163
* If only a range is specified, the expression will be extracted from the underlying document.
3164
* An optional expression can be used to override the extracted expression.
3165
* In this case the range is still used to highlight the range in the document.
3166
*/
3167
export class EvaluatableExpression {
3168
3169
/**
3170
* The range is used to extract the evaluatable expression from the underlying document and to highlight it.
3171
*/
3172
readonly range: Range;
3173
3174
/**
3175
* If specified the expression overrides the extracted expression.
3176
*/
3177
readonly expression?: string | undefined;
3178
3179
/**
3180
* Creates a new evaluatable expression object.
3181
*
3182
* @param range The range in the underlying document from which the evaluatable expression is extracted.
3183
* @param expression If specified overrides the extracted expression.
3184
*/
3185
constructor(range: Range, expression?: string);
3186
}
3187
3188
/**
3189
* The evaluatable expression provider interface defines the contract between extensions and
3190
* the debug hover. In this contract the provider returns an evaluatable expression for a given position
3191
* in a document and the editor evaluates this expression in the active debug session and shows the result in a debug hover.
3192
*/
3193
export interface EvaluatableExpressionProvider {
3194
3195
/**
3196
* Provide an evaluatable expression for the given document and position.
3197
* The editor will evaluate this expression in the active debug session and will show the result in the debug hover.
3198
* The expression can be implicitly specified by the range in the underlying document or by explicitly returning an expression.
3199
*
3200
* @param document The document for which the debug hover is about to appear.
3201
* @param position The line and character position in the document where the debug hover is about to appear.
3202
* @param token A cancellation token.
3203
* @returns An EvaluatableExpression or a thenable that resolves to such. The lack of a result can be
3204
* signaled by returning `undefined` or `null`.
3205
*/
3206
provideEvaluatableExpression(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<EvaluatableExpression>;
3207
}
3208
3209
/**
3210
* Provide inline value as text.
3211
*/
3212
export class InlineValueText {
3213
/**
3214
* The document range for which the inline value applies.
3215
*/
3216
readonly range: Range;
3217
/**
3218
* The text of the inline value.
3219
*/
3220
readonly text: string;
3221
/**
3222
* Creates a new InlineValueText object.
3223
*
3224
* @param range The document line where to show the inline value.
3225
* @param text The value to be shown for the line.
3226
*/
3227
constructor(range: Range, text: string);
3228
}
3229
3230
/**
3231
* Provide inline value through a variable lookup.
3232
* If only a range is specified, the variable name will be extracted from the underlying document.
3233
* An optional variable name can be used to override the extracted name.
3234
*/
3235
export class InlineValueVariableLookup {
3236
/**
3237
* The document range for which the inline value applies.
3238
* The range is used to extract the variable name from the underlying document.
3239
*/
3240
readonly range: Range;
3241
/**
3242
* If specified the name of the variable to look up.
3243
*/
3244
readonly variableName?: string | undefined;
3245
/**
3246
* How to perform the lookup.
3247
*/
3248
readonly caseSensitiveLookup: boolean;
3249
/**
3250
* Creates a new InlineValueVariableLookup object.
3251
*
3252
* @param range The document line where to show the inline value.
3253
* @param variableName The name of the variable to look up.
3254
* @param caseSensitiveLookup How to perform the lookup. If missing lookup is case sensitive.
3255
*/
3256
constructor(range: Range, variableName?: string, caseSensitiveLookup?: boolean);
3257
}
3258
3259
/**
3260
* Provide an inline value through an expression evaluation.
3261
* If only a range is specified, the expression will be extracted from the underlying document.
3262
* An optional expression can be used to override the extracted expression.
3263
*/
3264
export class InlineValueEvaluatableExpression {
3265
/**
3266
* The document range for which the inline value applies.
3267
* The range is used to extract the evaluatable expression from the underlying document.
3268
*/
3269
readonly range: Range;
3270
/**
3271
* If specified the expression overrides the extracted expression.
3272
*/
3273
readonly expression?: string | undefined;
3274
/**
3275
* Creates a new InlineValueEvaluatableExpression object.
3276
*
3277
* @param range The range in the underlying document from which the evaluatable expression is extracted.
3278
* @param expression If specified overrides the extracted expression.
3279
*/
3280
constructor(range: Range, expression?: string);
3281
}
3282
3283
/**
3284
* Inline value information can be provided by different means:
3285
* - directly as a text value (class InlineValueText).
3286
* - as a name to use for a variable lookup (class InlineValueVariableLookup)
3287
* - as an evaluatable expression (class InlineValueEvaluatableExpression)
3288
* The InlineValue types combines all inline value types into one type.
3289
*/
3290
export type InlineValue = InlineValueText | InlineValueVariableLookup | InlineValueEvaluatableExpression;
3291
3292
/**
3293
* A value-object that contains contextual information when requesting inline values from a InlineValuesProvider.
3294
*/
3295
export interface InlineValueContext {
3296
3297
/**
3298
* The stack frame (as a DAP Id) where the execution has stopped.
3299
*/
3300
readonly frameId: number;
3301
3302
/**
3303
* The document range where execution has stopped.
3304
* Typically the end position of the range denotes the line where the inline values are shown.
3305
*/
3306
readonly stoppedLocation: Range;
3307
}
3308
3309
/**
3310
* The inline values provider interface defines the contract between extensions and the editor's debugger inline values feature.
3311
* In this contract the provider returns inline value information for a given document range
3312
* and the editor shows this information in the editor at the end of lines.
3313
*/
3314
export interface InlineValuesProvider {
3315
3316
/**
3317
* An optional event to signal that inline values have changed.
3318
* @see {@link EventEmitter}
3319
*/
3320
onDidChangeInlineValues?: Event<void> | undefined;
3321
3322
/**
3323
* Provide "inline value" information for a given document and range.
3324
* The editor calls this method whenever debugging stops in the given document.
3325
* The returned inline values information is rendered in the editor at the end of lines.
3326
*
3327
* @param document The document for which the inline values information is needed.
3328
* @param viewPort The visible document range for which inline values should be computed.
3329
* @param context A bag containing contextual information like the current location.
3330
* @param token A cancellation token.
3331
* @returns An array of InlineValueDescriptors or a thenable that resolves to such. The lack of a result can be
3332
* signaled by returning `undefined` or `null`.
3333
*/
3334
provideInlineValues(document: TextDocument, viewPort: Range, context: InlineValueContext, token: CancellationToken): ProviderResult<InlineValue[]>;
3335
}
3336
3337
/**
3338
* A document highlight kind.
3339
*/
3340
export enum DocumentHighlightKind {
3341
3342
/**
3343
* A textual occurrence.
3344
*/
3345
Text = 0,
3346
3347
/**
3348
* Read-access of a symbol, like reading a variable.
3349
*/
3350
Read = 1,
3351
3352
/**
3353
* Write-access of a symbol, like writing to a variable.
3354
*/
3355
Write = 2
3356
}
3357
3358
/**
3359
* A document highlight is a range inside a text document which deserves
3360
* special attention. Usually a document highlight is visualized by changing
3361
* the background color of its range.
3362
*/
3363
export class DocumentHighlight {
3364
3365
/**
3366
* The range this highlight applies to.
3367
*/
3368
range: Range;
3369
3370
/**
3371
* The highlight kind, default is {@link DocumentHighlightKind.Text text}.
3372
*/
3373
kind?: DocumentHighlightKind;
3374
3375
/**
3376
* Creates a new document highlight object.
3377
*
3378
* @param range The range the highlight applies to.
3379
* @param kind The highlight kind, default is {@link DocumentHighlightKind.Text text}.
3380
*/
3381
constructor(range: Range, kind?: DocumentHighlightKind);
3382
}
3383
3384
/**
3385
* The document highlight provider interface defines the contract between extensions and
3386
* the word-highlight-feature.
3387
*/
3388
export interface DocumentHighlightProvider {
3389
3390
/**
3391
* Provide a set of document highlights, like all occurrences of a variable or
3392
* all exit-points of a function.
3393
*
3394
* @param document The document in which the command was invoked.
3395
* @param position The position at which the command was invoked.
3396
* @param token A cancellation token.
3397
* @returns An array of document highlights or a thenable that resolves to such. The lack of a result can be
3398
* signaled by returning `undefined`, `null`, or an empty array.
3399
*/
3400
provideDocumentHighlights(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<DocumentHighlight[]>;
3401
}
3402
3403
/**
3404
* A symbol kind.
3405
*/
3406
export enum SymbolKind {
3407
/**
3408
* The `File` symbol kind.
3409
*/
3410
File = 0,
3411
/**
3412
* The `Module` symbol kind.
3413
*/
3414
Module = 1,
3415
/**
3416
* The `Namespace` symbol kind.
3417
*/
3418
Namespace = 2,
3419
/**
3420
* The `Package` symbol kind.
3421
*/
3422
Package = 3,
3423
/**
3424
* The `Class` symbol kind.
3425
*/
3426
Class = 4,
3427
/**
3428
* The `Method` symbol kind.
3429
*/
3430
Method = 5,
3431
/**
3432
* The `Property` symbol kind.
3433
*/
3434
Property = 6,
3435
/**
3436
* The `Field` symbol kind.
3437
*/
3438
Field = 7,
3439
/**
3440
* The `Constructor` symbol kind.
3441
*/
3442
Constructor = 8,
3443
/**
3444
* The `Enum` symbol kind.
3445
*/
3446
Enum = 9,
3447
/**
3448
* The `Interface` symbol kind.
3449
*/
3450
Interface = 10,
3451
/**
3452
* The `Function` symbol kind.
3453
*/
3454
Function = 11,
3455
/**
3456
* The `Variable` symbol kind.
3457
*/
3458
Variable = 12,
3459
/**
3460
* The `Constant` symbol kind.
3461
*/
3462
Constant = 13,
3463
/**
3464
* The `String` symbol kind.
3465
*/
3466
String = 14,
3467
/**
3468
* The `Number` symbol kind.
3469
*/
3470
Number = 15,
3471
/**
3472
* The `Boolean` symbol kind.
3473
*/
3474
Boolean = 16,
3475
/**
3476
* The `Array` symbol kind.
3477
*/
3478
Array = 17,
3479
/**
3480
* The `Object` symbol kind.
3481
*/
3482
Object = 18,
3483
/**
3484
* The `Key` symbol kind.
3485
*/
3486
Key = 19,
3487
/**
3488
* The `Null` symbol kind.
3489
*/
3490
Null = 20,
3491
/**
3492
* The `EnumMember` symbol kind.
3493
*/
3494
EnumMember = 21,
3495
/**
3496
* The `Struct` symbol kind.
3497
*/
3498
Struct = 22,
3499
/**
3500
* The `Event` symbol kind.
3501
*/
3502
Event = 23,
3503
/**
3504
* The `Operator` symbol kind.
3505
*/
3506
Operator = 24,
3507
/**
3508
* The `TypeParameter` symbol kind.
3509
*/
3510
TypeParameter = 25
3511
}
3512
3513
/**
3514
* Symbol tags are extra annotations that tweak the rendering of a symbol.
3515
*/
3516
export enum SymbolTag {
3517
3518
/**
3519
* Render a symbol as obsolete, usually using a strike-out.
3520
*/
3521
Deprecated = 1
3522
}
3523
3524
/**
3525
* Represents information about programming constructs like variables, classes,
3526
* interfaces etc.
3527
*/
3528
export class SymbolInformation {
3529
3530
/**
3531
* The name of this symbol.
3532
*/
3533
name: string;
3534
3535
/**
3536
* The name of the symbol containing this symbol.
3537
*/
3538
containerName: string;
3539
3540
/**
3541
* The kind of this symbol.
3542
*/
3543
kind: SymbolKind;
3544
3545
/**
3546
* Tags for this symbol.
3547
*/
3548
tags?: readonly SymbolTag[];
3549
3550
/**
3551
* The location of this symbol.
3552
*/
3553
location: Location;
3554
3555
/**
3556
* Creates a new symbol information object.
3557
*
3558
* @param name The name of the symbol.
3559
* @param kind The kind of the symbol.
3560
* @param containerName The name of the symbol containing the symbol.
3561
* @param location The location of the symbol.
3562
*/
3563
constructor(name: string, kind: SymbolKind, containerName: string, location: Location);
3564
3565
/**
3566
* Creates a new symbol information object.
3567
*
3568
* @deprecated Please use the constructor taking a {@link Location} object.
3569
*
3570
* @param name The name of the symbol.
3571
* @param kind The kind of the symbol.
3572
* @param range The range of the location of the symbol.
3573
* @param uri The resource of the location of symbol, defaults to the current document.
3574
* @param containerName The name of the symbol containing the symbol.
3575
*/
3576
constructor(name: string, kind: SymbolKind, range: Range, uri?: Uri, containerName?: string);
3577
}
3578
3579
/**
3580
* Represents programming constructs like variables, classes, interfaces etc. that appear in a document. Document
3581
* symbols can be hierarchical and they have two ranges: one that encloses its definition and one that points to
3582
* its most interesting range, e.g. the range of an identifier.
3583
*/
3584
export class DocumentSymbol {
3585
3586
/**
3587
* The name of this symbol.
3588
*/
3589
name: string;
3590
3591
/**
3592
* More detail for this symbol, e.g. the signature of a function.
3593
*/
3594
detail: string;
3595
3596
/**
3597
* The kind of this symbol.
3598
*/
3599
kind: SymbolKind;
3600
3601
/**
3602
* Tags for this symbol.
3603
*/
3604
tags?: readonly SymbolTag[];
3605
3606
/**
3607
* The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code.
3608
*/
3609
range: Range;
3610
3611
/**
3612
* The range that should be selected and reveal when this symbol is being picked, e.g. the name of a function.
3613
* Must be contained by the {@linkcode DocumentSymbol.range range}.
3614
*/
3615
selectionRange: Range;
3616
3617
/**
3618
* Children of this symbol, e.g. properties of a class.
3619
*/
3620
children: DocumentSymbol[];
3621
3622
/**
3623
* Creates a new document symbol.
3624
*
3625
* @param name The name of the symbol.
3626
* @param detail Details for the symbol.
3627
* @param kind The kind of the symbol.
3628
* @param range The full range of the symbol.
3629
* @param selectionRange The range that should be reveal.
3630
*/
3631
constructor(name: string, detail: string, kind: SymbolKind, range: Range, selectionRange: Range);
3632
}
3633
3634
/**
3635
* The document symbol provider interface defines the contract between extensions and
3636
* the [go to symbol](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-symbol)-feature.
3637
*/
3638
export interface DocumentSymbolProvider {
3639
3640
/**
3641
* Provide symbol information for the given document.
3642
*
3643
* @param document The document in which the command was invoked.
3644
* @param token A cancellation token.
3645
* @returns An array of document highlights or a thenable that resolves to such. The lack of a result can be
3646
* signaled by returning `undefined`, `null`, or an empty array.
3647
*/
3648
provideDocumentSymbols(document: TextDocument, token: CancellationToken): ProviderResult<SymbolInformation[] | DocumentSymbol[]>;
3649
}
3650
3651
/**
3652
* Metadata about a document symbol provider.
3653
*/
3654
export interface DocumentSymbolProviderMetadata {
3655
/**
3656
* A human-readable string that is shown when multiple outlines trees show for one document.
3657
*/
3658
label?: string;
3659
}
3660
3661
/**
3662
* The workspace symbol provider interface defines the contract between extensions and
3663
* the [symbol search](https://code.visualstudio.com/docs/editor/editingevolved#_open-symbol-by-name)-feature.
3664
*/
3665
export interface WorkspaceSymbolProvider<T extends SymbolInformation = SymbolInformation> {
3666
3667
/**
3668
* Project-wide search for a symbol matching the given query string.
3669
*
3670
* The `query`-parameter should be interpreted in a *relaxed way* as the editor will apply its own highlighting
3671
* and scoring on the results. A good rule of thumb is to match case-insensitive and to simply check that the
3672
* characters of *query* appear in their order in a candidate symbol. Don't use prefix, substring, or similar
3673
* strict matching.
3674
*
3675
* To improve performance implementors can implement `resolveWorkspaceSymbol` and then provide symbols with partial
3676
* {@link SymbolInformation.location location}-objects, without a `range` defined. The editor will then call
3677
* `resolveWorkspaceSymbol` for selected symbols only, e.g. when opening a workspace symbol.
3678
*
3679
* @param query A query string, can be the empty string in which case all symbols should be returned.
3680
* @param token A cancellation token.
3681
* @returns An array of document highlights or a thenable that resolves to such. The lack of a result can be
3682
* signaled by returning `undefined`, `null`, or an empty array.
3683
*/
3684
provideWorkspaceSymbols(query: string, token: CancellationToken): ProviderResult<T[]>;
3685
3686
/**
3687
* Given a symbol fill in its {@link SymbolInformation.location location}. This method is called whenever a symbol
3688
* is selected in the UI. Providers can implement this method and return incomplete symbols from
3689
* {@linkcode WorkspaceSymbolProvider.provideWorkspaceSymbols provideWorkspaceSymbols} which often helps to improve
3690
* performance.
3691
*
3692
* @param symbol The symbol that is to be resolved. Guaranteed to be an instance of an object returned from an
3693
* earlier call to `provideWorkspaceSymbols`.
3694
* @param token A cancellation token.
3695
* @returns The resolved symbol or a thenable that resolves to that. When no result is returned,
3696
* the given `symbol` is used.
3697
*/
3698
resolveWorkspaceSymbol?(symbol: T, token: CancellationToken): ProviderResult<T>;
3699
}
3700
3701
/**
3702
* Value-object that contains additional information when
3703
* requesting references.
3704
*/
3705
export interface ReferenceContext {
3706
3707
/**
3708
* Include the declaration of the current symbol.
3709
*/
3710
readonly includeDeclaration: boolean;
3711
}
3712
3713
/**
3714
* The reference provider interface defines the contract between extensions and
3715
* the [find references](https://code.visualstudio.com/docs/editor/editingevolved#_peek)-feature.
3716
*/
3717
export interface ReferenceProvider {
3718
3719
/**
3720
* Provide a set of project-wide references for the given position and document.
3721
*
3722
* @param document The document in which the command was invoked.
3723
* @param position The position at which the command was invoked.
3724
* @param context Additional information about the references request.
3725
* @param token A cancellation token.
3726
*
3727
* @returns An array of locations or a thenable that resolves to such. The lack of a result can be
3728
* signaled by returning `undefined`, `null`, or an empty array.
3729
*/
3730
provideReferences(document: TextDocument, position: Position, context: ReferenceContext, token: CancellationToken): ProviderResult<Location[]>;
3731
}
3732
3733
/**
3734
* A text edit represents edits that should be applied
3735
* to a document.
3736
*/
3737
export class TextEdit {
3738
3739
/**
3740
* Utility to create a replace edit.
3741
*
3742
* @param range A range.
3743
* @param newText A string.
3744
* @returns A new text edit object.
3745
*/
3746
static replace(range: Range, newText: string): TextEdit;
3747
3748
/**
3749
* Utility to create an insert edit.
3750
*
3751
* @param position A position, will become an empty range.
3752
* @param newText A string.
3753
* @returns A new text edit object.
3754
*/
3755
static insert(position: Position, newText: string): TextEdit;
3756
3757
/**
3758
* Utility to create a delete edit.
3759
*
3760
* @param range A range.
3761
* @returns A new text edit object.
3762
*/
3763
static delete(range: Range): TextEdit;
3764
3765
/**
3766
* Utility to create an eol-edit.
3767
*
3768
* @param eol An eol-sequence
3769
* @returns A new text edit object.
3770
*/
3771
static setEndOfLine(eol: EndOfLine): TextEdit;
3772
3773
/**
3774
* The range this edit applies to.
3775
*/
3776
range: Range;
3777
3778
/**
3779
* The string this edit will insert.
3780
*/
3781
newText: string;
3782
3783
/**
3784
* The eol-sequence used in the document.
3785
*
3786
* *Note* that the eol-sequence will be applied to the
3787
* whole document.
3788
*/
3789
newEol?: EndOfLine;
3790
3791
/**
3792
* Create a new TextEdit.
3793
*
3794
* @param range A range.
3795
* @param newText A string.
3796
*/
3797
constructor(range: Range, newText: string);
3798
}
3799
3800
/**
3801
* A snippet edit represents an interactive edit that is performed by
3802
* the editor.
3803
*
3804
* *Note* that a snippet edit can always be performed as a normal {@link TextEdit text edit}.
3805
* This will happen when no matching editor is open or when a {@link WorkspaceEdit workspace edit}
3806
* contains snippet edits for multiple files. In that case only those that match the active editor
3807
* will be performed as snippet edits and the others as normal text edits.
3808
*/
3809
export class SnippetTextEdit {
3810
3811
/**
3812
* Utility to create a replace snippet edit.
3813
*
3814
* @param range A range.
3815
* @param snippet A snippet string.
3816
* @returns A new snippet edit object.
3817
*/
3818
static replace(range: Range, snippet: SnippetString): SnippetTextEdit;
3819
3820
/**
3821
* Utility to create an insert snippet edit.
3822
*
3823
* @param position A position, will become an empty range.
3824
* @param snippet A snippet string.
3825
* @returns A new snippet edit object.
3826
*/
3827
static insert(position: Position, snippet: SnippetString): SnippetTextEdit;
3828
3829
/**
3830
* The range this edit applies to.
3831
*/
3832
range: Range;
3833
3834
/**
3835
* The {@link SnippetString snippet} this edit will perform.
3836
*/
3837
snippet: SnippetString;
3838
3839
/**
3840
* Whether the snippet edit should be applied with existing whitespace preserved.
3841
*/
3842
keepWhitespace?: boolean;
3843
3844
/**
3845
* Create a new snippet edit.
3846
*
3847
* @param range A range.
3848
* @param snippet A snippet string.
3849
*/
3850
constructor(range: Range, snippet: SnippetString);
3851
}
3852
3853
/**
3854
* A notebook edit represents edits that should be applied to the contents of a notebook.
3855
*/
3856
export class NotebookEdit {
3857
3858
/**
3859
* Utility to create a edit that replaces cells in a notebook.
3860
*
3861
* @param range The range of cells to replace
3862
* @param newCells The new notebook cells.
3863
*/
3864
static replaceCells(range: NotebookRange, newCells: NotebookCellData[]): NotebookEdit;
3865
3866
/**
3867
* Utility to create an edit that replaces cells in a notebook.
3868
*
3869
* @param index The index to insert cells at.
3870
* @param newCells The new notebook cells.
3871
*/
3872
static insertCells(index: number, newCells: NotebookCellData[]): NotebookEdit;
3873
3874
/**
3875
* Utility to create an edit that deletes cells in a notebook.
3876
*
3877
* @param range The range of cells to delete.
3878
*/
3879
static deleteCells(range: NotebookRange): NotebookEdit;
3880
3881
/**
3882
* Utility to create an edit that update a cell's metadata.
3883
*
3884
* @param index The index of the cell to update.
3885
* @param newCellMetadata The new metadata for the cell.
3886
*/
3887
static updateCellMetadata(index: number, newCellMetadata: { [key: string]: any }): NotebookEdit;
3888
3889
/**
3890
* Utility to create an edit that updates the notebook's metadata.
3891
*
3892
* @param newNotebookMetadata The new metadata for the notebook.
3893
*/
3894
static updateNotebookMetadata(newNotebookMetadata: { [key: string]: any }): NotebookEdit;
3895
3896
/**
3897
* Range of the cells being edited. May be empty.
3898
*/
3899
range: NotebookRange;
3900
3901
/**
3902
* New cells being inserted. May be empty.
3903
*/
3904
newCells: NotebookCellData[];
3905
3906
/**
3907
* Optional new metadata for the cells.
3908
*/
3909
newCellMetadata?: { [key: string]: any };
3910
3911
/**
3912
* Optional new metadata for the notebook.
3913
*/
3914
newNotebookMetadata?: { [key: string]: any };
3915
3916
/**
3917
* Create a new notebook edit.
3918
*
3919
* @param range A notebook range.
3920
* @param newCells An array of new cell data.
3921
*/
3922
constructor(range: NotebookRange, newCells: NotebookCellData[]);
3923
}
3924
3925
/**
3926
* Additional data for entries of a workspace edit. Supports to label entries and marks entries
3927
* as needing confirmation by the user. The editor groups edits with equal labels into tree nodes,
3928
* for instance all edits labelled with "Changes in Strings" would be a tree node.
3929
*/
3930
export interface WorkspaceEditEntryMetadata {
3931
3932
/**
3933
* A flag which indicates that user confirmation is needed.
3934
*/
3935
needsConfirmation: boolean;
3936
3937
/**
3938
* A human-readable string which is rendered prominent.
3939
*/
3940
label: string;
3941
3942
/**
3943
* A human-readable string which is rendered less prominent on the same line.
3944
*/
3945
description?: string;
3946
3947
/**
3948
* The icon path or {@link ThemeIcon} for the edit.
3949
*/
3950
iconPath?: IconPath;
3951
}
3952
3953
/**
3954
* Additional data about a workspace edit.
3955
*/
3956
export interface WorkspaceEditMetadata {
3957
/**
3958
* Signal to the editor that this edit is a refactoring.
3959
*/
3960
isRefactoring?: boolean;
3961
}
3962
3963
/**
3964
* A workspace edit is a collection of textual and files changes for
3965
* multiple resources and documents.
3966
*
3967
* Use the {@link workspace.applyEdit applyEdit}-function to apply a workspace edit.
3968
*/
3969
export class WorkspaceEdit {
3970
3971
/**
3972
* The number of affected resources of textual or resource changes.
3973
*/
3974
readonly size: number;
3975
3976
/**
3977
* Replace the given range with given text for the given resource.
3978
*
3979
* @param uri A resource identifier.
3980
* @param range A range.
3981
* @param newText A string.
3982
* @param metadata Optional metadata for the entry.
3983
*/
3984
replace(uri: Uri, range: Range, newText: string, metadata?: WorkspaceEditEntryMetadata): void;
3985
3986
/**
3987
* Insert the given text at the given position.
3988
*
3989
* @param uri A resource identifier.
3990
* @param position A position.
3991
* @param newText A string.
3992
* @param metadata Optional metadata for the entry.
3993
*/
3994
insert(uri: Uri, position: Position, newText: string, metadata?: WorkspaceEditEntryMetadata): void;
3995
3996
/**
3997
* Delete the text at the given range.
3998
*
3999
* @param uri A resource identifier.
4000
* @param range A range.
4001
* @param metadata Optional metadata for the entry.
4002
*/
4003
delete(uri: Uri, range: Range, metadata?: WorkspaceEditEntryMetadata): void;
4004
4005
/**
4006
* Check if a text edit for a resource exists.
4007
*
4008
* @param uri A resource identifier.
4009
* @returns `true` if the given resource will be touched by this edit.
4010
*/
4011
has(uri: Uri): boolean;
4012
4013
/**
4014
* Set (and replace) text edits or snippet edits for a resource.
4015
*
4016
* @param uri A resource identifier.
4017
* @param edits An array of edits.
4018
*/
4019
set(uri: Uri, edits: ReadonlyArray<TextEdit | SnippetTextEdit>): void;
4020
4021
/**
4022
* Set (and replace) text edits or snippet edits with metadata for a resource.
4023
*
4024
* @param uri A resource identifier.
4025
* @param edits An array of edits.
4026
*/
4027
set(uri: Uri, edits: ReadonlyArray<[TextEdit | SnippetTextEdit, WorkspaceEditEntryMetadata | undefined]>): void;
4028
4029
/**
4030
* Set (and replace) notebook edits for a resource.
4031
*
4032
* @param uri A resource identifier.
4033
* @param edits An array of edits.
4034
*/
4035
set(uri: Uri, edits: readonly NotebookEdit[]): void;
4036
4037
/**
4038
* Set (and replace) notebook edits with metadata for a resource.
4039
*
4040
* @param uri A resource identifier.
4041
* @param edits An array of edits.
4042
*/
4043
set(uri: Uri, edits: ReadonlyArray<[NotebookEdit, WorkspaceEditEntryMetadata | undefined]>): void;
4044
4045
/**
4046
* Get the text edits for a resource.
4047
*
4048
* @param uri A resource identifier.
4049
* @returns An array of text edits.
4050
*/
4051
get(uri: Uri): TextEdit[];
4052
4053
/**
4054
* Create a regular file.
4055
*
4056
* @param uri Uri of the new file.
4057
* @param options Defines if an existing file should be overwritten or be
4058
* ignored. When `overwrite` and `ignoreIfExists` are both set `overwrite` wins.
4059
* When both are unset and when the file already exists then the edit cannot
4060
* be applied successfully. The `content`-property allows to set the initial contents
4061
* the file is being created with.
4062
* @param metadata Optional metadata for the entry.
4063
*/
4064
createFile(uri: Uri, options?: {
4065
/**
4066
* Overwrite existing file. Overwrite wins over `ignoreIfExists`
4067
*/
4068
readonly overwrite?: boolean;
4069
/**
4070
* Do nothing if a file with `uri` exists already.
4071
*/
4072
readonly ignoreIfExists?: boolean;
4073
/**
4074
* The initial contents of the new file.
4075
*
4076
* If creating a file from a {@link DocumentDropEditProvider drop operation}, you can
4077
* pass in a {@link DataTransferFile} to improve performance by avoiding extra data copying.
4078
*/
4079
readonly contents?: Uint8Array | DataTransferFile;
4080
}, metadata?: WorkspaceEditEntryMetadata): void;
4081
4082
/**
4083
* Delete a file or folder.
4084
*
4085
* @param uri The uri of the file that is to be deleted.
4086
* @param metadata Optional metadata for the entry.
4087
*/
4088
deleteFile(uri: Uri, options?: {
4089
/**
4090
* Delete the content recursively if a folder is denoted.
4091
*/
4092
readonly recursive?: boolean;
4093
/**
4094
* Do nothing if a file with `uri` exists already.
4095
*/
4096
readonly ignoreIfNotExists?: boolean;
4097
}, metadata?: WorkspaceEditEntryMetadata): void;
4098
4099
/**
4100
* Rename a file or folder.
4101
*
4102
* @param oldUri The existing file.
4103
* @param newUri The new location.
4104
* @param options Defines if existing files should be overwritten or be
4105
* ignored. When overwrite and ignoreIfExists are both set overwrite wins.
4106
* @param metadata Optional metadata for the entry.
4107
*/
4108
renameFile(oldUri: Uri, newUri: Uri, options?: {
4109
/**
4110
* Overwrite existing file. Overwrite wins over `ignoreIfExists`
4111
*/
4112
readonly overwrite?: boolean;
4113
/**
4114
* Do nothing if a file with `uri` exists already.
4115
*/
4116
readonly ignoreIfExists?: boolean;
4117
}, metadata?: WorkspaceEditEntryMetadata): void;
4118
4119
/**
4120
* Get all text edits grouped by resource.
4121
*
4122
* @returns A shallow copy of `[Uri, TextEdit[]]`-tuples.
4123
*/
4124
entries(): [Uri, TextEdit[]][];
4125
}
4126
4127
/**
4128
* A snippet string is a template which allows to insert text
4129
* and to control the editor cursor when insertion happens.
4130
*
4131
* A snippet can define tab stops and placeholders with `$1`, `$2`
4132
* and `${3:foo}`. `$0` defines the final tab stop, it defaults to
4133
* the end of the snippet. Variables are defined with `$name` and
4134
* `${name:default value}`. Also see
4135
* [the full snippet syntax](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_create-your-own-snippets).
4136
*/
4137
export class SnippetString {
4138
4139
/**
4140
* The snippet string.
4141
*/
4142
value: string;
4143
4144
/**
4145
* Create a new snippet string.
4146
*
4147
* @param value A snippet string.
4148
*/
4149
constructor(value?: string);
4150
4151
/**
4152
* Builder-function that appends the given string to
4153
* the {@linkcode SnippetString.value value} of this snippet string.
4154
*
4155
* @param string A value to append 'as given'. The string will be escaped.
4156
* @returns This snippet string.
4157
*/
4158
appendText(string: string): SnippetString;
4159
4160
/**
4161
* Builder-function that appends a tabstop (`$1`, `$2` etc) to
4162
* the {@linkcode SnippetString.value value} of this snippet string.
4163
*
4164
* @param number The number of this tabstop, defaults to an auto-increment
4165
* value starting at 1.
4166
* @returns This snippet string.
4167
*/
4168
appendTabstop(number?: number): SnippetString;
4169
4170
/**
4171
* Builder-function that appends a placeholder (`${1:value}`) to
4172
* the {@linkcode SnippetString.value value} of this snippet string.
4173
*
4174
* @param value The value of this placeholder - either a string or a function
4175
* with which a nested snippet can be created.
4176
* @param number The number of this tabstop, defaults to an auto-increment
4177
* value starting at 1.
4178
* @returns This snippet string.
4179
*/
4180
appendPlaceholder(value: string | ((snippet: SnippetString) => any), number?: number): SnippetString;
4181
4182
/**
4183
* Builder-function that appends a choice (`${1|a,b,c|}`) to
4184
* the {@linkcode SnippetString.value value} of this snippet string.
4185
*
4186
* @param values The values for choices - the array of strings
4187
* @param number The number of this tabstop, defaults to an auto-increment
4188
* value starting at 1.
4189
* @returns This snippet string.
4190
*/
4191
appendChoice(values: readonly string[], number?: number): SnippetString;
4192
4193
/**
4194
* Builder-function that appends a variable (`${VAR}`) to
4195
* the {@linkcode SnippetString.value value} of this snippet string.
4196
*
4197
* @param name The name of the variable - excluding the `$`.
4198
* @param defaultValue The default value which is used when the variable name cannot
4199
* be resolved - either a string or a function with which a nested snippet can be created.
4200
* @returns This snippet string.
4201
*/
4202
appendVariable(name: string, defaultValue: string | ((snippet: SnippetString) => any)): SnippetString;
4203
}
4204
4205
/**
4206
* The rename provider interface defines the contract between extensions and
4207
* the [rename](https://code.visualstudio.com/docs/editor/editingevolved#_rename-symbol)-feature.
4208
*/
4209
export interface RenameProvider {
4210
4211
/**
4212
* Provide an edit that describes changes that have to be made to one
4213
* or many resources to rename a symbol to a different name.
4214
*
4215
* @param document The document in which the command was invoked.
4216
* @param position The position at which the command was invoked.
4217
* @param newName The new name of the symbol. If the given name is not valid, the provider must return a rejected promise.
4218
* @param token A cancellation token.
4219
* @returns A workspace edit or a thenable that resolves to such. The lack of a result can be
4220
* signaled by returning `undefined` or `null`.
4221
*/
4222
provideRenameEdits(document: TextDocument, position: Position, newName: string, token: CancellationToken): ProviderResult<WorkspaceEdit>;
4223
4224
/**
4225
* Optional function for resolving and validating a position *before* running rename. The result can
4226
* be a range or a range and a placeholder text. The placeholder text should be the identifier of the symbol
4227
* which is being renamed - when omitted the text in the returned range is used.
4228
*
4229
* *Note:* This function should throw an error or return a rejected thenable when the provided location
4230
* doesn't allow for a rename.
4231
*
4232
* @param document The document in which rename will be invoked.
4233
* @param position The position at which rename will be invoked.
4234
* @param token A cancellation token.
4235
* @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`.
4236
*/
4237
prepareRename?(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Range | {
4238
/**
4239
* The range of the identifier that can be renamed.
4240
*/
4241
range: Range;
4242
/**
4243
* The placeholder of the editors rename input box.
4244
*/
4245
placeholder: string;
4246
}>;
4247
}
4248
4249
/**
4250
* A semantic tokens legend contains the needed information to decipher
4251
* the integer encoded representation of semantic tokens.
4252
*/
4253
export class SemanticTokensLegend {
4254
/**
4255
* The possible token types.
4256
*/
4257
readonly tokenTypes: string[];
4258
/**
4259
* The possible token modifiers.
4260
*/
4261
readonly tokenModifiers: string[];
4262
4263
/**
4264
* Creates a semantic tokens legend.
4265
*
4266
* @param tokenTypes An array of token types.
4267
* @param tokenModifiers An array of token modifiers.
4268
*/
4269
constructor(tokenTypes: string[], tokenModifiers?: string[]);
4270
}
4271
4272
/**
4273
* A semantic tokens builder can help with creating a `SemanticTokens` instance
4274
* which contains delta encoded semantic tokens.
4275
*/
4276
export class SemanticTokensBuilder {
4277
4278
/**
4279
* Creates a semantic tokens builder.
4280
*
4281
* @param legend A semantic tokens legend.
4282
*/
4283
constructor(legend?: SemanticTokensLegend);
4284
4285
/**
4286
* Add another token.
4287
*
4288
* @param line The token start line number (absolute value).
4289
* @param char The token start character (absolute value).
4290
* @param length The token length in characters.
4291
* @param tokenType The encoded token type.
4292
* @param tokenModifiers The encoded token modifiers.
4293
*/
4294
push(line: number, char: number, length: number, tokenType: number, tokenModifiers?: number): void;
4295
4296
/**
4297
* Add another token. Use only when providing a legend.
4298
*
4299
* @param range The range of the token. Must be single-line.
4300
* @param tokenType The token type.
4301
* @param tokenModifiers The token modifiers.
4302
*/
4303
push(range: Range, tokenType: string, tokenModifiers?: readonly string[]): void;
4304
4305
/**
4306
* Finish and create a `SemanticTokens` instance.
4307
*/
4308
build(resultId?: string): SemanticTokens;
4309
}
4310
4311
/**
4312
* Represents semantic tokens, either in a range or in an entire document.
4313
* @see {@link DocumentSemanticTokensProvider.provideDocumentSemanticTokens provideDocumentSemanticTokens} for an explanation of the format.
4314
* @see {@link SemanticTokensBuilder} for a helper to create an instance.
4315
*/
4316
export class SemanticTokens {
4317
/**
4318
* The result id of the tokens.
4319
*
4320
* This is the id that will be passed to `DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits` (if implemented).
4321
*/
4322
readonly resultId: string | undefined;
4323
/**
4324
* The actual tokens data.
4325
* @see {@link DocumentSemanticTokensProvider.provideDocumentSemanticTokens provideDocumentSemanticTokens} for an explanation of the format.
4326
*/
4327
readonly data: Uint32Array;
4328
4329
/**
4330
* Create new semantic tokens.
4331
*
4332
* @param data Token data.
4333
* @param resultId Result identifier.
4334
*/
4335
constructor(data: Uint32Array, resultId?: string);
4336
}
4337
4338
/**
4339
* Represents edits to semantic tokens.
4340
* @see {@link DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits provideDocumentSemanticTokensEdits} for an explanation of the format.
4341
*/
4342
export class SemanticTokensEdits {
4343
/**
4344
* The result id of the tokens.
4345
*
4346
* This is the id that will be passed to `DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits` (if implemented).
4347
*/
4348
readonly resultId: string | undefined;
4349
/**
4350
* The edits to the tokens data.
4351
* All edits refer to the initial data state.
4352
*/
4353
readonly edits: SemanticTokensEdit[];
4354
4355
/**
4356
* Create new semantic tokens edits.
4357
*
4358
* @param edits An array of semantic token edits
4359
* @param resultId Result identifier.
4360
*/
4361
constructor(edits: SemanticTokensEdit[], resultId?: string);
4362
}
4363
4364
/**
4365
* Represents an edit to semantic tokens.
4366
* @see {@link DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits provideDocumentSemanticTokensEdits} for an explanation of the format.
4367
*/
4368
export class SemanticTokensEdit {
4369
/**
4370
* The start offset of the edit.
4371
*/
4372
readonly start: number;
4373
/**
4374
* The count of elements to remove.
4375
*/
4376
readonly deleteCount: number;
4377
/**
4378
* The elements to insert.
4379
*/
4380
readonly data: Uint32Array | undefined;
4381
4382
/**
4383
* Create a semantic token edit.
4384
*
4385
* @param start Start offset
4386
* @param deleteCount Number of elements to remove.
4387
* @param data Elements to insert
4388
*/
4389
constructor(start: number, deleteCount: number, data?: Uint32Array);
4390
}
4391
4392
/**
4393
* The document semantic tokens provider interface defines the contract between extensions and
4394
* semantic tokens.
4395
*/
4396
export interface DocumentSemanticTokensProvider {
4397
/**
4398
* An optional event to signal that the semantic tokens from this provider have changed.
4399
*/
4400
onDidChangeSemanticTokens?: Event<void>;
4401
4402
/**
4403
* Tokens in a file are represented as an array of integers. The position of each token is expressed relative to
4404
* the token before it, because most tokens remain stable relative to each other when edits are made in a file.
4405
*
4406
* ---
4407
* In short, each token takes 5 integers to represent, so a specific token `i` in the file consists of the following array indices:
4408
* - at index `5*i` - `deltaLine`: token line number, relative to the previous token
4409
* - at index `5*i+1` - `deltaStart`: token start character, relative to the previous token (relative to 0 or the previous token's start if they are on the same line)
4410
* - at index `5*i+2` - `length`: the length of the token. A token cannot be multiline.
4411
* - at index `5*i+3` - `tokenType`: will be looked up in `SemanticTokensLegend.tokenTypes`. We currently ask that `tokenType` < 65536.
4412
* - at index `5*i+4` - `tokenModifiers`: each set bit will be looked up in `SemanticTokensLegend.tokenModifiers`
4413
*
4414
* ---
4415
* ### How to encode tokens
4416
*
4417
* Here is an example for encoding a file with 3 tokens in a uint32 array:
4418
* ```
4419
* { line: 2, startChar: 5, length: 3, tokenType: "property", tokenModifiers: ["private", "static"] },
4420
* { line: 2, startChar: 10, length: 4, tokenType: "type", tokenModifiers: [] },
4421
* { line: 5, startChar: 2, length: 7, tokenType: "class", tokenModifiers: [] }
4422
* ```
4423
*
4424
* 1. First of all, a legend must be devised. This legend must be provided up-front and capture all possible token types.
4425
* For this example, we will choose the following legend which must be passed in when registering the provider:
4426
* ```
4427
* tokenTypes: ['property', 'type', 'class'],
4428
* tokenModifiers: ['private', 'static']
4429
* ```
4430
*
4431
* 2. The first transformation step is to encode `tokenType` and `tokenModifiers` as integers using the legend. Token types are looked
4432
* up by index, so a `tokenType` value of `1` means `tokenTypes[1]`. Multiple token modifiers can be set by using bit flags,
4433
* so a `tokenModifier` value of `3` is first viewed as binary `0b00000011`, which means `[tokenModifiers[0], tokenModifiers[1]]` because
4434
* bits 0 and 1 are set. Using this legend, the tokens now are:
4435
* ```
4436
* { line: 2, startChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 },
4437
* { line: 2, startChar: 10, length: 4, tokenType: 1, tokenModifiers: 0 },
4438
* { line: 5, startChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 }
4439
* ```
4440
*
4441
* 3. The next step is to represent each token relative to the previous token in the file. In this case, the second token
4442
* is on the same line as the first token, so the `startChar` of the second token is made relative to the `startChar`
4443
* of the first token, so it will be `10 - 5`. The third token is on a different line than the second token, so the
4444
* `startChar` of the third token will not be altered:
4445
* ```
4446
* { deltaLine: 2, deltaStartChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 },
4447
* { deltaLine: 0, deltaStartChar: 5, length: 4, tokenType: 1, tokenModifiers: 0 },
4448
* { deltaLine: 3, deltaStartChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 }
4449
* ```
4450
*
4451
* 4. Finally, the last step is to inline each of the 5 fields for a token in a single array, which is a memory friendly representation:
4452
* ```
4453
* // 1st token, 2nd token, 3rd token
4454
* [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ]
4455
* ```
4456
*
4457
* @see {@link SemanticTokensBuilder} for a helper to encode tokens as integers.
4458
* *NOTE*: When doing edits, it is possible that multiple edits occur until the editor decides to invoke the semantic tokens provider.
4459
* *NOTE*: If the provider cannot temporarily compute semantic tokens, it can indicate this by throwing an error with the message 'Busy'.
4460
*/
4461
provideDocumentSemanticTokens(document: TextDocument, token: CancellationToken): ProviderResult<SemanticTokens>;
4462
4463
/**
4464
* Instead of always returning all the tokens in a file, it is possible for a `DocumentSemanticTokensProvider` to implement
4465
* this method (`provideDocumentSemanticTokensEdits`) and then return incremental updates to the previously provided semantic tokens.
4466
*
4467
* ---
4468
* ### How tokens change when the document changes
4469
*
4470
* Suppose that `provideDocumentSemanticTokens` has previously returned the following semantic tokens:
4471
* ```
4472
* // 1st token, 2nd token, 3rd token
4473
* [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ]
4474
* ```
4475
*
4476
* Also suppose that after some edits, the new semantic tokens in a file are:
4477
* ```
4478
* // 1st token, 2nd token, 3rd token
4479
* [ 3,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ]
4480
* ```
4481
* It is possible to express these new tokens in terms of an edit applied to the previous tokens:
4482
* ```
4483
* [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] // old tokens
4484
* [ 3,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] // new tokens
4485
*
4486
* edit: { start: 0, deleteCount: 1, data: [3] } // replace integer at offset 0 with 3
4487
* ```
4488
*
4489
* *NOTE*: If the provider cannot compute `SemanticTokensEdits`, it can "give up" and return all the tokens in the document again.
4490
* *NOTE*: All edits in `SemanticTokensEdits` contain indices in the old integers array, so they all refer to the previous result state.
4491
*/
4492
provideDocumentSemanticTokensEdits?(document: TextDocument, previousResultId: string, token: CancellationToken): ProviderResult<SemanticTokens | SemanticTokensEdits>;
4493
}
4494
4495
/**
4496
* The document range semantic tokens provider interface defines the contract between extensions and
4497
* semantic tokens.
4498
*/
4499
export interface DocumentRangeSemanticTokensProvider {
4500
4501
/**
4502
* An optional event to signal that the semantic tokens from this provider have changed.
4503
*/
4504
onDidChangeSemanticTokens?: Event<void>;
4505
4506
/**
4507
* @see {@link DocumentSemanticTokensProvider.provideDocumentSemanticTokens provideDocumentSemanticTokens}.
4508
*/
4509
provideDocumentRangeSemanticTokens(document: TextDocument, range: Range, token: CancellationToken): ProviderResult<SemanticTokens>;
4510
}
4511
4512
/**
4513
* Value-object describing what options formatting should use.
4514
*/
4515
export interface FormattingOptions {
4516
4517
/**
4518
* Size of a tab in spaces.
4519
*/
4520
tabSize: number;
4521
4522
/**
4523
* Prefer spaces over tabs.
4524
*/
4525
insertSpaces: boolean;
4526
4527
/**
4528
* Signature for further properties.
4529
*/
4530
[key: string]: boolean | number | string;
4531
}
4532
4533
/**
4534
* The document formatting provider interface defines the contract between extensions and
4535
* the formatting-feature.
4536
*/
4537
export interface DocumentFormattingEditProvider {
4538
4539
/**
4540
* Provide formatting edits for a whole document.
4541
*
4542
* @param document The document in which the command was invoked.
4543
* @param options Options controlling formatting.
4544
* @param token A cancellation token.
4545
* @returns A set of text edits or a thenable that resolves to such. The lack of a result can be
4546
* signaled by returning `undefined`, `null`, or an empty array.
4547
*/
4548
provideDocumentFormattingEdits(document: TextDocument, options: FormattingOptions, token: CancellationToken): ProviderResult<TextEdit[]>;
4549
}
4550
4551
/**
4552
* The document formatting provider interface defines the contract between extensions and
4553
* the formatting-feature.
4554
*/
4555
export interface DocumentRangeFormattingEditProvider {
4556
4557
/**
4558
* Provide formatting edits for a range in a document.
4559
*
4560
* The given range is a hint and providers can decide to format a smaller
4561
* or larger range. Often this is done by adjusting the start and end
4562
* of the range to full syntax nodes.
4563
*
4564
* @param document The document in which the command was invoked.
4565
* @param range The range which should be formatted.
4566
* @param options Options controlling formatting.
4567
* @param token A cancellation token.
4568
* @returns A set of text edits or a thenable that resolves to such. The lack of a result can be
4569
* signaled by returning `undefined`, `null`, or an empty array.
4570
*/
4571
provideDocumentRangeFormattingEdits(document: TextDocument, range: Range, options: FormattingOptions, token: CancellationToken): ProviderResult<TextEdit[]>;
4572
4573
4574
/**
4575
* Provide formatting edits for multiple ranges in a document.
4576
*
4577
* This function is optional but allows a formatter to perform faster when formatting only modified ranges or when
4578
* formatting a large number of selections.
4579
*
4580
* The given ranges are hints and providers can decide to format a smaller
4581
* or larger range. Often this is done by adjusting the start and end
4582
* of the range to full syntax nodes.
4583
*
4584
* @param document The document in which the command was invoked.
4585
* @param ranges The ranges which should be formatted.
4586
* @param options Options controlling formatting.
4587
* @param token A cancellation token.
4588
* @returns A set of text edits or a thenable that resolves to such. The lack of a result can be
4589
* signaled by returning `undefined`, `null`, or an empty array.
4590
*/
4591
provideDocumentRangesFormattingEdits?(document: TextDocument, ranges: Range[], options: FormattingOptions, token: CancellationToken): ProviderResult<TextEdit[]>;
4592
}
4593
4594
/**
4595
* The document formatting provider interface defines the contract between extensions and
4596
* the formatting-feature.
4597
*/
4598
export interface OnTypeFormattingEditProvider {
4599
4600
/**
4601
* Provide formatting edits after a character has been typed.
4602
*
4603
* The given position and character should hint to the provider
4604
* what range the position to expand to, like find the matching `{`
4605
* when `}` has been entered.
4606
*
4607
* @param document The document in which the command was invoked.
4608
* @param position The position at which the command was invoked.
4609
* @param ch The character that has been typed.
4610
* @param options Options controlling formatting.
4611
* @param token A cancellation token.
4612
* @returns A set of text edits or a thenable that resolves to such. The lack of a result can be
4613
* signaled by returning `undefined`, `null`, or an empty array.
4614
*/
4615
provideOnTypeFormattingEdits(document: TextDocument, position: Position, ch: string, options: FormattingOptions, token: CancellationToken): ProviderResult<TextEdit[]>;
4616
}
4617
4618
/**
4619
* Represents a parameter of a callable-signature. A parameter can
4620
* have a label and a doc-comment.
4621
*/
4622
export class ParameterInformation {
4623
4624
/**
4625
* The label of this signature.
4626
*
4627
* Either a string or inclusive start and exclusive end offsets within its containing
4628
* {@link SignatureInformation.label signature label}. *Note*: A label of type string must be
4629
* a substring of its containing signature information's {@link SignatureInformation.label label}.
4630
*/
4631
label: string | [number, number];
4632
4633
/**
4634
* The human-readable doc-comment of this signature. Will be shown
4635
* in the UI but can be omitted.
4636
*/
4637
documentation?: string | MarkdownString;
4638
4639
/**
4640
* Creates a new parameter information object.
4641
*
4642
* @param label A label string or inclusive start and exclusive end offsets within its containing signature label.
4643
* @param documentation A doc string.
4644
*/
4645
constructor(label: string | [number, number], documentation?: string | MarkdownString);
4646
}
4647
4648
/**
4649
* Represents the signature of something callable. A signature
4650
* can have a label, like a function-name, a doc-comment, and
4651
* a set of parameters.
4652
*/
4653
export class SignatureInformation {
4654
4655
/**
4656
* The label of this signature. Will be shown in
4657
* the UI.
4658
*/
4659
label: string;
4660
4661
/**
4662
* The human-readable doc-comment of this signature. Will be shown
4663
* in the UI but can be omitted.
4664
*/
4665
documentation?: string | MarkdownString;
4666
4667
/**
4668
* The parameters of this signature.
4669
*/
4670
parameters: ParameterInformation[];
4671
4672
/**
4673
* The index of the active parameter.
4674
*
4675
* If provided, this is used in place of {@linkcode SignatureHelp.activeParameter}.
4676
*/
4677
activeParameter?: number;
4678
4679
/**
4680
* Creates a new signature information object.
4681
*
4682
* @param label A label string.
4683
* @param documentation A doc string.
4684
*/
4685
constructor(label: string, documentation?: string | MarkdownString);
4686
}
4687
4688
/**
4689
* Signature help represents the signature of something
4690
* callable. There can be multiple signatures but only one
4691
* active and only one active parameter.
4692
*/
4693
export class SignatureHelp {
4694
4695
/**
4696
* One or more signatures.
4697
*/
4698
signatures: SignatureInformation[];
4699
4700
/**
4701
* The active signature.
4702
*/
4703
activeSignature: number;
4704
4705
/**
4706
* The active parameter of the active signature.
4707
*/
4708
activeParameter: number;
4709
}
4710
4711
/**
4712
* How a {@linkcode SignatureHelpProvider} was triggered.
4713
*/
4714
export enum SignatureHelpTriggerKind {
4715
/**
4716
* Signature help was invoked manually by the user or by a command.
4717
*/
4718
Invoke = 1,
4719
4720
/**
4721
* Signature help was triggered by a trigger character.
4722
*/
4723
TriggerCharacter = 2,
4724
4725
/**
4726
* Signature help was triggered by the cursor moving or by the document content changing.
4727
*/
4728
ContentChange = 3,
4729
}
4730
4731
/**
4732
* Additional information about the context in which a
4733
* {@linkcode SignatureHelpProvider.provideSignatureHelp SignatureHelpProvider} was triggered.
4734
*/
4735
export interface SignatureHelpContext {
4736
/**
4737
* Action that caused signature help to be triggered.
4738
*/
4739
readonly triggerKind: SignatureHelpTriggerKind;
4740
4741
/**
4742
* Character that caused signature help to be triggered.
4743
*
4744
* This is `undefined` when signature help is not triggered by typing, such as when manually invoking
4745
* signature help or when moving the cursor.
4746
*/
4747
readonly triggerCharacter: string | undefined;
4748
4749
/**
4750
* `true` if signature help was already showing when it was triggered.
4751
*
4752
* Retriggers occur when the signature help is already active and can be caused by actions such as
4753
* typing a trigger character, a cursor move, or document content changes.
4754
*/
4755
readonly isRetrigger: boolean;
4756
4757
/**
4758
* The currently active {@linkcode SignatureHelp}.
4759
*
4760
* The `activeSignatureHelp` has its {@linkcode SignatureHelp.activeSignature activeSignature} field updated based on
4761
* the user arrowing through available signatures.
4762
*/
4763
readonly activeSignatureHelp: SignatureHelp | undefined;
4764
}
4765
4766
/**
4767
* The signature help provider interface defines the contract between extensions and
4768
* the [parameter hints](https://code.visualstudio.com/docs/editor/intellisense)-feature.
4769
*/
4770
export interface SignatureHelpProvider {
4771
4772
/**
4773
* Provide help for the signature at the given position and document.
4774
*
4775
* @param document The document in which the command was invoked.
4776
* @param position The position at which the command was invoked.
4777
* @param token A cancellation token.
4778
* @param context Information about how signature help was triggered.
4779
*
4780
* @returns Signature help or a thenable that resolves to such. The lack of a result can be
4781
* signaled by returning `undefined` or `null`.
4782
*/
4783
provideSignatureHelp(document: TextDocument, position: Position, token: CancellationToken, context: SignatureHelpContext): ProviderResult<SignatureHelp>;
4784
}
4785
4786
/**
4787
* Metadata about a registered {@linkcode SignatureHelpProvider}.
4788
*/
4789
export interface SignatureHelpProviderMetadata {
4790
/**
4791
* List of characters that trigger signature help.
4792
*/
4793
readonly triggerCharacters: readonly string[];
4794
4795
/**
4796
* List of characters that re-trigger signature help.
4797
*
4798
* These trigger characters are only active when signature help is already showing. All trigger characters
4799
* are also counted as re-trigger characters.
4800
*/
4801
readonly retriggerCharacters: readonly string[];
4802
}
4803
4804
/**
4805
* A structured label for a {@link CompletionItem completion item}.
4806
*/
4807
export interface CompletionItemLabel {
4808
4809
/**
4810
* The label of this completion item.
4811
*
4812
* By default this is also the text that is inserted when this completion is selected.
4813
*/
4814
label: string;
4815
4816
/**
4817
* An optional string which is rendered less prominently directly after {@link CompletionItemLabel.label label},
4818
* without any spacing. Should be used for function signatures or type annotations.
4819
*/
4820
detail?: string;
4821
4822
/**
4823
* An optional string which is rendered less prominently after {@link CompletionItemLabel.detail}. Should be used
4824
* for fully qualified names or file path.
4825
*/
4826
description?: string;
4827
}
4828
4829
/**
4830
* Completion item kinds.
4831
*/
4832
export enum CompletionItemKind {
4833
/**
4834
* The `Text` completion item kind.
4835
*/
4836
Text = 0,
4837
/**
4838
* The `Method` completion item kind.
4839
*/
4840
Method = 1,
4841
/**
4842
* The `Function` completion item kind.
4843
*/
4844
Function = 2,
4845
/**
4846
* The `Constructor` completion item kind.
4847
*/
4848
Constructor = 3,
4849
/**
4850
* The `Field` completion item kind.
4851
*/
4852
Field = 4,
4853
/**
4854
* The `Variable` completion item kind.
4855
*/
4856
Variable = 5,
4857
/**
4858
* The `Class` completion item kind.
4859
*/
4860
Class = 6,
4861
/**
4862
* The `Interface` completion item kind.
4863
*/
4864
Interface = 7,
4865
/**
4866
* The `Module` completion item kind.
4867
*/
4868
Module = 8,
4869
/**
4870
* The `Property` completion item kind.
4871
*/
4872
Property = 9,
4873
/**
4874
* The `Unit` completion item kind.
4875
*/
4876
Unit = 10,
4877
/**
4878
* The `Value` completion item kind.
4879
*/
4880
Value = 11,
4881
/**
4882
* The `Enum` completion item kind.
4883
*/
4884
Enum = 12,
4885
/**
4886
* The `Keyword` completion item kind.
4887
*/
4888
Keyword = 13,
4889
/**
4890
* The `Snippet` completion item kind.
4891
*/
4892
Snippet = 14,
4893
/**
4894
* The `Color` completion item kind.
4895
*/
4896
Color = 15,
4897
/**
4898
* The `Reference` completion item kind.
4899
*/
4900
Reference = 17,
4901
/**
4902
* The `File` completion item kind.
4903
*/
4904
File = 16,
4905
/**
4906
* The `Folder` completion item kind.
4907
*/
4908
Folder = 18,
4909
/**
4910
* The `EnumMember` completion item kind.
4911
*/
4912
EnumMember = 19,
4913
/**
4914
* The `Constant` completion item kind.
4915
*/
4916
Constant = 20,
4917
/**
4918
* The `Struct` completion item kind.
4919
*/
4920
Struct = 21,
4921
/**
4922
* The `Event` completion item kind.
4923
*/
4924
Event = 22,
4925
/**
4926
* The `Operator` completion item kind.
4927
*/
4928
Operator = 23,
4929
/**
4930
* The `TypeParameter` completion item kind.
4931
*/
4932
TypeParameter = 24,
4933
/**
4934
* The `User` completion item kind.
4935
*/
4936
User = 25,
4937
/**
4938
* The `Issue` completion item kind.
4939
*/
4940
Issue = 26,
4941
}
4942
4943
/**
4944
* Completion item tags are extra annotations that tweak the rendering of a completion
4945
* item.
4946
*/
4947
export enum CompletionItemTag {
4948
/**
4949
* Render a completion as obsolete, usually using a strike-out.
4950
*/
4951
Deprecated = 1
4952
}
4953
4954
/**
4955
* A completion item represents a text snippet that is proposed to complete text that is being typed.
4956
*
4957
* It is sufficient to create a completion item from just a {@link CompletionItem.label label}. In that
4958
* case the completion item will replace the {@link TextDocument.getWordRangeAtPosition word}
4959
* until the cursor with the given label or {@link CompletionItem.insertText insertText}. Otherwise the
4960
* given {@link CompletionItem.textEdit edit} is used.
4961
*
4962
* When selecting a completion item in the editor its defined or synthesized text edit will be applied
4963
* to *all* cursors/selections whereas {@link CompletionItem.additionalTextEdits additionalTextEdits} will be
4964
* applied as provided.
4965
*
4966
* @see {@link CompletionItemProvider.provideCompletionItems}
4967
* @see {@link CompletionItemProvider.resolveCompletionItem}
4968
*/
4969
export class CompletionItem {
4970
4971
/**
4972
* The label of this completion item. By default
4973
* this is also the text that is inserted when selecting
4974
* this completion.
4975
*/
4976
label: string | CompletionItemLabel;
4977
4978
/**
4979
* The kind of this completion item. Based on the kind
4980
* an icon is chosen by the editor.
4981
*/
4982
kind?: CompletionItemKind;
4983
4984
/**
4985
* Tags for this completion item.
4986
*/
4987
tags?: readonly CompletionItemTag[];
4988
4989
/**
4990
* A human-readable string with additional information
4991
* about this item, like type or symbol information.
4992
*/
4993
detail?: string;
4994
4995
/**
4996
* A human-readable string that represents a doc-comment.
4997
*/
4998
documentation?: string | MarkdownString;
4999
5000
/**
5001
* A string that should be used when comparing this item
5002
* with other items. When `falsy` the {@link CompletionItem.label label}
5003
* is used.
5004
*
5005
* Note that `sortText` is only used for the initial ordering of completion
5006
* items. When having a leading word (prefix) ordering is based on how
5007
* well completions match that prefix and the initial ordering is only used
5008
* when completions match equally well. The prefix is defined by the
5009
* {@linkcode CompletionItem.range range}-property and can therefore be different
5010
* for each completion.
5011
*/
5012
sortText?: string;
5013
5014
/**
5015
* A string that should be used when filtering a set of
5016
* completion items. When `falsy` the {@link CompletionItem.label label}
5017
* is used.
5018
*
5019
* Note that the filter text is matched against the leading word (prefix) which is defined
5020
* by the {@linkcode CompletionItem.range range}-property.
5021
*/
5022
filterText?: string;
5023
5024
/**
5025
* Select this item when showing. *Note* that only one completion item can be selected and
5026
* that the editor decides which item that is. The rule is that the *first* item of those
5027
* that match best is selected.
5028
*/
5029
preselect?: boolean;
5030
5031
/**
5032
* A string or snippet that should be inserted in a document when selecting
5033
* this completion. When `falsy` the {@link CompletionItem.label label}
5034
* is used.
5035
*/
5036
insertText?: string | SnippetString;
5037
5038
/**
5039
* A range or a insert and replace range selecting the text that should be replaced by this completion item.
5040
*
5041
* When omitted, the range of the {@link TextDocument.getWordRangeAtPosition current word} is used as replace-range
5042
* and as insert-range the start of the {@link TextDocument.getWordRangeAtPosition current word} to the
5043
* current position is used.
5044
*
5045
* *Note 1:* A range must be a {@link Range.isSingleLine single line} and it must
5046
* {@link Range.contains contain} the position at which completion has been {@link CompletionItemProvider.provideCompletionItems requested}.
5047
* *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.
5048
*/
5049
range?: Range | {
5050
/**
5051
* The range that should be used when insert-accepting a completion. Must be a prefix of `replaceRange`.
5052
*/
5053
inserting: Range;
5054
/**
5055
* The range that should be used when replace-accepting a completion.
5056
*/
5057
replacing: Range;
5058
};
5059
5060
/**
5061
* An optional set of characters that when pressed while this completion is active will accept it first and
5062
* then type that character. *Note* that all commit characters should have `length=1` and that superfluous
5063
* characters will be ignored.
5064
*/
5065
commitCharacters?: string[];
5066
5067
/**
5068
* Keep whitespace of the {@link CompletionItem.insertText insertText} as is. By default, the editor adjusts leading
5069
* whitespace of new lines so that they match the indentation of the line for which the item is accepted - setting
5070
* this to `true` will prevent that.
5071
*/
5072
keepWhitespace?: boolean;
5073
5074
/**
5075
* @deprecated Use `CompletionItem.insertText` and `CompletionItem.range` instead.
5076
*
5077
* An {@link TextEdit edit} which is applied to a document when selecting
5078
* this completion. When an edit is provided the value of
5079
* {@link CompletionItem.insertText insertText} is ignored.
5080
*
5081
* The {@link Range} of the edit must be single-line and on the same
5082
* line completions were {@link CompletionItemProvider.provideCompletionItems requested} at.
5083
*/
5084
textEdit?: TextEdit;
5085
5086
/**
5087
* An optional array of additional {@link TextEdit text edits} that are applied when
5088
* selecting this completion. Edits must not overlap with the main {@link CompletionItem.textEdit edit}
5089
* nor with themselves.
5090
*/
5091
additionalTextEdits?: TextEdit[];
5092
5093
/**
5094
* An optional {@link Command} that is executed *after* inserting this completion. *Note* that
5095
* additional modifications to the current document should be described with the
5096
* {@link CompletionItem.additionalTextEdits additionalTextEdits}-property.
5097
*/
5098
command?: Command;
5099
5100
/**
5101
* Creates a new completion item.
5102
*
5103
* Completion items must have at least a {@link CompletionItem.label label} which then
5104
* will be used as insert text as well as for sorting and filtering.
5105
*
5106
* @param label The label of the completion.
5107
* @param kind The {@link CompletionItemKind kind} of the completion.
5108
*/
5109
constructor(label: string | CompletionItemLabel, kind?: CompletionItemKind);
5110
}
5111
5112
/**
5113
* Represents a collection of {@link CompletionItem completion items} to be presented
5114
* in the editor.
5115
*/
5116
export class CompletionList<T extends CompletionItem = CompletionItem> {
5117
5118
/**
5119
* This list is not complete. Further typing should result in recomputing
5120
* this list.
5121
*/
5122
isIncomplete?: boolean;
5123
5124
/**
5125
* The completion items.
5126
*/
5127
items: T[];
5128
5129
/**
5130
* Creates a new completion list.
5131
*
5132
* @param items The completion items.
5133
* @param isIncomplete The list is not complete.
5134
*/
5135
constructor(items?: T[], isIncomplete?: boolean);
5136
}
5137
5138
/**
5139
* How a {@link CompletionItemProvider completion provider} was triggered
5140
*/
5141
export enum CompletionTriggerKind {
5142
/**
5143
* Completion was triggered normally.
5144
*/
5145
Invoke = 0,
5146
/**
5147
* Completion was triggered by a trigger character.
5148
*/
5149
TriggerCharacter = 1,
5150
/**
5151
* Completion was re-triggered as current completion list is incomplete
5152
*/
5153
TriggerForIncompleteCompletions = 2
5154
}
5155
5156
/**
5157
* Contains additional information about the context in which
5158
* {@link CompletionItemProvider.provideCompletionItems completion provider} is triggered.
5159
*/
5160
export interface CompletionContext {
5161
/**
5162
* How the completion was triggered.
5163
*/
5164
readonly triggerKind: CompletionTriggerKind;
5165
5166
/**
5167
* Character that triggered the completion item provider.
5168
*
5169
* `undefined` if the provider was not triggered by a character.
5170
*
5171
* The trigger character is already in the document when the completion provider is triggered.
5172
*/
5173
readonly triggerCharacter: string | undefined;
5174
}
5175
5176
/**
5177
* The completion item provider interface defines the contract between extensions and
5178
* [IntelliSense](https://code.visualstudio.com/docs/editor/intellisense).
5179
*
5180
* Providers can delay the computation of the {@linkcode CompletionItem.detail detail}
5181
* and {@linkcode CompletionItem.documentation documentation} properties by implementing the
5182
* {@linkcode CompletionItemProvider.resolveCompletionItem resolveCompletionItem}-function. However, properties that
5183
* are needed for the initial sorting and filtering, like `sortText`, `filterText`, `insertText`, and `range`, must
5184
* not be changed during resolve.
5185
*
5186
* Providers are asked for completions either explicitly by a user gesture or -depending on the configuration-
5187
* implicitly when typing words or trigger characters.
5188
*/
5189
export interface CompletionItemProvider<T extends CompletionItem = CompletionItem> {
5190
5191
/**
5192
* Provide completion items for the given position and document.
5193
*
5194
* @param document The document in which the command was invoked.
5195
* @param position The position at which the command was invoked.
5196
* @param token A cancellation token.
5197
* @param context How the completion was triggered.
5198
*
5199
* @returns An array of completions, a {@link CompletionList completion list}, or a thenable that resolves to either.
5200
* The lack of a result can be signaled by returning `undefined`, `null`, or an empty array.
5201
*/
5202
provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext): ProviderResult<T[] | CompletionList<T>>;
5203
5204
/**
5205
* Given a completion item fill in more data, like {@link CompletionItem.documentation doc-comment}
5206
* or {@link CompletionItem.detail details}.
5207
*
5208
* The editor will only resolve a completion item once.
5209
*
5210
* *Note* that this function is called when completion items are already showing in the UI or when an item has been
5211
* selected for insertion. Because of that, no property that changes the presentation (label, sorting, filtering etc)
5212
* or the (primary) insert behaviour ({@link CompletionItem.insertText insertText}) can be changed.
5213
*
5214
* This function may fill in {@link CompletionItem.additionalTextEdits additionalTextEdits}. However, that means an item might be
5215
* inserted *before* resolving is done and in that case the editor will do a best effort to still apply those additional
5216
* text edits.
5217
*
5218
* @param item A completion item currently active in the UI.
5219
* @param token A cancellation token.
5220
* @returns The resolved completion item or a thenable that resolves to of such. It is OK to return the given
5221
* `item`. When no result is returned, the given `item` will be used.
5222
*/
5223
resolveCompletionItem?(item: T, token: CancellationToken): ProviderResult<T>;
5224
}
5225
5226
5227
/**
5228
* The inline completion item provider interface defines the contract between extensions and
5229
* the inline completion feature.
5230
*
5231
* Providers are asked for completions either explicitly by a user gesture or implicitly when typing.
5232
*/
5233
export interface InlineCompletionItemProvider {
5234
5235
/**
5236
* Provides inline completion items for the given position and document.
5237
* If inline completions are enabled, this method will be called whenever the user stopped typing.
5238
* It will also be called when the user explicitly triggers inline completions or explicitly asks for the next or previous inline completion.
5239
* In that case, all available inline completions should be returned.
5240
* `context.triggerKind` can be used to distinguish between these scenarios.
5241
*
5242
* @param document The document inline completions are requested for.
5243
* @param position The position inline completions are requested for.
5244
* @param context A context object with additional information.
5245
* @param token A cancellation token.
5246
* @returns An array of completion items or a thenable that resolves to an array of completion items.
5247
*/
5248
provideInlineCompletionItems(document: TextDocument, position: Position, context: InlineCompletionContext, token: CancellationToken): ProviderResult<InlineCompletionItem[] | InlineCompletionList>;
5249
}
5250
5251
/**
5252
* Represents a collection of {@link InlineCompletionItem inline completion items} to be presented
5253
* in the editor.
5254
*/
5255
export class InlineCompletionList {
5256
/**
5257
* The inline completion items.
5258
*/
5259
items: InlineCompletionItem[];
5260
5261
/**
5262
* Creates a new list of inline completion items.
5263
*/
5264
constructor(items: InlineCompletionItem[]);
5265
}
5266
5267
/**
5268
* Provides information about the context in which an inline completion was requested.
5269
*/
5270
export interface InlineCompletionContext {
5271
/**
5272
* Describes how the inline completion was triggered.
5273
*/
5274
readonly triggerKind: InlineCompletionTriggerKind;
5275
5276
/**
5277
* Provides information about the currently selected item in the autocomplete widget if it is visible.
5278
*
5279
* If set, provided inline completions must extend the text of the selected item
5280
* and use the same range, otherwise they are not shown as preview.
5281
* As an example, if the document text is `console.` and the selected item is `.log` replacing the `.` in the document,
5282
* the inline completion must also replace `.` and start with `.log`, for example `.log()`.
5283
*
5284
* Inline completion providers are requested again whenever the selected item changes.
5285
*/
5286
readonly selectedCompletionInfo: SelectedCompletionInfo | undefined;
5287
}
5288
5289
/**
5290
* Describes the currently selected completion item.
5291
*/
5292
export interface SelectedCompletionInfo {
5293
/**
5294
* The range that will be replaced if this completion item is accepted.
5295
*/
5296
readonly range: Range;
5297
5298
/**
5299
* The text the range will be replaced with if this completion is accepted.
5300
*/
5301
readonly text: string;
5302
}
5303
5304
/**
5305
* Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.
5306
*/
5307
export enum InlineCompletionTriggerKind {
5308
/**
5309
* Completion was triggered explicitly by a user gesture.
5310
* Return multiple completion items to enable cycling through them.
5311
*/
5312
Invoke = 0,
5313
5314
/**
5315
* Completion was triggered automatically while editing.
5316
* It is sufficient to return a single completion item in this case.
5317
*/
5318
Automatic = 1,
5319
}
5320
5321
/**
5322
* An inline completion item represents a text snippet that is proposed inline to complete text that is being typed.
5323
*
5324
* @see {@link InlineCompletionItemProvider.provideInlineCompletionItems}
5325
*/
5326
export class InlineCompletionItem {
5327
/**
5328
* The text to replace the range with. Must be set.
5329
* Is used both for the preview and the accept operation.
5330
*/
5331
insertText: string | SnippetString;
5332
5333
/**
5334
* A text that is used to decide if this inline completion should be shown. When `falsy`
5335
* the {@link InlineCompletionItem.insertText} is used.
5336
*
5337
* An inline completion is shown if the text to replace is a prefix of the filter text.
5338
*/
5339
filterText?: string;
5340
5341
/**
5342
* The range to replace.
5343
* Must begin and end on the same line.
5344
*
5345
* Prefer replacements over insertions to provide a better experience when the user deletes typed text.
5346
*/
5347
range?: Range;
5348
5349
/**
5350
* An optional {@link Command} that is executed *after* inserting this completion.
5351
*/
5352
command?: Command;
5353
5354
/**
5355
* Creates a new inline completion item.
5356
*
5357
* @param insertText The text to replace the range with.
5358
* @param range The range to replace. If not set, the word at the requested position will be used.
5359
* @param command An optional {@link Command} that is executed *after* inserting this completion.
5360
*/
5361
constructor(insertText: string | SnippetString, range?: Range, command?: Command);
5362
}
5363
5364
/**
5365
* A document link is a range in a text document that links to an internal or external resource, like another
5366
* text document or a web site.
5367
*/
5368
export class DocumentLink {
5369
5370
/**
5371
* The range this link applies to.
5372
*/
5373
range: Range;
5374
5375
/**
5376
* The uri this link points to.
5377
*/
5378
target?: Uri;
5379
5380
/**
5381
* The tooltip text when you hover over this link.
5382
*
5383
* If a tooltip is provided, is will be displayed in a string that includes instructions on how to
5384
* trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS,
5385
* user settings, and localization.
5386
*/
5387
tooltip?: string;
5388
5389
/**
5390
* Creates a new document link.
5391
*
5392
* @param range The range the document link applies to. Must not be empty.
5393
* @param target The uri the document link points to.
5394
*/
5395
constructor(range: Range, target?: Uri);
5396
}
5397
5398
/**
5399
* The document link provider defines the contract between extensions and feature of showing
5400
* links in the editor.
5401
*/
5402
export interface DocumentLinkProvider<T extends DocumentLink = DocumentLink> {
5403
5404
/**
5405
* Provide links for the given document. Note that the editor ships with a default provider that detects
5406
* `http(s)` and `file` links.
5407
*
5408
* @param document The document in which the command was invoked.
5409
* @param token A cancellation token.
5410
* @returns An array of {@link DocumentLink document links} or a thenable that resolves to such. The lack of a result
5411
* can be signaled by returning `undefined`, `null`, or an empty array.
5412
*/
5413
provideDocumentLinks(document: TextDocument, token: CancellationToken): ProviderResult<T[]>;
5414
5415
/**
5416
* Given a link fill in its {@link DocumentLink.target target}. This method is called when an incomplete
5417
* link is selected in the UI. Providers can implement this method and return incomplete links
5418
* (without target) from the {@linkcode DocumentLinkProvider.provideDocumentLinks provideDocumentLinks} method which
5419
* often helps to improve performance.
5420
*
5421
* @param link The link that is to be resolved.
5422
* @param token A cancellation token.
5423
*/
5424
resolveDocumentLink?(link: T, token: CancellationToken): ProviderResult<T>;
5425
}
5426
5427
/**
5428
* Represents a color in RGBA space.
5429
*/
5430
export class Color {
5431
5432
/**
5433
* The red component of this color in the range `[0-1]`.
5434
*/
5435
readonly red: number;
5436
5437
/**
5438
* The green component of this color in the range `[0-1]`.
5439
*/
5440
readonly green: number;
5441
5442
/**
5443
* The blue component of this color in the range `[0-1]`.
5444
*/
5445
readonly blue: number;
5446
5447
/**
5448
* The alpha component of this color in the range `[0-1]`.
5449
*/
5450
readonly alpha: number;
5451
5452
/**
5453
* Creates a new color instance.
5454
*
5455
* @param red The red component.
5456
* @param green The green component.
5457
* @param blue The blue component.
5458
* @param alpha The alpha component.
5459
*/
5460
constructor(red: number, green: number, blue: number, alpha: number);
5461
}
5462
5463
/**
5464
* Represents a color range from a document.
5465
*/
5466
export class ColorInformation {
5467
5468
/**
5469
* The range in the document where this color appears.
5470
*/
5471
range: Range;
5472
5473
/**
5474
* The actual color value for this color range.
5475
*/
5476
color: Color;
5477
5478
/**
5479
* Creates a new color range.
5480
*
5481
* @param range The range the color appears in. Must not be empty.
5482
* @param color The value of the color.
5483
*/
5484
constructor(range: Range, color: Color);
5485
}
5486
5487
/**
5488
* A color presentation object describes how a {@linkcode Color} should be represented as text and what
5489
* edits are required to refer to it from source code.
5490
*
5491
* For some languages one color can have multiple presentations, e.g. css can represent the color red with
5492
* the constant `Red`, the hex-value `#ff0000`, or in rgba and hsla forms. In csharp other representations
5493
* apply, e.g. `System.Drawing.Color.Red`.
5494
*/
5495
export class ColorPresentation {
5496
5497
/**
5498
* The label of this color presentation. It will be shown on the color
5499
* picker header. By default this is also the text that is inserted when selecting
5500
* this color presentation.
5501
*/
5502
label: string;
5503
5504
/**
5505
* An {@link TextEdit edit} which is applied to a document when selecting
5506
* this presentation for the color. When `falsy` the {@link ColorPresentation.label label}
5507
* is used.
5508
*/
5509
textEdit?: TextEdit;
5510
5511
/**
5512
* An optional array of additional {@link TextEdit text edits} that are applied when
5513
* selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves.
5514
*/
5515
additionalTextEdits?: TextEdit[];
5516
5517
/**
5518
* Creates a new color presentation.
5519
*
5520
* @param label The label of this color presentation.
5521
*/
5522
constructor(label: string);
5523
}
5524
5525
/**
5526
* The document color provider defines the contract between extensions and feature of
5527
* picking and modifying colors in the editor.
5528
*/
5529
export interface DocumentColorProvider {
5530
5531
/**
5532
* Provide colors for the given document.
5533
*
5534
* @param document The document in which the command was invoked.
5535
* @param token A cancellation token.
5536
* @returns An array of {@link ColorInformation color information} or a thenable that resolves to such. The lack of a result
5537
* can be signaled by returning `undefined`, `null`, or an empty array.
5538
*/
5539
provideDocumentColors(document: TextDocument, token: CancellationToken): ProviderResult<ColorInformation[]>;
5540
5541
/**
5542
* Provide {@link ColorPresentation representations} for a color.
5543
*
5544
* @param color The color to show and insert.
5545
* @param context A context object with additional information
5546
* @param token A cancellation token.
5547
* @returns An array of color presentations or a thenable that resolves to such. The lack of a result
5548
* can be signaled by returning `undefined`, `null`, or an empty array.
5549
*/
5550
provideColorPresentations(color: Color, context: {
5551
/**
5552
* The text document that contains the color
5553
*/
5554
readonly document: TextDocument;
5555
/**
5556
* The range in the document where the color is located.
5557
*/
5558
readonly range: Range;
5559
}, token: CancellationToken): ProviderResult<ColorPresentation[]>;
5560
}
5561
5562
/**
5563
* Inlay hint kinds.
5564
*
5565
* The kind of an inline hint defines its appearance, e.g the corresponding foreground and background colors are being
5566
* used.
5567
*/
5568
export enum InlayHintKind {
5569
/**
5570
* An inlay hint that is for a type annotation.
5571
*/
5572
Type = 1,
5573
/**
5574
* An inlay hint that is for a parameter.
5575
*/
5576
Parameter = 2,
5577
}
5578
5579
/**
5580
* An inlay hint label part allows for interactive and composite labels of inlay hints.
5581
*/
5582
export class InlayHintLabelPart {
5583
5584
/**
5585
* The value of this label part.
5586
*/
5587
value: string;
5588
5589
/**
5590
* The tooltip text when you hover over this label part.
5591
*
5592
* *Note* that this property can be set late during
5593
* {@link InlayHintsProvider.resolveInlayHint resolving} of inlay hints.
5594
*/
5595
tooltip?: string | MarkdownString | undefined;
5596
5597
/**
5598
* An optional {@link Location source code location} that represents this label
5599
* part.
5600
*
5601
* The editor will use this location for the hover and for code navigation features: This
5602
* part will become a clickable link that resolves to the definition of the symbol at the
5603
* given location (not necessarily the location itself), it shows the hover that shows at
5604
* the given location, and it shows a context menu with further code navigation commands.
5605
*
5606
* *Note* that this property can be set late during
5607
* {@link InlayHintsProvider.resolveInlayHint resolving} of inlay hints.
5608
*/
5609
location?: Location | undefined;
5610
5611
/**
5612
* An optional command for this label part.
5613
*
5614
* The editor renders parts with commands as clickable links. The command is added to the context menu
5615
* when a label part defines {@link InlayHintLabelPart.location location} and {@link InlayHintLabelPart.command command} .
5616
*
5617
* *Note* that this property can be set late during
5618
* {@link InlayHintsProvider.resolveInlayHint resolving} of inlay hints.
5619
*/
5620
command?: Command | undefined;
5621
5622
/**
5623
* Creates a new inlay hint label part.
5624
*
5625
* @param value The value of the part.
5626
*/
5627
constructor(value: string);
5628
}
5629
5630
/**
5631
* Inlay hint information.
5632
*/
5633
export class InlayHint {
5634
5635
/**
5636
* The position of this hint.
5637
*/
5638
position: Position;
5639
5640
/**
5641
* The label of this hint. A human readable string or an array of {@link InlayHintLabelPart label parts}.
5642
*
5643
* *Note* that neither the string nor the label part can be empty.
5644
*/
5645
label: string | InlayHintLabelPart[];
5646
5647
/**
5648
* The tooltip text when you hover over this item.
5649
*
5650
* *Note* that this property can be set late during
5651
* {@link InlayHintsProvider.resolveInlayHint resolving} of inlay hints.
5652
*/
5653
tooltip?: string | MarkdownString | undefined;
5654
5655
/**
5656
* The kind of this hint. The inlay hint kind defines the appearance of this inlay hint.
5657
*/
5658
kind?: InlayHintKind;
5659
5660
/**
5661
* Optional {@link TextEdit text edits} that are performed when accepting this inlay hint. The default
5662
* gesture for accepting an inlay hint is the double click.
5663
*
5664
* *Note* that edits are expected to change the document so that the inlay hint (or its nearest variant) is
5665
* now part of the document and the inlay hint itself is now obsolete.
5666
*
5667
* *Note* that this property can be set late during
5668
* {@link InlayHintsProvider.resolveInlayHint resolving} of inlay hints.
5669
*/
5670
textEdits?: TextEdit[];
5671
5672
/**
5673
* Render padding before the hint. Padding will use the editor's background color,
5674
* not the background color of the hint itself. That means padding can be used to visually
5675
* align/separate an inlay hint.
5676
*/
5677
paddingLeft?: boolean;
5678
5679
/**
5680
* Render padding after the hint. Padding will use the editor's background color,
5681
* not the background color of the hint itself. That means padding can be used to visually
5682
* align/separate an inlay hint.
5683
*/
5684
paddingRight?: boolean;
5685
5686
/**
5687
* Creates a new inlay hint.
5688
*
5689
* @param position The position of the hint.
5690
* @param label The label of the hint.
5691
* @param kind The {@link InlayHintKind kind} of the hint.
5692
*/
5693
constructor(position: Position, label: string | InlayHintLabelPart[], kind?: InlayHintKind);
5694
}
5695
5696
/**
5697
* The inlay hints provider interface defines the contract between extensions and
5698
* the inlay hints feature.
5699
*/
5700
export interface InlayHintsProvider<T extends InlayHint = InlayHint> {
5701
5702
/**
5703
* An optional event to signal that inlay hints from this provider have changed.
5704
*/
5705
onDidChangeInlayHints?: Event<void>;
5706
5707
/**
5708
* Provide inlay hints for the given range and document.
5709
*
5710
* *Note* that inlay hints that are not {@link Range.contains contained} by the given range are ignored.
5711
*
5712
* @param document The document in which the command was invoked.
5713
* @param range The range for which inlay hints should be computed.
5714
* @param token A cancellation token.
5715
* @returns An array of inlay hints or a thenable that resolves to such.
5716
*/
5717
provideInlayHints(document: TextDocument, range: Range, token: CancellationToken): ProviderResult<T[]>;
5718
5719
/**
5720
* Given an inlay hint fill in {@link InlayHint.tooltip tooltip}, {@link InlayHint.textEdits text edits},
5721
* or complete label {@link InlayHintLabelPart parts}.
5722
*
5723
* *Note* that the editor will resolve an inlay hint at most once.
5724
*
5725
* @param hint An inlay hint.
5726
* @param token A cancellation token.
5727
* @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.
5728
*/
5729
resolveInlayHint?(hint: T, token: CancellationToken): ProviderResult<T>;
5730
}
5731
5732
/**
5733
* A line based folding range. To be valid, start and end line must be bigger than zero and smaller than the number of lines in the document.
5734
* Invalid ranges will be ignored.
5735
*/
5736
export class FoldingRange {
5737
5738
/**
5739
* The zero-based start line of the range to fold. The folded area starts after the line's last character.
5740
* To be valid, the end must be zero or larger and smaller than the number of lines in the document.
5741
*/
5742
start: number;
5743
5744
/**
5745
* The zero-based end line of the range to fold. The folded area ends with the line's last character.
5746
* To be valid, the end must be zero or larger and smaller than the number of lines in the document.
5747
*/
5748
end: number;
5749
5750
/**
5751
* Describes the {@link FoldingRangeKind Kind} of the folding range such as {@link FoldingRangeKind.Comment Comment} or
5752
* {@link FoldingRangeKind.Region Region}. The kind is used to categorize folding ranges and used by commands
5753
* like 'Fold all comments'. See
5754
* {@link FoldingRangeKind} for an enumeration of all kinds.
5755
* If not set, the range is originated from a syntax element.
5756
*/
5757
kind?: FoldingRangeKind;
5758
5759
/**
5760
* Creates a new folding range.
5761
*
5762
* @param start The start line of the folded range.
5763
* @param end The end line of the folded range.
5764
* @param kind The kind of the folding range.
5765
*/
5766
constructor(start: number, end: number, kind?: FoldingRangeKind);
5767
}
5768
5769
/**
5770
* An enumeration of specific folding range kinds. The kind is an optional field of a {@link FoldingRange}
5771
* and is used to distinguish specific folding ranges such as ranges originated from comments. The kind is used by commands like
5772
* `Fold all comments` or `Fold all regions`.
5773
* If the kind is not set on the range, the range originated from a syntax element other than comments, imports or region markers.
5774
*/
5775
export enum FoldingRangeKind {
5776
/**
5777
* Kind for folding range representing a comment.
5778
*/
5779
Comment = 1,
5780
/**
5781
* Kind for folding range representing a import.
5782
*/
5783
Imports = 2,
5784
/**
5785
* Kind for folding range representing regions originating from folding markers like `#region` and `#endregion`.
5786
*/
5787
Region = 3
5788
}
5789
5790
/**
5791
* Folding context (for future use)
5792
*/
5793
export interface FoldingContext {
5794
}
5795
5796
/**
5797
* The folding range provider interface defines the contract between extensions and
5798
* [Folding](https://code.visualstudio.com/docs/editor/codebasics#_folding) in the editor.
5799
*/
5800
export interface FoldingRangeProvider {
5801
5802
/**
5803
* An optional event to signal that the folding ranges from this provider have changed.
5804
*/
5805
onDidChangeFoldingRanges?: Event<void>;
5806
5807
/**
5808
* Returns a list of folding ranges or null and undefined if the provider
5809
* does not want to participate or was cancelled.
5810
* @param document The document in which the command was invoked.
5811
* @param context Additional context information (for future use)
5812
* @param token A cancellation token.
5813
*/
5814
provideFoldingRanges(document: TextDocument, context: FoldingContext, token: CancellationToken): ProviderResult<FoldingRange[]>;
5815
}
5816
5817
/**
5818
* A selection range represents a part of a selection hierarchy. A selection range
5819
* may have a parent selection range that contains it.
5820
*/
5821
export class SelectionRange {
5822
5823
/**
5824
* The {@link Range} of this selection range.
5825
*/
5826
range: Range;
5827
5828
/**
5829
* The parent selection range containing this range.
5830
*/
5831
parent?: SelectionRange;
5832
5833
/**
5834
* Creates a new selection range.
5835
*
5836
* @param range The range of the selection range.
5837
* @param parent The parent of the selection range.
5838
*/
5839
constructor(range: Range, parent?: SelectionRange);
5840
}
5841
5842
/**
5843
* The selection range provider interface defines the contract between extensions and the "Expand and Shrink Selection" feature.
5844
*/
5845
export interface SelectionRangeProvider {
5846
/**
5847
* Provide selection ranges for the given positions.
5848
*
5849
* Selection ranges should be computed individually and independent for each position. The editor will merge
5850
* and deduplicate ranges but providers must return hierarchies of selection ranges so that a range
5851
* is {@link Range.contains contained} by its parent.
5852
*
5853
* @param document The document in which the command was invoked.
5854
* @param positions The positions at which the command was invoked.
5855
* @param token A cancellation token.
5856
* @returns Selection ranges or a thenable that resolves to such. The lack of a result can be
5857
* signaled by returning `undefined` or `null`.
5858
*/
5859
provideSelectionRanges(document: TextDocument, positions: readonly Position[], token: CancellationToken): ProviderResult<SelectionRange[]>;
5860
}
5861
5862
/**
5863
* Represents programming constructs like functions or constructors in the context
5864
* of call hierarchy.
5865
*/
5866
export class CallHierarchyItem {
5867
/**
5868
* The name of this item.
5869
*/
5870
name: string;
5871
5872
/**
5873
* The kind of this item.
5874
*/
5875
kind: SymbolKind;
5876
5877
/**
5878
* Tags for this item.
5879
*/
5880
tags?: readonly SymbolTag[];
5881
5882
/**
5883
* More detail for this item, e.g. the signature of a function.
5884
*/
5885
detail?: string;
5886
5887
/**
5888
* The resource identifier of this item.
5889
*/
5890
uri: Uri;
5891
5892
/**
5893
* The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code.
5894
*/
5895
range: Range;
5896
5897
/**
5898
* The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function.
5899
* Must be contained by the {@linkcode CallHierarchyItem.range range}.
5900
*/
5901
selectionRange: Range;
5902
5903
/**
5904
* Creates a new call hierarchy item.
5905
*/
5906
constructor(kind: SymbolKind, name: string, detail: string, uri: Uri, range: Range, selectionRange: Range);
5907
}
5908
5909
/**
5910
* Represents an incoming call, e.g. a caller of a method or constructor.
5911
*/
5912
export class CallHierarchyIncomingCall {
5913
5914
/**
5915
* The item that makes the call.
5916
*/
5917
from: CallHierarchyItem;
5918
5919
/**
5920
* The range at which at which the calls appears. This is relative to the caller
5921
* denoted by {@linkcode CallHierarchyIncomingCall.from this.from}.
5922
*/
5923
fromRanges: Range[];
5924
5925
/**
5926
* Create a new call object.
5927
*
5928
* @param item The item making the call.
5929
* @param fromRanges The ranges at which the calls appear.
5930
*/
5931
constructor(item: CallHierarchyItem, fromRanges: Range[]);
5932
}
5933
5934
/**
5935
* Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc.
5936
*/
5937
export class CallHierarchyOutgoingCall {
5938
5939
/**
5940
* The item that is called.
5941
*/
5942
to: CallHierarchyItem;
5943
5944
/**
5945
* The range at which this item is called. This is the range relative to the caller, e.g the item
5946
* passed to {@linkcode CallHierarchyProvider.provideCallHierarchyOutgoingCalls provideCallHierarchyOutgoingCalls}
5947
* and not {@linkcode CallHierarchyOutgoingCall.to this.to}.
5948
*/
5949
fromRanges: Range[];
5950
5951
/**
5952
* Create a new call object.
5953
*
5954
* @param item The item being called
5955
* @param fromRanges The ranges at which the calls appear.
5956
*/
5957
constructor(item: CallHierarchyItem, fromRanges: Range[]);
5958
}
5959
5960
/**
5961
* The call hierarchy provider interface describes the contract between extensions
5962
* and the call hierarchy feature which allows to browse calls and caller of function,
5963
* methods, constructor etc.
5964
*/
5965
export interface CallHierarchyProvider {
5966
5967
/**
5968
* Bootstraps call hierarchy by returning the item that is denoted by the given document
5969
* and position. This item will be used as entry into the call graph. Providers should
5970
* return `undefined` or `null` when there is no item at the given location.
5971
*
5972
* @param document The document in which the command was invoked.
5973
* @param position The position at which the command was invoked.
5974
* @param token A cancellation token.
5975
* @returns One or multiple call hierarchy items or a thenable that resolves to such. The lack of a result can be
5976
* signaled by returning `undefined`, `null`, or an empty array.
5977
*/
5978
prepareCallHierarchy(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<CallHierarchyItem | CallHierarchyItem[]>;
5979
5980
/**
5981
* Provide all incoming calls for an item, e.g all callers for a method. In graph terms this describes directed
5982
* and annotated edges inside the call graph, e.g the given item is the starting node and the result is the nodes
5983
* that can be reached.
5984
*
5985
* @param item The hierarchy item for which incoming calls should be computed.
5986
* @param token A cancellation token.
5987
* @returns A set of incoming calls or a thenable that resolves to such. The lack of a result can be
5988
* signaled by returning `undefined` or `null`.
5989
*/
5990
provideCallHierarchyIncomingCalls(item: CallHierarchyItem, token: CancellationToken): ProviderResult<CallHierarchyIncomingCall[]>;
5991
5992
/**
5993
* Provide all outgoing calls for an item, e.g call calls to functions, methods, or constructors from the given item. In
5994
* graph terms this describes directed and annotated edges inside the call graph, e.g the given item is the starting
5995
* node and the result is the nodes that can be reached.
5996
*
5997
* @param item The hierarchy item for which outgoing calls should be computed.
5998
* @param token A cancellation token.
5999
* @returns A set of outgoing calls or a thenable that resolves to such. The lack of a result can be
6000
* signaled by returning `undefined` or `null`.
6001
*/
6002
provideCallHierarchyOutgoingCalls(item: CallHierarchyItem, token: CancellationToken): ProviderResult<CallHierarchyOutgoingCall[]>;
6003
}
6004
6005
/**
6006
* Represents an item of a type hierarchy, like a class or an interface.
6007
*/
6008
export class TypeHierarchyItem {
6009
/**
6010
* The name of this item.
6011
*/
6012
name: string;
6013
6014
/**
6015
* The kind of this item.
6016
*/
6017
kind: SymbolKind;
6018
6019
/**
6020
* Tags for this item.
6021
*/
6022
tags?: ReadonlyArray<SymbolTag>;
6023
6024
/**
6025
* More detail for this item, e.g. the signature of a function.
6026
*/
6027
detail?: string;
6028
6029
/**
6030
* The resource identifier of this item.
6031
*/
6032
uri: Uri;
6033
6034
/**
6035
* The range enclosing this symbol not including leading/trailing whitespace
6036
* but everything else, e.g. comments and code.
6037
*/
6038
range: Range;
6039
6040
/**
6041
* The range that should be selected and revealed when this symbol is being
6042
* picked, e.g. the name of a class. Must be contained by the {@link TypeHierarchyItem.range range}-property.
6043
*/
6044
selectionRange: Range;
6045
6046
/**
6047
* Creates a new type hierarchy item.
6048
*
6049
* @param kind The kind of the item.
6050
* @param name The name of the item.
6051
* @param detail The details of the item.
6052
* @param uri The Uri of the item.
6053
* @param range The whole range of the item.
6054
* @param selectionRange The selection range of the item.
6055
*/
6056
constructor(kind: SymbolKind, name: string, detail: string, uri: Uri, range: Range, selectionRange: Range);
6057
}
6058
6059
/**
6060
* The type hierarchy provider interface describes the contract between extensions
6061
* and the type hierarchy feature.
6062
*/
6063
export interface TypeHierarchyProvider {
6064
6065
/**
6066
* Bootstraps type hierarchy by returning the item that is denoted by the given document
6067
* and position. This item will be used as entry into the type graph. Providers should
6068
* return `undefined` or `null` when there is no item at the given location.
6069
*
6070
* @param document The document in which the command was invoked.
6071
* @param position The position at which the command was invoked.
6072
* @param token A cancellation token.
6073
* @returns One or multiple type hierarchy items or a thenable that resolves to such. The lack of a result can be
6074
* signaled by returning `undefined`, `null`, or an empty array.
6075
*/
6076
prepareTypeHierarchy(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<TypeHierarchyItem | TypeHierarchyItem[]>;
6077
6078
/**
6079
* Provide all supertypes for an item, e.g all types from which a type is derived/inherited. In graph terms this describes directed
6080
* and annotated edges inside the type graph, e.g the given item is the starting node and the result is the nodes
6081
* that can be reached.
6082
*
6083
* @param item The hierarchy item for which super types should be computed.
6084
* @param token A cancellation token.
6085
* @returns A set of direct supertypes or a thenable that resolves to such. The lack of a result can be
6086
* signaled by returning `undefined` or `null`.
6087
*/
6088
provideTypeHierarchySupertypes(item: TypeHierarchyItem, token: CancellationToken): ProviderResult<TypeHierarchyItem[]>;
6089
6090
/**
6091
* Provide all subtypes for an item, e.g all types which are derived/inherited from the given item. In
6092
* graph terms this describes directed and annotated edges inside the type graph, e.g the given item is the starting
6093
* node and the result is the nodes that can be reached.
6094
*
6095
* @param item The hierarchy item for which subtypes should be computed.
6096
* @param token A cancellation token.
6097
* @returns A set of direct subtypes or a thenable that resolves to such. The lack of a result can be
6098
* signaled by returning `undefined` or `null`.
6099
*/
6100
provideTypeHierarchySubtypes(item: TypeHierarchyItem, token: CancellationToken): ProviderResult<TypeHierarchyItem[]>;
6101
}
6102
6103
/**
6104
* Represents a list of ranges that can be edited together along with a word pattern to describe valid range contents.
6105
*/
6106
export class LinkedEditingRanges {
6107
/**
6108
* Create a new linked editing ranges object.
6109
*
6110
* @param ranges A list of ranges that can be edited together
6111
* @param wordPattern An optional word pattern that describes valid contents for the given ranges
6112
*/
6113
constructor(ranges: Range[], wordPattern?: RegExp);
6114
6115
/**
6116
* A list of ranges that can be edited together. The ranges must have
6117
* identical length and text content. The ranges cannot overlap.
6118
*/
6119
readonly ranges: Range[];
6120
6121
/**
6122
* An optional word pattern that describes valid contents for the given ranges.
6123
* If no pattern is provided, the language configuration's word pattern will be used.
6124
*/
6125
readonly wordPattern: RegExp | undefined;
6126
}
6127
6128
/**
6129
* The linked editing range provider interface defines the contract between extensions and
6130
* the linked editing feature.
6131
*/
6132
export interface LinkedEditingRangeProvider {
6133
/**
6134
* For a given position in a document, returns the range of the symbol at the position and all ranges
6135
* that have the same content. A change to one of the ranges can be applied to all other ranges if the new content
6136
* is valid. An optional word pattern can be returned with the result to describe valid contents.
6137
* If no result-specific word pattern is provided, the word pattern from the language configuration is used.
6138
*
6139
* @param document The document in which the provider was invoked.
6140
* @param position The position at which the provider was invoked.
6141
* @param token A cancellation token.
6142
* @returns A list of ranges that can be edited together
6143
*/
6144
provideLinkedEditingRanges(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<LinkedEditingRanges>;
6145
}
6146
6147
/**
6148
* Identifies a {@linkcode DocumentDropEdit} or {@linkcode DocumentPasteEdit}
6149
*/
6150
export class DocumentDropOrPasteEditKind {
6151
static readonly Empty: DocumentDropOrPasteEditKind;
6152
6153
/**
6154
* The root kind for basic text edits.
6155
*
6156
* This kind should be used for edits that insert basic text into the document. A good example of this is
6157
* an edit that pastes the clipboard text while also updating imports in the file based on the pasted text.
6158
* For this we could use a kind such as `text.updateImports.someLanguageId`.
6159
*
6160
* Even though most drop/paste edits ultimately insert text, you should not use {@linkcode Text} as the base kind
6161
* for every edit as this is redundant. Instead a more specific kind that describes the type of content being
6162
* inserted should be used instead. For example, if the edit adds a Markdown link, use `markdown.link` since even
6163
* though the content being inserted is text, it's more important to know that the edit inserts Markdown syntax.
6164
*/
6165
static readonly Text: DocumentDropOrPasteEditKind;
6166
6167
/**
6168
* Root kind for edits that update imports in a document in addition to inserting text.
6169
*/
6170
static readonly TextUpdateImports: DocumentDropOrPasteEditKind;
6171
6172
/**
6173
* Use {@linkcode DocumentDropOrPasteEditKind.Empty} instead.
6174
*/
6175
private constructor(value: string);
6176
6177
/**
6178
* The raw string value of the kind.
6179
*/
6180
readonly value: string;
6181
6182
/**
6183
* Create a new kind by appending additional scopes to the current kind.
6184
*
6185
* Does not modify the current kind.
6186
*/
6187
append(...parts: string[]): DocumentDropOrPasteEditKind;
6188
6189
/**
6190
* Checks if this kind intersects `other`.
6191
*
6192
* The kind `"text.plain"` for example intersects `text`, `"text.plain"` and `"text.plain.list"`,
6193
* but not `"unicorn"`, or `"textUnicorn.plain"`.
6194
*
6195
* @param other Kind to check.
6196
*/
6197
intersects(other: DocumentDropOrPasteEditKind): boolean;
6198
6199
/**
6200
* Checks if `other` is a sub-kind of this `DocumentDropOrPasteEditKind`.
6201
*
6202
* The kind `"text.plain"` for example contains `"text.plain"` and `"text.plain.list"`,
6203
* but not `"text"` or `"unicorn.text.plain"`.
6204
*
6205
* @param other Kind to check.
6206
*/
6207
contains(other: DocumentDropOrPasteEditKind): boolean;
6208
}
6209
6210
/**
6211
* An edit operation applied {@link DocumentDropEditProvider on drop}.
6212
*/
6213
export class DocumentDropEdit {
6214
/**
6215
* Human readable label that describes the edit.
6216
*/
6217
title?: string;
6218
6219
/**
6220
* {@link DocumentDropOrPasteEditKind Kind} of the edit.
6221
*/
6222
kind?: DocumentDropOrPasteEditKind;
6223
6224
/**
6225
* Controls the ordering or multiple edits. If this provider yield to edits, it will be shown lower in the list.
6226
*/
6227
yieldTo?: readonly DocumentDropOrPasteEditKind[];
6228
6229
/**
6230
* The text or snippet to insert at the drop location.
6231
*/
6232
insertText: string | SnippetString;
6233
6234
/**
6235
* An optional additional edit to apply on drop.
6236
*/
6237
additionalEdit?: WorkspaceEdit;
6238
6239
/**
6240
* @param insertText The text or snippet to insert at the drop location.
6241
* @param title Human readable label that describes the edit.
6242
* @param kind {@link DocumentDropOrPasteEditKind Kind} of the edit.
6243
*/
6244
constructor(insertText: string | SnippetString, title?: string, kind?: DocumentDropOrPasteEditKind);
6245
}
6246
6247
/**
6248
* Provider which handles dropping of resources into a text editor.
6249
*
6250
* This allows users to drag and drop resources (including resources from external apps) into the editor. While dragging
6251
* and dropping files, users can hold down `shift` to drop the file into the editor instead of opening it.
6252
* Requires `editor.dropIntoEditor.enabled` to be on.
6253
*/
6254
export interface DocumentDropEditProvider<T extends DocumentDropEdit = DocumentDropEdit> {
6255
/**
6256
* Provide edits which inserts the content being dragged and dropped into the document.
6257
*
6258
* @param document The document in which the drop occurred.
6259
* @param position The position in the document where the drop occurred.
6260
* @param dataTransfer A {@link DataTransfer} object that holds data about what is being dragged and dropped.
6261
* @param token A cancellation token.
6262
*
6263
* @returns A {@link DocumentDropEdit} or a thenable that resolves to such. The lack of a result can be
6264
* signaled by returning `undefined` or `null`.
6265
*/
6266
provideDocumentDropEdits(document: TextDocument, position: Position, dataTransfer: DataTransfer, token: CancellationToken): ProviderResult<T | T[]>;
6267
6268
/**
6269
* Optional method which fills in the {@linkcode DocumentDropEdit.additionalEdit} before the edit is applied.
6270
*
6271
* This is called once per edit and should be used if generating the complete edit may take a long time.
6272
* Resolve can only be used to change {@link DocumentDropEdit.additionalEdit}.
6273
*
6274
* @param edit The {@linkcode DocumentDropEdit} to resolve.
6275
* @param token A cancellation token.
6276
*
6277
* @returns The resolved edit or a thenable that resolves to such. It is OK to return the given
6278
* `edit`. If no result is returned, the given `edit` is used.
6279
*/
6280
resolveDocumentDropEdit?(edit: T, token: CancellationToken): ProviderResult<T>;
6281
}
6282
6283
/**
6284
* Provides additional metadata about how a {@linkcode DocumentDropEditProvider} works.
6285
*/
6286
export interface DocumentDropEditProviderMetadata {
6287
/**
6288
* List of {@link DocumentDropOrPasteEditKind kinds} that the provider may return in {@linkcode DocumentDropEditProvider.provideDocumentDropEdits provideDocumentDropEdits}.
6289
*
6290
* This is used to filter out providers when a specific {@link DocumentDropOrPasteEditKind kind} of edit is requested.
6291
*/
6292
readonly providedDropEditKinds?: readonly DocumentDropOrPasteEditKind[];
6293
6294
/**
6295
* List of {@link DataTransfer} mime types that the provider can handle.
6296
*
6297
* This can either be an exact mime type such as `image/png`, or a wildcard pattern such as `image/*`.
6298
*
6299
* Use `text/uri-list` for resources dropped from the explorer or other tree views in the workbench.
6300
*
6301
* Use `files` to indicate that the provider should be invoked if any {@link DataTransferFile files} are present in the {@link DataTransfer}.
6302
* Note that {@link DataTransferFile} entries are only created when dropping content from outside the editor, such as
6303
* from the operating system.
6304
*/
6305
readonly dropMimeTypes: readonly string[];
6306
}
6307
6308
6309
/**
6310
* The reason why paste edits were requested.
6311
*/
6312
export enum DocumentPasteTriggerKind {
6313
/**
6314
* Pasting was requested as part of a normal paste operation.
6315
*/
6316
Automatic = 0,
6317
6318
/**
6319
* Pasting was requested by the user with the `paste as` command.
6320
*/
6321
PasteAs = 1,
6322
}
6323
6324
/**
6325
* Additional information about the paste operation.
6326
*/
6327
export interface DocumentPasteEditContext {
6328
6329
/**
6330
* Requested kind of paste edits to return.
6331
*
6332
* When a explicit kind if requested by {@linkcode DocumentPasteTriggerKind.PasteAs PasteAs}, providers are
6333
* encourage to be more flexible when generating an edit of the requested kind.
6334
*/
6335
readonly only: DocumentDropOrPasteEditKind | undefined;
6336
6337
/**
6338
* The reason why paste edits were requested.
6339
*/
6340
readonly triggerKind: DocumentPasteTriggerKind;
6341
}
6342
6343
/**
6344
* Provider invoked when the user copies or pastes in a {@linkcode TextDocument}.
6345
*/
6346
export interface DocumentPasteEditProvider<T extends DocumentPasteEdit = DocumentPasteEdit> {
6347
6348
/**
6349
* Optional method invoked after the user copies from a {@link TextEditor text editor}.
6350
*
6351
* This allows the provider to attach metadata about the copied text to the {@link DataTransfer}. This data
6352
* transfer is then passed back to providers in {@linkcode provideDocumentPasteEdits}.
6353
*
6354
* Note that currently any changes to the {@linkcode DataTransfer} are isolated to the current editor window.
6355
* This means that any added metadata cannot be seen by other editor windows or by other applications.
6356
*
6357
* @param document Text document where the copy took place.
6358
* @param ranges Ranges being copied in {@linkcode document}.
6359
* @param dataTransfer The data transfer associated with the copy. You can store additional values on this for
6360
* later use in {@linkcode provideDocumentPasteEdits}. This object is only valid for the duration of this method.
6361
* @param token A cancellation token.
6362
*
6363
* @return Optional thenable that resolves when all changes to the `dataTransfer` are complete.
6364
*/
6365
prepareDocumentPaste?(document: TextDocument, ranges: readonly Range[], dataTransfer: DataTransfer, token: CancellationToken): void | Thenable<void>;
6366
6367
/**
6368
* Invoked before the user pastes into a {@link TextEditor text editor}.
6369
*
6370
* Returned edits can replace the standard pasting behavior.
6371
*
6372
* @param document Document being pasted into
6373
* @param ranges Range in the {@linkcode document} to paste into.
6374
* @param dataTransfer The {@link DataTransfer data transfer} associated with the paste. This object is only
6375
* valid for the duration of the paste operation.
6376
* @param context Additional context for the paste.
6377
* @param token A cancellation token.
6378
*
6379
* @return Set of potential {@link DocumentPasteEdit edits} that can apply the paste. Only a single returned
6380
* {@linkcode DocumentPasteEdit} is applied at a time. If multiple edits are returned from all providers, then
6381
* the first is automatically applied and a widget is shown that lets the user switch to the other edits.
6382
*/
6383
provideDocumentPasteEdits?(document: TextDocument, ranges: readonly Range[], dataTransfer: DataTransfer, context: DocumentPasteEditContext, token: CancellationToken): ProviderResult<T[]>;
6384
6385
/**
6386
* Optional method which fills in the {@linkcode DocumentPasteEdit.additionalEdit} before the edit is applied.
6387
*
6388
* This is called once per edit and should be used if generating the complete edit may take a long time.
6389
* Resolve can only be used to change {@linkcode DocumentPasteEdit.insertText} or {@linkcode DocumentPasteEdit.additionalEdit}.
6390
*
6391
* @param pasteEdit The {@linkcode DocumentPasteEdit} to resolve.
6392
* @param token A cancellation token.
6393
*
6394
* @returns The resolved paste edit or a thenable that resolves to such. It is OK to return the given
6395
* `pasteEdit`. If no result is returned, the given `pasteEdit` is used.
6396
*/
6397
resolveDocumentPasteEdit?(pasteEdit: T, token: CancellationToken): ProviderResult<T>;
6398
}
6399
6400
/**
6401
* An edit the applies a paste operation.
6402
*/
6403
export class DocumentPasteEdit {
6404
6405
/**
6406
* Human readable label that describes the edit.
6407
*/
6408
title: string;
6409
6410
/**
6411
* {@link DocumentDropOrPasteEditKind Kind} of the edit.
6412
*/
6413
kind: DocumentDropOrPasteEditKind;
6414
6415
/**
6416
* The text or snippet to insert at the pasted locations.
6417
*
6418
* If your edit requires more advanced insertion logic, set this to an empty string and provide an {@link DocumentPasteEdit.additionalEdit additional edit} instead.
6419
*/
6420
insertText: string | SnippetString;
6421
6422
/**
6423
* An optional additional edit to apply on paste.
6424
*/
6425
additionalEdit?: WorkspaceEdit;
6426
6427
/**
6428
* Controls ordering when multiple paste edits can potentially be applied.
6429
*
6430
* If this edit yields to another, it will be shown lower in the list of possible paste edits shown to the user.
6431
*/
6432
yieldTo?: readonly DocumentDropOrPasteEditKind[];
6433
6434
/**
6435
* Create a new paste edit.
6436
*
6437
* @param insertText The text or snippet to insert at the pasted locations.
6438
* @param title Human readable label that describes the edit.
6439
* @param kind {@link DocumentDropOrPasteEditKind Kind} of the edit.
6440
*/
6441
constructor(insertText: string | SnippetString, title: string, kind: DocumentDropOrPasteEditKind);
6442
}
6443
6444
/**
6445
* Provides additional metadata about how a {@linkcode DocumentPasteEditProvider} works.
6446
*/
6447
export interface DocumentPasteProviderMetadata {
6448
/**
6449
* List of {@link DocumentDropOrPasteEditKind kinds} that the provider may return in {@linkcode DocumentPasteEditProvider.provideDocumentPasteEdits provideDocumentPasteEdits}.
6450
*
6451
* This is used to filter out providers when a specific {@link DocumentDropOrPasteEditKind kind} of edit is requested.
6452
*/
6453
readonly providedPasteEditKinds: readonly DocumentDropOrPasteEditKind[];
6454
6455
/**
6456
* Mime types that {@linkcode DocumentPasteEditProvider.prepareDocumentPaste prepareDocumentPaste} may add on copy.
6457
*/
6458
readonly copyMimeTypes?: readonly string[];
6459
6460
/**
6461
* Mime types that {@linkcode DocumentPasteEditProvider.provideDocumentPasteEdits provideDocumentPasteEdits} should be invoked for.
6462
*
6463
* This can either be an exact mime type such as `image/png`, or a wildcard pattern such as `image/*`.
6464
*
6465
* Use `text/uri-list` for resources dropped from the explorer or other tree views in the workbench.
6466
*
6467
* Use `files` to indicate that the provider should be invoked if any {@link DataTransferFile files} are present in the {@linkcode DataTransfer}.
6468
* Note that {@linkcode DataTransferFile} entries are only created when pasting content from outside the editor, such as
6469
* from the operating system.
6470
*/
6471
readonly pasteMimeTypes?: readonly string[];
6472
}
6473
6474
/**
6475
* A tuple of two characters, like a pair of
6476
* opening and closing brackets.
6477
*/
6478
export type CharacterPair = [string, string];
6479
6480
/**
6481
* Configuration for line comments.
6482
*/
6483
export interface LineCommentRule {
6484
/**
6485
* The line comment token, like `//`
6486
*/
6487
comment: string;
6488
/**
6489
* Whether the comment token should not be indented and placed at the first column.
6490
* Defaults to false.
6491
*/
6492
noIndent?: boolean;
6493
}
6494
6495
/**
6496
* Describes how comments for a language work.
6497
*/
6498
export interface CommentRule {
6499
6500
/**
6501
* The line comment token, like `// this is a comment`
6502
*/
6503
lineComment?: string | LineCommentRule;
6504
6505
/**
6506
* The block comment character pair, like `/* block comment *&#47;`
6507
*/
6508
blockComment?: CharacterPair;
6509
}
6510
6511
/**
6512
* Describes indentation rules for a language.
6513
*/
6514
export interface IndentationRule {
6515
/**
6516
* If a line matches this pattern, then all the lines after it should be unindented once (until another rule matches).
6517
*/
6518
decreaseIndentPattern: RegExp;
6519
/**
6520
* If a line matches this pattern, then all the lines after it should be indented once (until another rule matches).
6521
*/
6522
increaseIndentPattern: RegExp;
6523
/**
6524
* If a line matches this pattern, then **only the next line** after it should be indented once.
6525
*/
6526
indentNextLinePattern?: RegExp;
6527
/**
6528
* If a line matches this pattern, then its indentation should not be changed and it should not be evaluated against the other rules.
6529
*/
6530
unIndentedLinePattern?: RegExp;
6531
}
6532
6533
/**
6534
* Describes what to do with the indentation when pressing Enter.
6535
*/
6536
export enum IndentAction {
6537
/**
6538
* Insert new line and copy the previous line's indentation.
6539
*/
6540
None = 0,
6541
/**
6542
* Insert new line and indent once (relative to the previous line's indentation).
6543
*/
6544
Indent = 1,
6545
/**
6546
* Insert two new lines:
6547
* - the first one indented which will hold the cursor
6548
* - the second one at the same indentation level
6549
*/
6550
IndentOutdent = 2,
6551
/**
6552
* Insert new line and outdent once (relative to the previous line's indentation).
6553
*/
6554
Outdent = 3
6555
}
6556
6557
/**
6558
* Describes what to do when pressing Enter.
6559
*/
6560
export interface EnterAction {
6561
/**
6562
* Describe what to do with the indentation.
6563
*/
6564
indentAction: IndentAction;
6565
/**
6566
* Describes text to be appended after the new line and after the indentation.
6567
*/
6568
appendText?: string;
6569
/**
6570
* Describes the number of characters to remove from the new line's indentation.
6571
*/
6572
removeText?: number;
6573
}
6574
6575
/**
6576
* Describes a rule to be evaluated when pressing Enter.
6577
*/
6578
export interface OnEnterRule {
6579
/**
6580
* This rule will only execute if the text before the cursor matches this regular expression.
6581
*/
6582
beforeText: RegExp;
6583
/**
6584
* This rule will only execute if the text after the cursor matches this regular expression.
6585
*/
6586
afterText?: RegExp;
6587
/**
6588
* This rule will only execute if the text above the current line matches this regular expression.
6589
*/
6590
previousLineText?: RegExp;
6591
/**
6592
* The action to execute.
6593
*/
6594
action: EnterAction;
6595
}
6596
6597
/**
6598
* Enumeration of commonly encountered syntax token types.
6599
*/
6600
export enum SyntaxTokenType {
6601
/**
6602
* Everything except tokens that are part of comments, string literals and regular expressions.
6603
*/
6604
Other = 0,
6605
/**
6606
* A comment.
6607
*/
6608
Comment = 1,
6609
/**
6610
* A string literal.
6611
*/
6612
String = 2,
6613
/**
6614
* A regular expression.
6615
*/
6616
RegEx = 3
6617
}
6618
6619
/**
6620
* Describes pairs of strings where the close string will be automatically inserted when typing the opening string.
6621
*/
6622
export interface AutoClosingPair {
6623
/**
6624
* The string that will trigger the automatic insertion of the closing string.
6625
*/
6626
open: string;
6627
/**
6628
* The closing string that will be automatically inserted when typing the opening string.
6629
*/
6630
close: string;
6631
/**
6632
* A set of tokens where the pair should not be auto closed.
6633
*/
6634
notIn?: SyntaxTokenType[];
6635
}
6636
6637
/**
6638
* The language configuration interfaces defines the contract between extensions
6639
* and various editor features, like automatic bracket insertion, automatic indentation etc.
6640
*/
6641
export interface LanguageConfiguration {
6642
/**
6643
* The language's comment settings.
6644
*/
6645
comments?: CommentRule;
6646
/**
6647
* The language's brackets.
6648
* This configuration implicitly affects pressing Enter around these brackets.
6649
*/
6650
brackets?: CharacterPair[];
6651
/**
6652
* The language's word definition.
6653
* If the language supports Unicode identifiers (e.g. JavaScript), it is preferable
6654
* to provide a word definition that uses exclusion of known separators.
6655
* e.g.: A regex that matches anything except known separators (and dot is allowed to occur in a floating point number):
6656
* ```
6657
* /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g
6658
* ```
6659
*/
6660
wordPattern?: RegExp;
6661
/**
6662
* The language's indentation settings.
6663
*/
6664
indentationRules?: IndentationRule;
6665
/**
6666
* The language's rules to be evaluated when pressing Enter.
6667
*/
6668
onEnterRules?: OnEnterRule[];
6669
/**
6670
* The language's auto closing pairs.
6671
*/
6672
autoClosingPairs?: AutoClosingPair[];
6673
6674
/**
6675
* **Deprecated** Do not use.
6676
*
6677
* @deprecated Will be replaced by a better API soon.
6678
*/
6679
__electricCharacterSupport?: {
6680
/**
6681
* This property is deprecated and will be **ignored** from
6682
* the editor.
6683
* @deprecated
6684
*/
6685
brackets?: any;
6686
/**
6687
* This property is deprecated and not fully supported anymore by
6688
* the editor (scope and lineStart are ignored).
6689
* Use the autoClosingPairs property in the language configuration file instead.
6690
* @deprecated
6691
*/
6692
docComment?: {
6693
/**
6694
* @deprecated
6695
*/
6696
scope: string;
6697
/**
6698
* @deprecated
6699
*/
6700
open: string;
6701
/**
6702
* @deprecated
6703
*/
6704
lineStart: string;
6705
/**
6706
* @deprecated
6707
*/
6708
close?: string;
6709
};
6710
};
6711
6712
/**
6713
* **Deprecated** Do not use.
6714
*
6715
* @deprecated * Use the autoClosingPairs property in the language configuration file instead.
6716
*/
6717
__characterPairSupport?: {
6718
/**
6719
* @deprecated
6720
*/
6721
autoClosingPairs: {
6722
/**
6723
* @deprecated
6724
*/
6725
open: string;
6726
/**
6727
* @deprecated
6728
*/
6729
close: string;
6730
/**
6731
* @deprecated
6732
*/
6733
notIn?: string[];
6734
}[];
6735
};
6736
}
6737
6738
/**
6739
* The configuration target
6740
*/
6741
export enum ConfigurationTarget {
6742
/**
6743
* Global configuration
6744
*/
6745
Global = 1,
6746
6747
/**
6748
* Workspace configuration
6749
*/
6750
Workspace = 2,
6751
6752
/**
6753
* Workspace folder configuration
6754
*/
6755
WorkspaceFolder = 3
6756
}
6757
6758
/**
6759
* Represents the configuration. It is a merged view of
6760
*
6761
* - *Default Settings*
6762
* - *Global (User) Settings*
6763
* - *Workspace settings*
6764
* - *Workspace Folder settings* - From one of the {@link workspace.workspaceFolders Workspace Folders} under which requested resource belongs to.
6765
* - *Language settings* - Settings defined under requested language.
6766
*
6767
* The *effective* value (returned by {@linkcode WorkspaceConfiguration.get get}) is computed by overriding or merging the values in the following order:
6768
*
6769
* 1. `defaultValue` (if defined in `package.json` otherwise derived from the value's type)
6770
* 1. `globalValue` (if defined)
6771
* 1. `workspaceValue` (if defined)
6772
* 1. `workspaceFolderValue` (if defined)
6773
* 1. `defaultLanguageValue` (if defined)
6774
* 1. `globalLanguageValue` (if defined)
6775
* 1. `workspaceLanguageValue` (if defined)
6776
* 1. `workspaceFolderLanguageValue` (if defined)
6777
*
6778
* **Note:** Only `object` value types are merged and all other value types are overridden.
6779
*
6780
* Example 1: Overriding
6781
*
6782
* ```ts
6783
* defaultValue = 'on';
6784
* globalValue = 'relative'
6785
* workspaceFolderValue = 'off'
6786
* value = 'off'
6787
* ```
6788
*
6789
* Example 2: Language Values
6790
*
6791
* ```ts
6792
* defaultValue = 'on';
6793
* globalValue = 'relative'
6794
* workspaceFolderValue = 'off'
6795
* globalLanguageValue = 'on'
6796
* value = 'on'
6797
* ```
6798
*
6799
* Example 3: Object Values
6800
*
6801
* ```ts
6802
* defaultValue = { "a": 1, "b": 2 };
6803
* globalValue = { "b": 3, "c": 4 };
6804
* value = { "a": 1, "b": 3, "c": 4 };
6805
* ```
6806
*
6807
* *Note:* Workspace and Workspace Folder configurations contains `launch` and `tasks` settings. Their basename will be
6808
* part of the section identifier. The following snippets shows how to retrieve all configurations
6809
* from `launch.json`:
6810
*
6811
* ```ts
6812
* // launch.json configuration
6813
* const config = workspace.getConfiguration('launch', vscode.workspace.workspaceFolders[0].uri);
6814
*
6815
* // retrieve values
6816
* const values = config.get('configurations');
6817
* ```
6818
*
6819
* Refer to [Settings](https://code.visualstudio.com/docs/getstarted/settings) for more information.
6820
*/
6821
export interface WorkspaceConfiguration {
6822
6823
/**
6824
* Return a value from this configuration.
6825
*
6826
* @param section Configuration name, supports _dotted_ names.
6827
* @returns The value `section` denotes or `undefined`.
6828
*/
6829
get<T>(section: string): T | undefined;
6830
6831
/**
6832
* Return a value from this configuration.
6833
*
6834
* @param section Configuration name, supports _dotted_ names.
6835
* @param defaultValue A value should be returned when no value could be found, is `undefined`.
6836
* @returns The value `section` denotes or the default.
6837
*/
6838
get<T>(section: string, defaultValue: T): T;
6839
6840
/**
6841
* Check if this configuration has a certain value.
6842
*
6843
* @param section Configuration name, supports _dotted_ names.
6844
* @returns `true` if the section doesn't resolve to `undefined`.
6845
*/
6846
has(section: string): boolean;
6847
6848
/**
6849
* Retrieve all information about a configuration setting. A configuration value
6850
* often consists of a *default* value, a global or installation-wide value,
6851
* a workspace-specific value, folder-specific value
6852
* and language-specific values (if {@link WorkspaceConfiguration} is scoped to a language).
6853
*
6854
* Also provides all language ids under which the given configuration setting is defined.
6855
*
6856
* *Note:* The configuration name must denote a leaf in the configuration tree
6857
* (`editor.fontSize` vs `editor`) otherwise no result is returned.
6858
*
6859
* @param section Configuration name, supports _dotted_ names.
6860
* @returns Information about a configuration setting or `undefined`.
6861
*/
6862
inspect<T>(section: string): {
6863
6864
/**
6865
* The fully qualified key of the configuration value
6866
*/
6867
key: string;
6868
6869
/**
6870
* The default value which is used when no other value is defined
6871
*/
6872
defaultValue?: T;
6873
6874
/**
6875
* The global or installation-wide value.
6876
*/
6877
globalValue?: T;
6878
6879
/**
6880
* The workspace-specific value.
6881
*/
6882
workspaceValue?: T;
6883
6884
/**
6885
* The workspace-folder-specific value.
6886
*/
6887
workspaceFolderValue?: T;
6888
6889
/**
6890
* Language specific default value when this configuration value is created for a {@link ConfigurationScope language scope}.
6891
*/
6892
defaultLanguageValue?: T;
6893
6894
/**
6895
* Language specific global value when this configuration value is created for a {@link ConfigurationScope language scope}.
6896
*/
6897
globalLanguageValue?: T;
6898
6899
/**
6900
* Language specific workspace value when this configuration value is created for a {@link ConfigurationScope language scope}.
6901
*/
6902
workspaceLanguageValue?: T;
6903
6904
/**
6905
* Language specific workspace-folder value when this configuration value is created for a {@link ConfigurationScope language scope}.
6906
*/
6907
workspaceFolderLanguageValue?: T;
6908
6909
/**
6910
* All language identifiers for which this configuration is defined.
6911
*/
6912
languageIds?: string[];
6913
6914
} | undefined;
6915
6916
/**
6917
* Update a configuration value. The updated configuration values are persisted.
6918
*
6919
* A value can be changed in
6920
*
6921
* - {@link ConfigurationTarget.Global Global settings}: Changes the value for all instances of the editor.
6922
* - {@link ConfigurationTarget.Workspace Workspace settings}: Changes the value for current workspace, if available.
6923
* - {@link ConfigurationTarget.WorkspaceFolder Workspace folder settings}: Changes the value for settings from one of the {@link workspace.workspaceFolders Workspace Folders} under which the requested resource belongs to.
6924
* - Language settings: Changes the value for the requested languageId.
6925
*
6926
* *Note:* To remove a configuration value use `undefined`, like so: `config.update('somekey', undefined)`
6927
*
6928
* @param section Configuration name, supports _dotted_ names.
6929
* @param value The new value.
6930
* @param configurationTarget The {@link ConfigurationTarget configuration target} or a boolean value.
6931
* - If `true` updates {@link ConfigurationTarget.Global Global settings}.
6932
* - If `false` updates {@link ConfigurationTarget.Workspace Workspace settings}.
6933
* - If `undefined` or `null` updates to {@link ConfigurationTarget.WorkspaceFolder Workspace folder settings} if configuration is resource specific,
6934
* otherwise to {@link ConfigurationTarget.Workspace Workspace settings}.
6935
* @param overrideInLanguage Whether to update the value in the scope of requested languageId or not.
6936
* - If `true` updates the value under the requested languageId.
6937
* - If `undefined` updates the value under the requested languageId only if the configuration is defined for the language.
6938
* @throws error while updating
6939
* - configuration which is not registered.
6940
* - window configuration to workspace folder
6941
* - configuration to workspace or workspace folder when no workspace is opened.
6942
* - configuration to workspace folder when there is no workspace folder settings.
6943
* - configuration to workspace folder when {@link WorkspaceConfiguration} is not scoped to a resource.
6944
*/
6945
update(section: string, value: any, configurationTarget?: ConfigurationTarget | boolean | null, overrideInLanguage?: boolean): Thenable<void>;
6946
6947
/**
6948
* Readable dictionary that backs this configuration.
6949
*/
6950
readonly [key: string]: any;
6951
}
6952
6953
/**
6954
* Represents a location inside a resource, such as a line
6955
* inside a text file.
6956
*/
6957
export class Location {
6958
6959
/**
6960
* The resource identifier of this location.
6961
*/
6962
uri: Uri;
6963
6964
/**
6965
* The document range of this location.
6966
*/
6967
range: Range;
6968
6969
/**
6970
* Creates a new location object.
6971
*
6972
* @param uri The resource identifier.
6973
* @param rangeOrPosition The range or position. Positions will be converted to an empty range.
6974
*/
6975
constructor(uri: Uri, rangeOrPosition: Range | Position);
6976
}
6977
6978
/**
6979
* Represents the connection of two locations. Provides additional metadata over normal {@link Location locations},
6980
* including an origin range.
6981
*/
6982
export interface LocationLink {
6983
/**
6984
* Span of the origin of this link.
6985
*
6986
* Used as the underlined span for mouse definition hover. Defaults to the word range at
6987
* the definition position.
6988
*/
6989
originSelectionRange?: Range;
6990
6991
/**
6992
* The target resource identifier of this link.
6993
*/
6994
targetUri: Uri;
6995
6996
/**
6997
* The full target range of this link.
6998
*/
6999
targetRange: Range;
7000
7001
/**
7002
* The span of this link.
7003
*/
7004
targetSelectionRange?: Range;
7005
}
7006
7007
/**
7008
* The event that is fired when diagnostics change.
7009
*/
7010
export interface DiagnosticChangeEvent {
7011
7012
/**
7013
* An array of resources for which diagnostics have changed.
7014
*/
7015
readonly uris: readonly Uri[];
7016
}
7017
7018
/**
7019
* Represents the severity of diagnostics.
7020
*/
7021
export enum DiagnosticSeverity {
7022
7023
/**
7024
* Something not allowed by the rules of a language or other means.
7025
*/
7026
Error = 0,
7027
7028
/**
7029
* Something suspicious but allowed.
7030
*/
7031
Warning = 1,
7032
7033
/**
7034
* Something to inform about but not a problem.
7035
*/
7036
Information = 2,
7037
7038
/**
7039
* Something to hint to a better way of doing it, like proposing
7040
* a refactoring.
7041
*/
7042
Hint = 3
7043
}
7044
7045
/**
7046
* Represents a related message and source code location for a diagnostic. This should be
7047
* used to point to code locations that cause or related to a diagnostics, e.g. when duplicating
7048
* a symbol in a scope.
7049
*/
7050
export class DiagnosticRelatedInformation {
7051
7052
/**
7053
* The location of this related diagnostic information.
7054
*/
7055
location: Location;
7056
7057
/**
7058
* The message of this related diagnostic information.
7059
*/
7060
message: string;
7061
7062
/**
7063
* Creates a new related diagnostic information object.
7064
*
7065
* @param location The location.
7066
* @param message The message.
7067
*/
7068
constructor(location: Location, message: string);
7069
}
7070
7071
/**
7072
* Additional metadata about the type of a diagnostic.
7073
*/
7074
export enum DiagnosticTag {
7075
/**
7076
* Unused or unnecessary code.
7077
*
7078
* Diagnostics with this tag are rendered faded out. The amount of fading
7079
* is controlled by the `"editorUnnecessaryCode.opacity"` theme color. For
7080
* example, `"editorUnnecessaryCode.opacity": "#000000c0"` will render the
7081
* code with 75% opacity. For high contrast themes, use the
7082
* `"editorUnnecessaryCode.border"` theme color to underline unnecessary code
7083
* instead of fading it out.
7084
*/
7085
Unnecessary = 1,
7086
7087
/**
7088
* Deprecated or obsolete code.
7089
*
7090
* Diagnostics with this tag are rendered with a strike through.
7091
*/
7092
Deprecated = 2,
7093
}
7094
7095
/**
7096
* Represents a diagnostic, such as a compiler error or warning. Diagnostic objects
7097
* are only valid in the scope of a file.
7098
*/
7099
export class Diagnostic {
7100
7101
/**
7102
* The range to which this diagnostic applies.
7103
*/
7104
range: Range;
7105
7106
/**
7107
* The human-readable message.
7108
*/
7109
message: string;
7110
7111
/**
7112
* The severity, default is {@link DiagnosticSeverity.Error error}.
7113
*/
7114
severity: DiagnosticSeverity;
7115
7116
/**
7117
* A human-readable string describing the source of this
7118
* diagnostic, e.g. 'typescript' or 'super lint'.
7119
*/
7120
source?: string;
7121
7122
/**
7123
* A code or identifier for this diagnostic.
7124
* Should be used for later processing, e.g. when providing {@link CodeActionContext code actions}.
7125
*/
7126
code?: string | number | {
7127
/**
7128
* A code or identifier for this diagnostic.
7129
* Should be used for later processing, e.g. when providing {@link CodeActionContext code actions}.
7130
*/
7131
value: string | number;
7132
7133
/**
7134
* A target URI to open with more information about the diagnostic error.
7135
*/
7136
target: Uri;
7137
};
7138
7139
/**
7140
* An array of related diagnostic information, e.g. when symbol-names within
7141
* a scope collide all definitions can be marked via this property.
7142
*/
7143
relatedInformation?: DiagnosticRelatedInformation[];
7144
7145
/**
7146
* Additional metadata about the diagnostic.
7147
*/
7148
tags?: DiagnosticTag[];
7149
7150
/**
7151
* Creates a new diagnostic object.
7152
*
7153
* @param range The range to which this diagnostic applies.
7154
* @param message The human-readable message.
7155
* @param severity The severity, default is {@link DiagnosticSeverity.Error error}.
7156
*/
7157
constructor(range: Range, message: string, severity?: DiagnosticSeverity);
7158
}
7159
7160
/**
7161
* A diagnostics collection is a container that manages a set of
7162
* {@link Diagnostic diagnostics}. Diagnostics are always scopes to a
7163
* diagnostics collection and a resource.
7164
*
7165
* To get an instance of a `DiagnosticCollection` use
7166
* {@link languages.createDiagnosticCollection createDiagnosticCollection}.
7167
*/
7168
export interface DiagnosticCollection extends Iterable<[uri: Uri, diagnostics: readonly Diagnostic[]]> {
7169
7170
/**
7171
* The name of this diagnostic collection, for instance `typescript`. Every diagnostic
7172
* from this collection will be associated with this name. Also, the task framework uses this
7173
* name when defining [problem matchers](https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher).
7174
*/
7175
readonly name: string;
7176
7177
/**
7178
* Assign diagnostics for given resource. Will replace
7179
* existing diagnostics for that resource.
7180
*
7181
* @param uri A resource identifier.
7182
* @param diagnostics Array of diagnostics or `undefined`
7183
*/
7184
set(uri: Uri, diagnostics: readonly Diagnostic[] | undefined): void;
7185
7186
/**
7187
* Replace diagnostics for multiple resources in this collection.
7188
*
7189
* _Note_ that multiple tuples of the same uri will be merged, e.g
7190
* `[[file1, [d1]], [file1, [d2]]]` is equivalent to `[[file1, [d1, d2]]]`.
7191
* If a diagnostics item is `undefined` as in `[file1, undefined]`
7192
* all previous but not subsequent diagnostics are removed.
7193
*
7194
* @param entries An array of tuples, like `[[file1, [d1, d2]], [file2, [d3, d4, d5]]]`, or `undefined`.
7195
*/
7196
set(entries: ReadonlyArray<[Uri, readonly Diagnostic[] | undefined]>): void;
7197
7198
/**
7199
* Remove all diagnostics from this collection that belong
7200
* to the provided `uri`. The same as `#set(uri, undefined)`.
7201
*
7202
* @param uri A resource identifier.
7203
*/
7204
delete(uri: Uri): void;
7205
7206
/**
7207
* Remove all diagnostics from this collection. The same
7208
* as calling `#set(undefined)`;
7209
*/
7210
clear(): void;
7211
7212
/**
7213
* Iterate over each entry in this collection.
7214
*
7215
* @param callback Function to execute for each entry.
7216
* @param thisArg The `this` context used when invoking the handler function.
7217
*/
7218
forEach(callback: (uri: Uri, diagnostics: readonly Diagnostic[], collection: DiagnosticCollection) => any, thisArg?: any): void;
7219
7220
/**
7221
* Get the diagnostics for a given resource. *Note* that you cannot
7222
* modify the diagnostics-array returned from this call.
7223
*
7224
* @param uri A resource identifier.
7225
* @returns An immutable array of {@link Diagnostic diagnostics} or `undefined`.
7226
*/
7227
get(uri: Uri): readonly Diagnostic[] | undefined;
7228
7229
/**
7230
* Check if this collection contains diagnostics for a
7231
* given resource.
7232
*
7233
* @param uri A resource identifier.
7234
* @returns `true` if this collection has diagnostic for the given resource.
7235
*/
7236
has(uri: Uri): boolean;
7237
7238
/**
7239
* Dispose and free associated resources. Calls
7240
* {@link DiagnosticCollection.clear clear}.
7241
*/
7242
dispose(): void;
7243
}
7244
7245
/**
7246
* Represents the severity of a language status item.
7247
*/
7248
/**
7249
* Represents the severity level of a language status.
7250
*/
7251
export enum LanguageStatusSeverity {
7252
/**
7253
* Informational severity level.
7254
*/
7255
Information = 0,
7256
/**
7257
* Warning severity level.
7258
*/
7259
Warning = 1,
7260
/**
7261
* Error severity level.
7262
*/
7263
Error = 2
7264
}
7265
7266
/**
7267
* A language status item is the preferred way to present language status reports for the active text editors,
7268
* such as selected linter or notifying about a configuration problem.
7269
*/
7270
export interface LanguageStatusItem {
7271
7272
/**
7273
* The identifier of this item.
7274
*/
7275
readonly id: string;
7276
7277
/**
7278
* The short name of this item, like 'Java Language Status', etc.
7279
*/
7280
name: string | undefined;
7281
7282
/**
7283
* A {@link DocumentSelector selector} that defines for what editors
7284
* this item shows.
7285
*/
7286
selector: DocumentSelector;
7287
7288
/**
7289
* The severity of this item.
7290
*
7291
* Defaults to {@link LanguageStatusSeverity.Information information}. You can use this property to
7292
* signal to users that there is a problem that needs attention, like a missing executable or an
7293
* invalid configuration.
7294
*/
7295
severity: LanguageStatusSeverity;
7296
7297
/**
7298
* The text to show for the entry. You can embed icons in the text by leveraging the syntax:
7299
*
7300
* `My text $(icon-name) contains icons like $(icon-name) this one.`
7301
*
7302
* Where the icon-name is taken from the ThemeIcon [icon set](https://code.visualstudio.com/api/references/icons-in-labels#icon-listing), e.g.
7303
* `light-bulb`, `thumbsup`, `zap` etc.
7304
*/
7305
text: string;
7306
7307
/**
7308
* Optional, human-readable details for this item.
7309
*/
7310
detail?: string;
7311
7312
/**
7313
* Controls whether the item is shown as "busy". Defaults to `false`.
7314
*/
7315
busy: boolean;
7316
7317
/**
7318
* A {@linkcode Command command} for this item.
7319
*/
7320
command: Command | undefined;
7321
7322
/**
7323
* Accessibility information used when a screen reader interacts with this item
7324
*/
7325
accessibilityInformation?: AccessibilityInformation;
7326
7327
/**
7328
* Dispose and free associated resources.
7329
*/
7330
dispose(): void;
7331
}
7332
7333
/**
7334
* Denotes a location of an editor in the window. Editors can be arranged in a grid
7335
* and each column represents one editor location in that grid by counting the editors
7336
* in order of their appearance.
7337
*/
7338
export enum ViewColumn {
7339
/**
7340
* A *symbolic* editor column representing the currently active column. This value
7341
* can be used when opening editors, but the *resolved* {@link TextEditor.viewColumn viewColumn}-value
7342
* of editors will always be `One`, `Two`, `Three`,... or `undefined` but never `Active`.
7343
*/
7344
Active = -1,
7345
/**
7346
* A *symbolic* editor column representing the column to the side of the active one. This value
7347
* can be used when opening editors, but the *resolved* {@link TextEditor.viewColumn viewColumn}-value
7348
* of editors will always be `One`, `Two`, `Three`,... or `undefined` but never `Beside`.
7349
*/
7350
Beside = -2,
7351
/**
7352
* The first editor column.
7353
*/
7354
One = 1,
7355
/**
7356
* The second editor column.
7357
*/
7358
Two = 2,
7359
/**
7360
* The third editor column.
7361
*/
7362
Three = 3,
7363
/**
7364
* The fourth editor column.
7365
*/
7366
Four = 4,
7367
/**
7368
* The fifth editor column.
7369
*/
7370
Five = 5,
7371
/**
7372
* The sixth editor column.
7373
*/
7374
Six = 6,
7375
/**
7376
* The seventh editor column.
7377
*/
7378
Seven = 7,
7379
/**
7380
* The eighth editor column.
7381
*/
7382
Eight = 8,
7383
/**
7384
* The ninth editor column.
7385
*/
7386
Nine = 9
7387
}
7388
7389
/**
7390
* An output channel is a container for readonly textual information.
7391
*
7392
* To get an instance of an `OutputChannel` use
7393
* {@link window.createOutputChannel createOutputChannel}.
7394
*/
7395
export interface OutputChannel {
7396
7397
/**
7398
* The human-readable name of this output channel.
7399
*/
7400
readonly name: string;
7401
7402
/**
7403
* Append the given value to the channel.
7404
*
7405
* @param value A string, falsy values will not be printed.
7406
*/
7407
append(value: string): void;
7408
7409
/**
7410
* Append the given value and a line feed character
7411
* to the channel.
7412
*
7413
* @param value A string, falsy values will be printed.
7414
*/
7415
appendLine(value: string): void;
7416
7417
/**
7418
* Replaces all output from the channel with the given value.
7419
*
7420
* @param value A string, falsy values will not be printed.
7421
*/
7422
replace(value: string): void;
7423
7424
/**
7425
* Removes all output from the channel.
7426
*/
7427
clear(): void;
7428
7429
/**
7430
* Reveal this channel in the UI.
7431
*
7432
* @param preserveFocus When `true` the channel will not take focus.
7433
*/
7434
show(preserveFocus?: boolean): void;
7435
7436
/**
7437
* Reveal this channel in the UI.
7438
*
7439
* @deprecated Use the overload with just one parameter (`show(preserveFocus?: boolean): void`).
7440
*
7441
* @param column This argument is **deprecated** and will be ignored.
7442
* @param preserveFocus When `true` the channel will not take focus.
7443
*/
7444
show(column?: ViewColumn, preserveFocus?: boolean): void;
7445
7446
/**
7447
* Hide this channel from the UI.
7448
*/
7449
hide(): void;
7450
7451
/**
7452
* Dispose and free associated resources.
7453
*/
7454
dispose(): void;
7455
}
7456
7457
/**
7458
* A channel for containing log output.
7459
*
7460
* To get an instance of a `LogOutputChannel` use
7461
* {@link window.createOutputChannel createOutputChannel}.
7462
*/
7463
export interface LogOutputChannel extends OutputChannel {
7464
7465
/**
7466
* The current log level of the channel. Defaults to {@link env.logLevel editor log level}.
7467
*/
7468
readonly logLevel: LogLevel;
7469
7470
/**
7471
* An {@link Event} which fires when the log level of the channel changes.
7472
*/
7473
readonly onDidChangeLogLevel: Event<LogLevel>;
7474
7475
/**
7476
* Outputs the given trace message to the channel. Use this method to log verbose information.
7477
*
7478
* The message is only logged if the channel is configured to display {@link LogLevel.Trace trace} log level.
7479
*
7480
* @param message trace message to log
7481
*/
7482
trace(message: string, ...args: any[]): void;
7483
7484
/**
7485
* Outputs the given debug message to the channel.
7486
*
7487
* The message is only logged if the channel is configured to display {@link LogLevel.Debug debug} log level or lower.
7488
*
7489
* @param message debug message to log
7490
*/
7491
debug(message: string, ...args: any[]): void;
7492
7493
/**
7494
* Outputs the given information message to the channel.
7495
*
7496
* The message is only logged if the channel is configured to display {@link LogLevel.Info info} log level or lower.
7497
*
7498
* @param message info message to log
7499
*/
7500
info(message: string, ...args: any[]): void;
7501
7502
/**
7503
* Outputs the given warning message to the channel.
7504
*
7505
* The message is only logged if the channel is configured to display {@link LogLevel.Warning warning} log level or lower.
7506
*
7507
* @param message warning message to log
7508
*/
7509
warn(message: string, ...args: any[]): void;
7510
7511
/**
7512
* Outputs the given error or error message to the channel.
7513
*
7514
* The message is only logged if the channel is configured to display {@link LogLevel.Error error} log level or lower.
7515
*
7516
* @param error Error or error message to log
7517
*/
7518
error(error: string | Error, ...args: any[]): void;
7519
}
7520
7521
/**
7522
* Accessibility information which controls screen reader behavior.
7523
*/
7524
export interface AccessibilityInformation {
7525
/**
7526
* Label to be read out by a screen reader once the item has focus.
7527
*/
7528
readonly label: string;
7529
7530
/**
7531
* Role of the widget which defines how a screen reader interacts with it.
7532
* The role should be set in special cases when for example a tree-like element behaves like a checkbox.
7533
* If role is not specified the editor will pick the appropriate role automatically.
7534
* More about aria roles can be found here https://w3c.github.io/aria/#widget_roles
7535
*/
7536
readonly role?: string;
7537
}
7538
7539
/**
7540
* Represents the alignment of status bar items.
7541
*/
7542
export enum StatusBarAlignment {
7543
7544
/**
7545
* Aligned to the left side.
7546
*/
7547
Left = 1,
7548
7549
/**
7550
* Aligned to the right side.
7551
*/
7552
Right = 2
7553
}
7554
7555
/**
7556
* A status bar item is a status bar contribution that can
7557
* show text and icons and run a command on click.
7558
*/
7559
export interface StatusBarItem {
7560
7561
/**
7562
* The identifier of this item.
7563
*
7564
* *Note*: if no identifier was provided by the {@linkcode window.createStatusBarItem}
7565
* method, the identifier will match the {@link Extension.id extension identifier}.
7566
*/
7567
readonly id: string;
7568
7569
/**
7570
* The alignment of this item.
7571
*/
7572
readonly alignment: StatusBarAlignment;
7573
7574
/**
7575
* The priority of this item. Higher value means the item should
7576
* be shown more to the left.
7577
*/
7578
readonly priority: number | undefined;
7579
7580
/**
7581
* The name of the entry, like 'Python Language Indicator', 'Git Status' etc.
7582
* Try to keep the length of the name short, yet descriptive enough that
7583
* users can understand what the status bar item is about.
7584
*/
7585
name: string | undefined;
7586
7587
/**
7588
* The text to show for the entry. You can embed icons in the text by leveraging the syntax:
7589
*
7590
* `My text $(icon-name) contains icons like $(icon-name) this one.`
7591
*
7592
* Where the icon-name is taken from the ThemeIcon [icon set](https://code.visualstudio.com/api/references/icons-in-labels#icon-listing), e.g.
7593
* `light-bulb`, `thumbsup`, `zap` etc.
7594
*/
7595
text: string;
7596
7597
/**
7598
* The tooltip text when you hover over this entry.
7599
*/
7600
tooltip: string | MarkdownString | undefined;
7601
7602
/**
7603
* The foreground color for this entry.
7604
*/
7605
color: string | ThemeColor | undefined;
7606
7607
/**
7608
* The background color for this entry.
7609
*
7610
* *Note*: only the following colors are supported:
7611
* * `new ThemeColor('statusBarItem.errorBackground')`
7612
* * `new ThemeColor('statusBarItem.warningBackground')`
7613
*
7614
* More background colors may be supported in the future.
7615
*
7616
* *Note*: when a background color is set, the statusbar may override
7617
* the `color` choice to ensure the entry is readable in all themes.
7618
*/
7619
backgroundColor: ThemeColor | undefined;
7620
7621
/**
7622
* {@linkcode Command} or identifier of a command to run on click.
7623
*
7624
* The command must be {@link commands.getCommands known}.
7625
*
7626
* Note that if this is a {@linkcode Command} object, only the {@linkcode Command.command command} and {@linkcode Command.arguments arguments}
7627
* are used by the editor.
7628
*/
7629
command: string | Command | undefined;
7630
7631
/**
7632
* Accessibility information used when a screen reader interacts with this StatusBar item
7633
*/
7634
accessibilityInformation: AccessibilityInformation | undefined;
7635
7636
/**
7637
* Shows the entry in the status bar.
7638
*/
7639
show(): void;
7640
7641
/**
7642
* Hide the entry in the status bar.
7643
*/
7644
hide(): void;
7645
7646
/**
7647
* Dispose and free associated resources. Call
7648
* {@link StatusBarItem.hide hide}.
7649
*/
7650
dispose(): void;
7651
}
7652
7653
/**
7654
* Defines a generalized way of reporting progress updates.
7655
*/
7656
export interface Progress<T> {
7657
7658
/**
7659
* Report a progress update.
7660
* @param value A progress item, like a message and/or an
7661
* report on how much work finished
7662
*/
7663
report(value: T): void;
7664
}
7665
7666
/**
7667
* An individual terminal instance within the integrated terminal.
7668
*/
7669
export interface Terminal {
7670
7671
/**
7672
* The name of the terminal.
7673
*/
7674
readonly name: string;
7675
7676
/**
7677
* The process ID of the shell process.
7678
*/
7679
readonly processId: Thenable<number | undefined>;
7680
7681
/**
7682
* The object used to initialize the terminal, this is useful for example to detecting the
7683
* shell type of when the terminal was not launched by this extension or for detecting what
7684
* folder the shell was launched in.
7685
*/
7686
readonly creationOptions: Readonly<TerminalOptions | ExtensionTerminalOptions>;
7687
7688
/**
7689
* The exit status of the terminal, this will be undefined while the terminal is active.
7690
*
7691
* **Example:** Show a notification with the exit code when the terminal exits with a
7692
* non-zero exit code.
7693
* ```typescript
7694
* window.onDidCloseTerminal(t => {
7695
* if (t.exitStatus && t.exitStatus.code) {
7696
* vscode.window.showInformationMessage(`Exit code: ${t.exitStatus.code}`);
7697
* }
7698
* });
7699
* ```
7700
*/
7701
readonly exitStatus: TerminalExitStatus | undefined;
7702
7703
/**
7704
* The current state of the {@link Terminal}.
7705
*/
7706
readonly state: TerminalState;
7707
7708
/**
7709
* An object that contains [shell integration](https://code.visualstudio.com/docs/terminal/shell-integration)-powered
7710
* features for the terminal. This will always be `undefined` immediately after the terminal
7711
* is created. Listen to {@link window.onDidChangeTerminalShellIntegration} to be notified
7712
* when shell integration is activated for a terminal.
7713
*
7714
* Note that this object may remain undefined if shell integration never activates. For
7715
* example Command Prompt does not support shell integration and a user's shell setup could
7716
* conflict with the automatic shell integration activation.
7717
*/
7718
readonly shellIntegration: TerminalShellIntegration | undefined;
7719
7720
/**
7721
* Send text to the terminal. The text is written to the stdin of the underlying pty process
7722
* (shell) of the terminal.
7723
*
7724
* @param text The text to send.
7725
* @param shouldExecute Indicates that the text being sent should be executed rather than just inserted in the terminal.
7726
* The character(s) added are `\n` or `\r\n`, depending on the platform. This defaults to `true`.
7727
*/
7728
sendText(text: string, shouldExecute?: boolean): void;
7729
7730
/**
7731
* Show the terminal panel and reveal this terminal in the UI.
7732
*
7733
* @param preserveFocus When `true` the terminal will not take focus.
7734
*/
7735
show(preserveFocus?: boolean): void;
7736
7737
/**
7738
* Hide the terminal panel if this terminal is currently showing.
7739
*/
7740
hide(): void;
7741
7742
/**
7743
* Dispose and free associated resources.
7744
*/
7745
dispose(): void;
7746
}
7747
7748
/**
7749
* The location of the terminal.
7750
*/
7751
export enum TerminalLocation {
7752
/**
7753
* In the terminal view
7754
*/
7755
Panel = 1,
7756
/**
7757
* In the editor area
7758
*/
7759
Editor = 2,
7760
}
7761
7762
/**
7763
* Assumes a {@link TerminalLocation} of editor and allows specifying a {@link ViewColumn} and
7764
* {@link TerminalEditorLocationOptions.preserveFocus preserveFocus } property
7765
*/
7766
export interface TerminalEditorLocationOptions {
7767
/**
7768
* A view column in which the {@link Terminal terminal} should be shown in the editor area.
7769
* The default is the {@link ViewColumn.Active active}. Columns that do not exist
7770
* will be created as needed up to the maximum of {@linkcode ViewColumn.Nine}.
7771
* Use {@linkcode ViewColumn.Beside} to open the editor to the side of the currently
7772
* active one.
7773
*/
7774
viewColumn: ViewColumn;
7775
/**
7776
* An optional flag that when `true` will stop the {@link Terminal} from taking focus.
7777
*/
7778
preserveFocus?: boolean;
7779
}
7780
7781
/**
7782
* Uses the parent {@link Terminal}'s location for the terminal
7783
*/
7784
export interface TerminalSplitLocationOptions {
7785
/**
7786
* The parent terminal to split this terminal beside. This works whether the parent terminal
7787
* is in the panel or the editor area.
7788
*/
7789
parentTerminal: Terminal;
7790
}
7791
7792
/**
7793
* Represents the state of a {@link Terminal}.
7794
*/
7795
export interface TerminalState {
7796
/**
7797
* Whether the {@link Terminal} has been interacted with. Interaction means that the
7798
* terminal has sent data to the process which depending on the terminal's _mode_. By
7799
* default input is sent when a key is pressed or when a command or extension sends text,
7800
* but based on the terminal's mode it can also happen on:
7801
*
7802
* - a pointer click event
7803
* - a pointer scroll event
7804
* - a pointer move event
7805
* - terminal focus in/out
7806
*
7807
* For more information on events that can send data see "DEC Private Mode Set (DECSET)" on
7808
* https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
7809
*/
7810
readonly isInteractedWith: boolean;
7811
7812
/**
7813
* The detected shell type of the {@link Terminal}. This will be `undefined` when there is
7814
* not a clear signal as to what the shell is, or the shell is not supported yet. This
7815
* value should change to the shell type of a sub-shell when launched (for example, running
7816
* `bash` inside `zsh`).
7817
*
7818
* Note that the possible values are currently defined as any of the following:
7819
* 'bash', 'cmd', 'csh', 'fish', 'gitbash', 'julia', 'ksh', 'node', 'nu', 'pwsh', 'python',
7820
* 'sh', 'wsl', 'xonsh', 'zsh'.
7821
*/
7822
readonly shell: string | undefined;
7823
}
7824
7825
/**
7826
* [Shell integration](https://code.visualstudio.com/docs/terminal/shell-integration)-powered capabilities owned by a terminal.
7827
*/
7828
export interface TerminalShellIntegration {
7829
/**
7830
* The current working directory of the terminal. This {@link Uri} may represent a file on
7831
* another machine (eg. ssh into another machine). This requires the shell integration to
7832
* support working directory reporting.
7833
*/
7834
readonly cwd: Uri | undefined;
7835
7836
/**
7837
* Execute a command, sending ^C as necessary to interrupt any running command if needed.
7838
*
7839
* @param commandLine The command line to execute, this is the exact text that will be sent
7840
* to the terminal.
7841
*
7842
* @throws When run on a terminal doesn't support this API, such as task terminals.
7843
*
7844
* @example
7845
* // Execute a command in a terminal immediately after being created
7846
* const myTerm = window.createTerminal();
7847
* window.onDidChangeTerminalShellIntegration(async ({ terminal, shellIntegration }) => {
7848
* if (terminal === myTerm) {
7849
* const execution = shellIntegration.executeCommand('echo "Hello world"');
7850
* window.onDidEndTerminalShellExecution(event => {
7851
* if (event.execution === execution) {
7852
* console.log(`Command exited with code ${event.exitCode}`);
7853
* }
7854
* });
7855
* }
7856
* }));
7857
* // Fallback to sendText if there is no shell integration within 3 seconds of launching
7858
* setTimeout(() => {
7859
* if (!myTerm.shellIntegration) {
7860
* myTerm.sendText('echo "Hello world"');
7861
* // Without shell integration, we can't know when the command has finished or what the
7862
* // exit code was.
7863
* }
7864
* }, 3000);
7865
*
7866
* @example
7867
* // Send command to terminal that has been alive for a while
7868
* const commandLine = 'echo "Hello world"';
7869
* if (term.shellIntegration) {
7870
* const execution = shellIntegration.executeCommand({ commandLine });
7871
* window.onDidEndTerminalShellExecution(event => {
7872
* if (event.execution === execution) {
7873
* console.log(`Command exited with code ${event.exitCode}`);
7874
* }
7875
* });
7876
* } else {
7877
* term.sendText(commandLine);
7878
* // Without shell integration, we can't know when the command has finished or what the
7879
* // exit code was.
7880
* }
7881
*/
7882
executeCommand(commandLine: string): TerminalShellExecution;
7883
7884
/**
7885
* Execute a command, sending ^C as necessary to interrupt any running command if needed.
7886
*
7887
* *Note* This is not guaranteed to work as [shell integration](https://code.visualstudio.com/docs/terminal/shell-integration)
7888
* must be activated. Check whether {@link TerminalShellExecution.exitCode} is rejected to
7889
* verify whether it was successful.
7890
*
7891
* @param executable A command to run.
7892
* @param args Arguments to launch the executable with. The arguments will be escaped such
7893
* that they are interpreted as single arguments when the argument both contains whitespace
7894
* and does not include any single quote, double quote or backtick characters.
7895
*
7896
* Note that this escaping is not intended to be a security measure, be careful when passing
7897
* untrusted data to this API as strings like `$(...)` can often be used in shells to
7898
* execute code within a string.
7899
*
7900
* @example
7901
* // Execute a command in a terminal immediately after being created
7902
* const myTerm = window.createTerminal();
7903
* window.onDidChangeTerminalShellIntegration(async ({ terminal, shellIntegration }) => {
7904
* if (terminal === myTerm) {
7905
* const command = shellIntegration.executeCommand({
7906
* command: 'echo',
7907
* args: ['Hello world']
7908
* });
7909
* const code = await command.exitCode;
7910
* console.log(`Command exited with code ${code}`);
7911
* }
7912
* }));
7913
* // Fallback to sendText if there is no shell integration within 3 seconds of launching
7914
* setTimeout(() => {
7915
* if (!myTerm.shellIntegration) {
7916
* myTerm.sendText('echo "Hello world"');
7917
* // Without shell integration, we can't know when the command has finished or what the
7918
* // exit code was.
7919
* }
7920
* }, 3000);
7921
*
7922
* @example
7923
* // Send command to terminal that has been alive for a while
7924
* const commandLine = 'echo "Hello world"';
7925
* if (term.shellIntegration) {
7926
* const command = term.shellIntegration.executeCommand({
7927
* command: 'echo',
7928
* args: ['Hello world']
7929
* });
7930
* const code = await command.exitCode;
7931
* console.log(`Command exited with code ${code}`);
7932
* } else {
7933
* term.sendText(commandLine);
7934
* // Without shell integration, we can't know when the command has finished or what the
7935
* // exit code was.
7936
* }
7937
*/
7938
executeCommand(executable: string, args: string[]): TerminalShellExecution;
7939
}
7940
7941
/**
7942
* A command that was executed in a terminal.
7943
*/
7944
export interface TerminalShellExecution {
7945
/**
7946
* The command line that was executed. The {@link TerminalShellExecutionCommandLineConfidence confidence}
7947
* of this value depends on the specific shell's shell integration implementation. This
7948
* value may become more accurate after {@link window.onDidEndTerminalShellExecution} is
7949
* fired.
7950
*
7951
* @example
7952
* // Log the details of the command line on start and end
7953
* window.onDidStartTerminalShellExecution(event => {
7954
* const commandLine = event.execution.commandLine;
7955
* console.log(`Command started\n${summarizeCommandLine(commandLine)}`);
7956
* });
7957
* window.onDidEndTerminalShellExecution(event => {
7958
* const commandLine = event.execution.commandLine;
7959
* console.log(`Command ended\n${summarizeCommandLine(commandLine)}`);
7960
* });
7961
* function summarizeCommandLine(commandLine: TerminalShellExecutionCommandLine) {
7962
* return [
7963
* ` Command line: ${command.commandLine.value}`,
7964
* ` Confidence: ${command.commandLine.confidence}`,
7965
* ` Trusted: ${command.commandLine.isTrusted}
7966
* ].join('\n');
7967
* }
7968
*/
7969
readonly commandLine: TerminalShellExecutionCommandLine;
7970
7971
/**
7972
* The working directory that was reported by the shell when this command executed. This
7973
* {@link Uri} may represent a file on another machine (eg. ssh into another machine). This
7974
* requires the shell integration to support working directory reporting.
7975
*/
7976
readonly cwd: Uri | undefined;
7977
7978
/**
7979
* Creates a stream of raw data (including escape sequences) that is written to the
7980
* terminal. This will only include data that was written after `read` was called for
7981
* the first time, ie. you must call `read` immediately after the command is executed via
7982
* {@link TerminalShellIntegration.executeCommand} or
7983
* {@link window.onDidStartTerminalShellExecution} to not miss any data.
7984
*
7985
* @example
7986
* // Log all data written to the terminal for a command
7987
* const command = term.shellIntegration.executeCommand({ commandLine: 'echo "Hello world"' });
7988
* const stream = command.read();
7989
* for await (const data of stream) {
7990
* console.log(data);
7991
* }
7992
*/
7993
read(): AsyncIterable<string>;
7994
}
7995
7996
/**
7997
* A command line that was executed in a terminal.
7998
*/
7999
export interface TerminalShellExecutionCommandLine {
8000
/**
8001
* The full command line that was executed, including both the command and its arguments.
8002
*/
8003
readonly value: string;
8004
8005
/**
8006
* Whether the command line value came from a trusted source and is therefore safe to
8007
* execute without user additional confirmation, such as a notification that asks "Do you
8008
* want to execute (command)?". This verification is likely only needed if you are going to
8009
* execute the command again.
8010
*
8011
* This is `true` only when the command line was reported explicitly by the shell
8012
* integration script (ie. {@link TerminalShellExecutionCommandLineConfidence.High high confidence})
8013
* and it used a nonce for verification.
8014
*/
8015
readonly isTrusted: boolean;
8016
8017
/**
8018
* The confidence of the command line value which is determined by how the value was
8019
* obtained. This depends upon the implementation of the shell integration script.
8020
*/
8021
readonly confidence: TerminalShellExecutionCommandLineConfidence;
8022
}
8023
8024
/**
8025
* The confidence of a {@link TerminalShellExecutionCommandLine} value.
8026
*/
8027
export enum TerminalShellExecutionCommandLineConfidence {
8028
/**
8029
* The command line value confidence is low. This means that the value was read from the
8030
* terminal buffer using markers reported by the shell integration script. Additionally one
8031
* of the following conditions will be met:
8032
*
8033
* - The command started on the very left-most column which is unusual, or
8034
* - The command is multi-line which is more difficult to accurately detect due to line
8035
* continuation characters and right prompts.
8036
* - Command line markers were not reported by the shell integration script.
8037
*/
8038
Low = 0,
8039
8040
/**
8041
* The command line value confidence is medium. This means that the value was read from the
8042
* terminal buffer using markers reported by the shell integration script. The command is
8043
* single-line and does not start on the very left-most column (which is unusual).
8044
*/
8045
Medium = 1,
8046
8047
/**
8048
* The command line value confidence is high. This means that the value was explicitly sent
8049
* from the shell integration script or the command was executed via the
8050
* {@link TerminalShellIntegration.executeCommand} API.
8051
*/
8052
High = 2
8053
}
8054
8055
/**
8056
* An event signalling that a terminal's shell integration has changed.
8057
*/
8058
export interface TerminalShellIntegrationChangeEvent {
8059
/**
8060
* The terminal that shell integration has been activated in.
8061
*/
8062
readonly terminal: Terminal;
8063
8064
/**
8065
* The shell integration object.
8066
*/
8067
readonly shellIntegration: TerminalShellIntegration;
8068
}
8069
8070
/**
8071
* An event signalling that an execution has started in a terminal.
8072
*/
8073
export interface TerminalShellExecutionStartEvent {
8074
/**
8075
* The terminal that shell integration has been activated in.
8076
*/
8077
readonly terminal: Terminal;
8078
8079
/**
8080
* The shell integration object.
8081
*/
8082
readonly shellIntegration: TerminalShellIntegration;
8083
8084
/**
8085
* The terminal shell execution that has ended.
8086
*/
8087
readonly execution: TerminalShellExecution;
8088
}
8089
8090
/**
8091
* An event signalling that an execution has ended in a terminal.
8092
*/
8093
export interface TerminalShellExecutionEndEvent {
8094
/**
8095
* The terminal that shell integration has been activated in.
8096
*/
8097
readonly terminal: Terminal;
8098
8099
/**
8100
* The shell integration object.
8101
*/
8102
readonly shellIntegration: TerminalShellIntegration;
8103
8104
/**
8105
* The terminal shell execution that has ended.
8106
*/
8107
readonly execution: TerminalShellExecution;
8108
8109
/**
8110
* The exit code reported by the shell.
8111
*
8112
* When this is `undefined` it can mean several things:
8113
*
8114
* - The shell either did not report an exit code (ie. the shell integration script is
8115
* misbehaving)
8116
* - The shell reported a command started before the command finished (eg. a sub-shell was
8117
* opened).
8118
* - The user canceled the command via ctrl+c.
8119
* - The user pressed enter when there was no input.
8120
*
8121
* Generally this should not happen. Depending on the use case, it may be best to treat this
8122
* as a failure.
8123
*
8124
* @example
8125
* const execution = shellIntegration.executeCommand({
8126
* command: 'echo',
8127
* args: ['Hello world']
8128
* });
8129
* window.onDidEndTerminalShellExecution(event => {
8130
* if (event.execution === execution) {
8131
* if (event.exitCode === undefined) {
8132
* console.log('Command finished but exit code is unknown');
8133
* } else if (event.exitCode === 0) {
8134
* console.log('Command succeeded');
8135
* } else {
8136
* console.log('Command failed');
8137
* }
8138
* }
8139
* });
8140
*/
8141
readonly exitCode: number | undefined;
8142
}
8143
8144
/**
8145
* Provides information on a line in a terminal in order to provide links for it.
8146
*/
8147
export interface TerminalLinkContext {
8148
/**
8149
* This is the text from the unwrapped line in the terminal.
8150
*/
8151
line: string;
8152
8153
/**
8154
* The terminal the link belongs to.
8155
*/
8156
terminal: Terminal;
8157
}
8158
8159
/**
8160
* A provider that enables detection and handling of links within terminals.
8161
*/
8162
export interface TerminalLinkProvider<T extends TerminalLink = TerminalLink> {
8163
/**
8164
* Provide terminal links for the given context. Note that this can be called multiple times
8165
* even before previous calls resolve, make sure to not share global objects (eg. `RegExp`)
8166
* that could have problems when asynchronous usage may overlap.
8167
* @param context Information about what links are being provided for.
8168
* @param token A cancellation token.
8169
* @returns A list of terminal links for the given line.
8170
*/
8171
provideTerminalLinks(context: TerminalLinkContext, token: CancellationToken): ProviderResult<T[]>;
8172
8173
/**
8174
* Handle an activated terminal link.
8175
* @param link The link to handle.
8176
*/
8177
handleTerminalLink(link: T): ProviderResult<void>;
8178
}
8179
8180
/**
8181
* A link on a terminal line.
8182
*/
8183
export class TerminalLink {
8184
/**
8185
* The start index of the link on {@link TerminalLinkContext.line}.
8186
*/
8187
startIndex: number;
8188
8189
/**
8190
* The length of the link on {@link TerminalLinkContext.line}.
8191
*/
8192
length: number;
8193
8194
/**
8195
* The tooltip text when you hover over this link.
8196
*
8197
* If a tooltip is provided, is will be displayed in a string that includes instructions on
8198
* how to trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary
8199
* depending on OS, user settings, and localization.
8200
*/
8201
tooltip?: string;
8202
8203
/**
8204
* Creates a new terminal link.
8205
* @param startIndex The start index of the link on {@link TerminalLinkContext.line}.
8206
* @param length The length of the link on {@link TerminalLinkContext.line}.
8207
* @param tooltip The tooltip text when you hover over this link.
8208
*
8209
* If a tooltip is provided, is will be displayed in a string that includes instructions on
8210
* how to trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary
8211
* depending on OS, user settings, and localization.
8212
*/
8213
constructor(startIndex: number, length: number, tooltip?: string);
8214
}
8215
8216
/**
8217
* Provides a terminal profile for the contributed terminal profile when launched via the UI or
8218
* command.
8219
*/
8220
export interface TerminalProfileProvider {
8221
/**
8222
* Provide the terminal profile.
8223
* @param token A cancellation token that indicates the result is no longer needed.
8224
* @returns The terminal profile.
8225
*/
8226
provideTerminalProfile(token: CancellationToken): ProviderResult<TerminalProfile>;
8227
}
8228
8229
/**
8230
* A terminal profile defines how a terminal will be launched.
8231
*/
8232
export class TerminalProfile {
8233
/**
8234
* The options that the terminal will launch with.
8235
*/
8236
options: TerminalOptions | ExtensionTerminalOptions;
8237
8238
/**
8239
* Creates a new terminal profile.
8240
* @param options The options that the terminal will launch with.
8241
*/
8242
constructor(options: TerminalOptions | ExtensionTerminalOptions);
8243
}
8244
8245
/**
8246
* A file decoration represents metadata that can be rendered with a file.
8247
*/
8248
export class FileDecoration {
8249
8250
/**
8251
* A very short string that represents this decoration.
8252
*/
8253
badge?: string;
8254
8255
/**
8256
* A human-readable tooltip for this decoration.
8257
*/
8258
tooltip?: string;
8259
8260
/**
8261
* The color of this decoration.
8262
*/
8263
color?: ThemeColor;
8264
8265
/**
8266
* A flag expressing that this decoration should be
8267
* propagated to its parents.
8268
*/
8269
propagate?: boolean;
8270
8271
/**
8272
* Creates a new decoration.
8273
*
8274
* @param badge A letter that represents the decoration.
8275
* @param tooltip The tooltip of the decoration.
8276
* @param color The color of the decoration.
8277
*/
8278
constructor(badge?: string, tooltip?: string, color?: ThemeColor);
8279
}
8280
8281
/**
8282
* The decoration provider interfaces defines the contract between extensions and
8283
* file decorations.
8284
*/
8285
export interface FileDecorationProvider {
8286
8287
/**
8288
* An optional event to signal that decorations for one or many files have changed.
8289
*
8290
* *Note* that this event should be used to propagate information about children.
8291
*
8292
* @see {@link EventEmitter}
8293
*/
8294
onDidChangeFileDecorations?: Event<undefined | Uri | Uri[]>;
8295
8296
/**
8297
* Provide decorations for a given uri.
8298
*
8299
* *Note* that this function is only called when a file gets rendered in the UI.
8300
* This means a decoration from a descendent that propagates upwards must be signaled
8301
* to the editor via the {@link FileDecorationProvider.onDidChangeFileDecorations onDidChangeFileDecorations}-event.
8302
*
8303
* @param uri The uri of the file to provide a decoration for.
8304
* @param token A cancellation token.
8305
* @returns A decoration or a thenable that resolves to such.
8306
*/
8307
provideFileDecoration(uri: Uri, token: CancellationToken): ProviderResult<FileDecoration>;
8308
}
8309
8310
8311
/**
8312
* In a remote window the extension kind describes if an extension
8313
* runs where the UI (window) runs or if an extension runs remotely.
8314
*/
8315
export enum ExtensionKind {
8316
8317
/**
8318
* Extension runs where the UI runs.
8319
*/
8320
UI = 1,
8321
8322
/**
8323
* Extension runs where the remote extension host runs.
8324
*/
8325
Workspace = 2
8326
}
8327
8328
/**
8329
* Represents an extension.
8330
*
8331
* To get an instance of an `Extension` use {@link extensions.getExtension getExtension}.
8332
*/
8333
export interface Extension<T> {
8334
8335
/**
8336
* The canonical extension identifier in the form of: `publisher.name`.
8337
*/
8338
readonly id: string;
8339
8340
/**
8341
* The uri of the directory containing the extension.
8342
*/
8343
readonly extensionUri: Uri;
8344
8345
/**
8346
* The absolute file path of the directory containing this extension. Shorthand
8347
* notation for {@link Extension.extensionUri Extension.extensionUri.fsPath} (independent of the uri scheme).
8348
*/
8349
readonly extensionPath: string;
8350
8351
/**
8352
* `true` if the extension has been activated.
8353
*/
8354
readonly isActive: boolean;
8355
8356
/**
8357
* The parsed contents of the extension's package.json.
8358
*/
8359
readonly packageJSON: any;
8360
8361
/**
8362
* The extension kind describes if an extension runs where the UI runs
8363
* or if an extension runs where the remote extension host runs. The extension kind
8364
* is defined in the `package.json`-file of extensions but can also be refined
8365
* via the `remote.extensionKind`-setting. When no remote extension host exists,
8366
* the value is {@linkcode ExtensionKind.UI}.
8367
*/
8368
extensionKind: ExtensionKind;
8369
8370
/**
8371
* The public API exported by this extension (return value of `activate`).
8372
* It is an invalid action to access this field before this extension has been activated.
8373
*/
8374
readonly exports: T;
8375
8376
/**
8377
* Activates this extension and returns its public API.
8378
*
8379
* @returns A promise that will resolve when this extension has been activated.
8380
*/
8381
activate(): Thenable<T>;
8382
}
8383
8384
/**
8385
* The ExtensionMode is provided on the `ExtensionContext` and indicates the
8386
* mode the specific extension is running in.
8387
*/
8388
export enum ExtensionMode {
8389
/**
8390
* The extension is installed normally (for example, from the marketplace
8391
* or VSIX) in the editor.
8392
*/
8393
Production = 1,
8394
8395
/**
8396
* The extension is running from an `--extensionDevelopmentPath` provided
8397
* when launching the editor.
8398
*/
8399
Development = 2,
8400
8401
/**
8402
* The extension is running from an `--extensionTestsPath` and
8403
* the extension host is running unit tests.
8404
*/
8405
Test = 3,
8406
}
8407
8408
/**
8409
* An extension context is a collection of utilities private to an
8410
* extension.
8411
*
8412
* An instance of an `ExtensionContext` is provided as the first
8413
* parameter to the `activate`-call of an extension.
8414
*/
8415
export interface ExtensionContext {
8416
8417
/**
8418
* An array to which disposables can be added. When this
8419
* extension is deactivated the disposables will be disposed.
8420
*
8421
* *Note* that asynchronous dispose-functions aren't awaited.
8422
*/
8423
readonly subscriptions: {
8424
/**
8425
* Function to clean up resources.
8426
*/
8427
dispose(): any;
8428
}[];
8429
8430
/**
8431
* A memento object that stores state in the context
8432
* of the currently opened {@link workspace.workspaceFolders workspace}.
8433
*/
8434
readonly workspaceState: Memento;
8435
8436
/**
8437
* A memento object that stores state independent
8438
* of the current opened {@link workspace.workspaceFolders workspace}.
8439
*/
8440
readonly globalState: Memento & {
8441
/**
8442
* Set the keys whose values should be synchronized across devices when synchronizing user-data
8443
* like configuration, extensions, and mementos.
8444
*
8445
* Note that this function defines the whole set of keys whose values are synchronized:
8446
* - calling it with an empty array stops synchronization for this memento
8447
* - calling it with a non-empty array replaces all keys whose values are synchronized
8448
*
8449
* For any given set of keys this function needs to be called only once but there is no harm in
8450
* repeatedly calling it.
8451
*
8452
* @param keys The set of keys whose values are synced.
8453
*/
8454
setKeysForSync(keys: readonly string[]): void;
8455
};
8456
8457
/**
8458
* A secret storage object that stores state independent
8459
* of the current opened {@link workspace.workspaceFolders workspace}.
8460
*/
8461
readonly secrets: SecretStorage;
8462
8463
/**
8464
* The uri of the directory containing the extension.
8465
*/
8466
readonly extensionUri: Uri;
8467
8468
/**
8469
* The absolute file path of the directory containing the extension. Shorthand
8470
* notation for {@link TextDocument.uri ExtensionContext.extensionUri.fsPath} (independent of the uri scheme).
8471
*/
8472
readonly extensionPath: string;
8473
8474
/**
8475
* Gets the extension's global environment variable collection for this workspace, enabling changes to be
8476
* applied to terminal environment variables.
8477
*/
8478
readonly environmentVariableCollection: GlobalEnvironmentVariableCollection;
8479
8480
/**
8481
* Get the absolute path of a resource contained in the extension.
8482
*
8483
* *Note* that an absolute uri can be constructed via {@linkcode Uri.joinPath} and
8484
* {@linkcode ExtensionContext.extensionUri extensionUri}, e.g. `vscode.Uri.joinPath(context.extensionUri, relativePath);`
8485
*
8486
* @param relativePath A relative path to a resource contained in the extension.
8487
* @returns The absolute path of the resource.
8488
*/
8489
asAbsolutePath(relativePath: string): string;
8490
8491
/**
8492
* The uri of a workspace specific directory in which the extension
8493
* can store private state. The directory might not exist and creation is
8494
* up to the extension. However, the parent directory is guaranteed to be existent.
8495
* The value is `undefined` when no workspace nor folder has been opened.
8496
*
8497
* Use {@linkcode ExtensionContext.workspaceState workspaceState} or
8498
* {@linkcode ExtensionContext.globalState globalState} to store key value data.
8499
*
8500
* @see {@linkcode FileSystem workspace.fs} for how to read and write files and folders from
8501
* a uri.
8502
*/
8503
readonly storageUri: Uri | undefined;
8504
8505
/**
8506
* An absolute file path of a workspace specific directory in which the extension
8507
* can store private state. The directory might not exist on disk and creation is
8508
* up to the extension. However, the parent directory is guaranteed to be existent.
8509
*
8510
* Use {@linkcode ExtensionContext.workspaceState workspaceState} or
8511
* {@linkcode ExtensionContext.globalState globalState} to store key value data.
8512
*
8513
* @deprecated Use {@link ExtensionContext.storageUri storageUri} instead.
8514
*/
8515
readonly storagePath: string | undefined;
8516
8517
/**
8518
* The uri of a directory in which the extension can store global state.
8519
* The directory might not exist on disk and creation is
8520
* up to the extension. However, the parent directory is guaranteed to be existent.
8521
*
8522
* Use {@linkcode ExtensionContext.globalState globalState} to store key value data.
8523
*
8524
* @see {@linkcode FileSystem workspace.fs} for how to read and write files and folders from
8525
* an uri.
8526
*/
8527
readonly globalStorageUri: Uri;
8528
8529
/**
8530
* An absolute file path in which the extension can store global state.
8531
* The directory might not exist on disk and creation is
8532
* up to the extension. However, the parent directory is guaranteed to be existent.
8533
*
8534
* Use {@linkcode ExtensionContext.globalState globalState} to store key value data.
8535
*
8536
* @deprecated Use {@link ExtensionContext.globalStorageUri globalStorageUri} instead.
8537
*/
8538
readonly globalStoragePath: string;
8539
8540
/**
8541
* The uri of a directory in which the extension can create log files.
8542
* The directory might not exist on disk and creation is up to the extension. However,
8543
* the parent directory is guaranteed to be existent.
8544
*
8545
* @see {@linkcode FileSystem workspace.fs} for how to read and write files and folders from
8546
* an uri.
8547
*/
8548
readonly logUri: Uri;
8549
8550
/**
8551
* An absolute file path of a directory in which the extension can create log files.
8552
* The directory might not exist on disk and creation is up to the extension. However,
8553
* the parent directory is guaranteed to be existent.
8554
*
8555
* @deprecated Use {@link ExtensionContext.logUri logUri} instead.
8556
*/
8557
readonly logPath: string;
8558
8559
/**
8560
* The mode the extension is running in. See {@link ExtensionMode}
8561
* for possible values and scenarios.
8562
*/
8563
readonly extensionMode: ExtensionMode;
8564
8565
/**
8566
* The current `Extension` instance.
8567
*/
8568
readonly extension: Extension<any>;
8569
8570
/**
8571
* An object that keeps information about how this extension can use language models.
8572
*
8573
* @see {@link LanguageModelChat.sendRequest}
8574
*/
8575
readonly languageModelAccessInformation: LanguageModelAccessInformation;
8576
}
8577
8578
/**
8579
* A memento represents a storage utility. It can store and retrieve
8580
* values.
8581
*/
8582
export interface Memento {
8583
8584
/**
8585
* Returns the stored keys.
8586
*
8587
* @returns The stored keys.
8588
*/
8589
keys(): readonly string[];
8590
8591
/**
8592
* Return a value.
8593
*
8594
* @param key A string.
8595
* @returns The stored value or `undefined`.
8596
*/
8597
get<T>(key: string): T | undefined;
8598
8599
/**
8600
* Return a value.
8601
*
8602
* @param key A string.
8603
* @param defaultValue A value that should be returned when there is no
8604
* value (`undefined`) with the given key.
8605
* @returns The stored value or the defaultValue.
8606
*/
8607
get<T>(key: string, defaultValue: T): T;
8608
8609
/**
8610
* Store a value. The value must be JSON-stringifyable.
8611
*
8612
* *Note* that using `undefined` as value removes the key from the underlying
8613
* storage.
8614
*
8615
* @param key A string.
8616
* @param value A value. MUST not contain cyclic references.
8617
*/
8618
update(key: string, value: any): Thenable<void>;
8619
}
8620
8621
/**
8622
* The event data that is fired when a secret is added or removed.
8623
*/
8624
export interface SecretStorageChangeEvent {
8625
/**
8626
* The key of the secret that has changed.
8627
*/
8628
readonly key: string;
8629
}
8630
8631
/**
8632
* Represents a storage utility for secrets (or any information that is sensitive)
8633
* that will be stored encrypted. The implementation of the secret storage will
8634
* be different on each platform and the secrets will not be synced across
8635
* machines.
8636
*/
8637
export interface SecretStorage {
8638
/**
8639
* Retrieve the keys of all the secrets stored by this extension.
8640
*/
8641
keys(): Thenable<string[]>;
8642
8643
/**
8644
* Retrieve a secret that was stored with key. Returns undefined if there
8645
* is no password matching that key.
8646
* @param key The key the secret was stored under.
8647
* @returns The stored value or `undefined`.
8648
*/
8649
get(key: string): Thenable<string | undefined>;
8650
8651
/**
8652
* Store a secret under a given key.
8653
* @param key The key to store the secret under.
8654
* @param value The secret.
8655
*/
8656
store(key: string, value: string): Thenable<void>;
8657
8658
/**
8659
* Remove a secret from storage.
8660
* @param key The key the secret was stored under.
8661
*/
8662
delete(key: string): Thenable<void>;
8663
8664
/**
8665
* Fires when a secret is stored or deleted.
8666
*/
8667
readonly onDidChange: Event<SecretStorageChangeEvent>;
8668
}
8669
8670
/**
8671
* Represents a color theme kind.
8672
*/
8673
export enum ColorThemeKind {
8674
/**
8675
* A light color theme.
8676
*/
8677
Light = 1,
8678
/**
8679
* A dark color theme.
8680
*/
8681
Dark = 2,
8682
/**
8683
* A dark high contrast color theme.
8684
*/
8685
HighContrast = 3,
8686
/**
8687
* A light high contrast color theme.
8688
*/
8689
HighContrastLight = 4
8690
}
8691
8692
/**
8693
* Represents a color theme.
8694
*/
8695
export interface ColorTheme {
8696
8697
/**
8698
* The kind of this color theme: light, dark, high contrast dark and high contrast light.
8699
*/
8700
readonly kind: ColorThemeKind;
8701
}
8702
8703
/**
8704
* Controls the behaviour of the terminal's visibility.
8705
*/
8706
export enum TaskRevealKind {
8707
/**
8708
* Always brings the terminal to front if the task is executed.
8709
*/
8710
Always = 1,
8711
8712
/**
8713
* Only brings the terminal to front if a problem is detected executing the task
8714
* (e.g. the task couldn't be started because).
8715
*/
8716
Silent = 2,
8717
8718
/**
8719
* The terminal never comes to front when the task is executed.
8720
*/
8721
Never = 3
8722
}
8723
8724
/**
8725
* Controls how the task channel is used between tasks
8726
*/
8727
export enum TaskPanelKind {
8728
8729
/**
8730
* Shares a panel with other tasks. This is the default.
8731
*/
8732
Shared = 1,
8733
8734
/**
8735
* Uses a dedicated panel for this tasks. The panel is not
8736
* shared with other tasks.
8737
*/
8738
Dedicated = 2,
8739
8740
/**
8741
* Creates a new panel whenever this task is executed.
8742
*/
8743
New = 3
8744
}
8745
8746
/**
8747
* Controls how the task is presented in the UI.
8748
*/
8749
export interface TaskPresentationOptions {
8750
/**
8751
* Controls whether the task output is reveal in the user interface.
8752
* Defaults to `RevealKind.Always`.
8753
*/
8754
reveal?: TaskRevealKind;
8755
8756
/**
8757
* Controls whether the command associated with the task is echoed
8758
* in the user interface.
8759
*/
8760
echo?: boolean;
8761
8762
/**
8763
* Controls whether the panel showing the task output is taking focus.
8764
*/
8765
focus?: boolean;
8766
8767
/**
8768
* Controls if the task panel is used for this task only (dedicated),
8769
* shared between tasks (shared) or if a new panel is created on
8770
* every task execution (new). Defaults to `TaskInstanceKind.Shared`
8771
*/
8772
panel?: TaskPanelKind;
8773
8774
/**
8775
* Controls whether to show the "Terminal will be reused by tasks, press any key to close it" message.
8776
*/
8777
showReuseMessage?: boolean;
8778
8779
/**
8780
* Controls whether the terminal is cleared before executing the task.
8781
*/
8782
clear?: boolean;
8783
8784
/**
8785
* Controls whether the terminal is closed after executing the task.
8786
*/
8787
close?: boolean;
8788
}
8789
8790
/**
8791
* A grouping for tasks. The editor by default supports the
8792
* 'Clean', 'Build', 'RebuildAll' and 'Test' group.
8793
*/
8794
export class TaskGroup {
8795
8796
/**
8797
* The clean task group;
8798
*/
8799
static Clean: TaskGroup;
8800
8801
/**
8802
* The build task group;
8803
*/
8804
static Build: TaskGroup;
8805
8806
/**
8807
* The rebuild all task group;
8808
*/
8809
static Rebuild: TaskGroup;
8810
8811
/**
8812
* The test all task group;
8813
*/
8814
static Test: TaskGroup;
8815
8816
/**
8817
* Whether the task that is part of this group is the default for the group.
8818
* This property cannot be set through API, and is controlled by a user's task configurations.
8819
*/
8820
readonly isDefault: boolean | undefined;
8821
8822
/**
8823
* The ID of the task group. Is one of TaskGroup.Clean.id, TaskGroup.Build.id, TaskGroup.Rebuild.id, or TaskGroup.Test.id.
8824
*/
8825
readonly id: string;
8826
8827
/**
8828
* Private constructor
8829
*
8830
* @param id Identifier of a task group.
8831
* @param label The human-readable name of a task group.
8832
*/
8833
private constructor(id: string, label: string);
8834
}
8835
8836
/**
8837
* A structure that defines a task kind in the system.
8838
* The value must be JSON-stringifyable.
8839
*/
8840
export interface TaskDefinition {
8841
/**
8842
* The task definition describing the task provided by an extension.
8843
* Usually a task provider defines more properties to identify
8844
* a task. They need to be defined in the package.json of the
8845
* extension under the 'taskDefinitions' extension point. The npm
8846
* task definition for example looks like this
8847
* ```typescript
8848
* interface NpmTaskDefinition extends TaskDefinition {
8849
* script: string;
8850
* }
8851
* ```
8852
*
8853
* Note that type identifier starting with a '$' are reserved for internal
8854
* usages and shouldn't be used by extensions.
8855
*/
8856
readonly type: string;
8857
8858
/**
8859
* Additional attributes of a concrete task definition.
8860
*/
8861
[name: string]: any;
8862
}
8863
8864
/**
8865
* Options for a process execution
8866
*/
8867
export interface ProcessExecutionOptions {
8868
/**
8869
* The current working directory of the executed program or shell.
8870
* If omitted the tools current workspace root is used.
8871
*/
8872
cwd?: string;
8873
8874
/**
8875
* The additional environment of the executed program or shell. If omitted
8876
* the parent process' environment is used. If provided it is merged with
8877
* the parent process' environment.
8878
*/
8879
env?: { [key: string]: string };
8880
}
8881
8882
/**
8883
* The execution of a task happens as an external process
8884
* without shell interaction.
8885
*/
8886
export class ProcessExecution {
8887
8888
/**
8889
* Creates a process execution.
8890
*
8891
* @param process The process to start.
8892
* @param options Optional options for the started process.
8893
*/
8894
constructor(process: string, options?: ProcessExecutionOptions);
8895
8896
/**
8897
* Creates a process execution.
8898
*
8899
* @param process The process to start.
8900
* @param args Arguments to be passed to the process.
8901
* @param options Optional options for the started process.
8902
*/
8903
constructor(process: string, args: string[], options?: ProcessExecutionOptions);
8904
8905
/**
8906
* The process to be executed.
8907
*/
8908
process: string;
8909
8910
/**
8911
* The arguments passed to the process. Defaults to an empty array.
8912
*/
8913
args: string[];
8914
8915
/**
8916
* The process options used when the process is executed.
8917
* Defaults to undefined.
8918
*/
8919
options?: ProcessExecutionOptions;
8920
}
8921
8922
/**
8923
* The shell quoting options.
8924
*/
8925
export interface ShellQuotingOptions {
8926
8927
/**
8928
* The character used to do character escaping. If a string is provided only spaces
8929
* are escaped. If a `{ escapeChar, charsToEscape }` literal is provide all characters
8930
* in `charsToEscape` are escaped using the `escapeChar`.
8931
*/
8932
escape?: string | {
8933
/**
8934
* The escape character.
8935
*/
8936
escapeChar: string;
8937
/**
8938
* The characters to escape.
8939
*/
8940
charsToEscape: string;
8941
};
8942
8943
/**
8944
* The character used for strong quoting. The string's length must be 1.
8945
*/
8946
strong?: string;
8947
8948
/**
8949
* The character used for weak quoting. The string's length must be 1.
8950
*/
8951
weak?: string;
8952
}
8953
8954
/**
8955
* Options for a shell execution
8956
*/
8957
export interface ShellExecutionOptions {
8958
/**
8959
* The shell executable.
8960
*/
8961
executable?: string;
8962
8963
/**
8964
* The arguments to be passed to the shell executable used to run the task. Most shells
8965
* require special arguments to execute a command. For example `bash` requires the `-c`
8966
* argument to execute a command, `PowerShell` requires `-Command` and `cmd` requires both
8967
* `/d` and `/c`.
8968
*/
8969
shellArgs?: string[];
8970
8971
/**
8972
* The shell quotes supported by this shell.
8973
*/
8974
shellQuoting?: ShellQuotingOptions;
8975
8976
/**
8977
* The current working directory of the executed shell.
8978
* If omitted the tools current workspace root is used.
8979
*/
8980
cwd?: string;
8981
8982
/**
8983
* The additional environment of the executed shell. If omitted
8984
* the parent process' environment is used. If provided it is merged with
8985
* the parent process' environment.
8986
*/
8987
env?: { [key: string]: string };
8988
}
8989
8990
/**
8991
* Defines how an argument should be quoted if it contains
8992
* spaces or unsupported characters.
8993
*/
8994
export enum ShellQuoting {
8995
8996
/**
8997
* Character escaping should be used. This for example
8998
* uses \ on bash and ` on PowerShell.
8999
*/
9000
Escape = 1,
9001
9002
/**
9003
* Strong string quoting should be used. This for example
9004
* uses " for Windows cmd and ' for bash and PowerShell.
9005
* Strong quoting treats arguments as literal strings.
9006
* Under PowerShell echo 'The value is $(2 * 3)' will
9007
* print `The value is $(2 * 3)`
9008
*/
9009
Strong = 2,
9010
9011
/**
9012
* Weak string quoting should be used. This for example
9013
* uses " for Windows cmd, bash and PowerShell. Weak quoting
9014
* still performs some kind of evaluation inside the quoted
9015
* string. Under PowerShell echo "The value is $(2 * 3)"
9016
* will print `The value is 6`
9017
*/
9018
Weak = 3
9019
}
9020
9021
/**
9022
* A string that will be quoted depending on the used shell.
9023
*/
9024
export interface ShellQuotedString {
9025
/**
9026
* The actual string value.
9027
*/
9028
value: string;
9029
9030
/**
9031
* The quoting style to use.
9032
*/
9033
quoting: ShellQuoting;
9034
}
9035
9036
/**
9037
* Represents a task execution that happens inside a shell.
9038
*/
9039
export class ShellExecution {
9040
/**
9041
* Creates a shell execution with a full command line.
9042
*
9043
* @param commandLine The command line to execute.
9044
* @param options Optional options for the started the shell.
9045
*/
9046
constructor(commandLine: string, options?: ShellExecutionOptions);
9047
9048
/**
9049
* Creates a shell execution with a command and arguments. For the real execution the editor will
9050
* construct a command line from the command and the arguments. This is subject to interpretation
9051
* especially when it comes to quoting. If full control over the command line is needed please
9052
* use the constructor that creates a `ShellExecution` with the full command line.
9053
*
9054
* @param command The command to execute.
9055
* @param args The command arguments.
9056
* @param options Optional options for the started the shell.
9057
*/
9058
constructor(command: string | ShellQuotedString, args: Array<string | ShellQuotedString>, options?: ShellExecutionOptions);
9059
9060
/**
9061
* The shell command line. Is `undefined` if created with a command and arguments.
9062
*/
9063
commandLine: string | undefined;
9064
9065
/**
9066
* The shell command. Is `undefined` if created with a full command line.
9067
*/
9068
command: string | ShellQuotedString | undefined;
9069
9070
/**
9071
* The shell args. Is `undefined` if created with a full command line.
9072
*/
9073
args: Array<string | ShellQuotedString> | undefined;
9074
9075
/**
9076
* The shell options used when the command line is executed in a shell.
9077
* Defaults to undefined.
9078
*/
9079
options?: ShellExecutionOptions;
9080
}
9081
9082
/**
9083
* Class used to execute an extension callback as a task.
9084
*/
9085
export class CustomExecution {
9086
/**
9087
* Constructs a CustomExecution task object. The callback will be executed when the task is run, at which point the
9088
* extension should return the Pseudoterminal it will "run in". The task should wait to do further execution until
9089
* {@link Pseudoterminal.open} is called. Task cancellation should be handled using
9090
* {@link Pseudoterminal.close}. When the task is complete fire
9091
* {@link Pseudoterminal.onDidClose}.
9092
* @param callback The callback that will be called when the task is started by a user. Any ${} style variables that
9093
* were in the task definition will be resolved and passed into the callback as `resolvedDefinition`.
9094
*/
9095
constructor(callback: (resolvedDefinition: TaskDefinition) => Thenable<Pseudoterminal>);
9096
}
9097
9098
/**
9099
* The scope of a task.
9100
*/
9101
export enum TaskScope {
9102
/**
9103
* The task is a global task. Global tasks are currently not supported.
9104
*/
9105
Global = 1,
9106
9107
/**
9108
* The task is a workspace task
9109
*/
9110
Workspace = 2
9111
}
9112
9113
/**
9114
* Run options for a task.
9115
*/
9116
export interface RunOptions {
9117
/**
9118
* Controls whether task variables are re-evaluated on rerun.
9119
*/
9120
reevaluateOnRerun?: boolean;
9121
}
9122
9123
/**
9124
* A task to execute
9125
*/
9126
export class Task {
9127
9128
/**
9129
* Creates a new task.
9130
*
9131
* @param taskDefinition The task definition as defined in the taskDefinitions extension point.
9132
* @param scope Specifies the task's scope. It is either a global or a workspace task or a task for a specific workspace folder. Global tasks are currently not supported.
9133
* @param name The task's name. Is presented in the user interface.
9134
* @param source The task's source (e.g. 'gulp', 'npm', ...). Is presented in the user interface.
9135
* @param execution The process or shell execution.
9136
* @param problemMatchers the names of problem matchers to use, like '$tsc'
9137
* or '$eslint'. Problem matchers can be contributed by an extension using
9138
* the `problemMatchers` extension point.
9139
*/
9140
constructor(taskDefinition: TaskDefinition, scope: WorkspaceFolder | TaskScope.Global | TaskScope.Workspace, name: string, source: string, execution?: ProcessExecution | ShellExecution | CustomExecution, problemMatchers?: string | string[]);
9141
9142
/**
9143
* Creates a new task.
9144
*
9145
* @deprecated Use the new constructors that allow specifying a scope for the task.
9146
*
9147
* @param taskDefinition The task definition as defined in the taskDefinitions extension point.
9148
* @param name The task's name. Is presented in the user interface.
9149
* @param source The task's source (e.g. 'gulp', 'npm', ...). Is presented in the user interface.
9150
* @param execution The process or shell execution.
9151
* @param problemMatchers the names of problem matchers to use, like '$tsc'
9152
* or '$eslint'. Problem matchers can be contributed by an extension using
9153
* the `problemMatchers` extension point.
9154
*/
9155
constructor(taskDefinition: TaskDefinition, name: string, source: string, execution?: ProcessExecution | ShellExecution, problemMatchers?: string | string[]);
9156
9157
/**
9158
* The task's definition.
9159
*/
9160
definition: TaskDefinition;
9161
9162
/**
9163
* The task's scope.
9164
*/
9165
readonly scope: TaskScope.Global | TaskScope.Workspace | WorkspaceFolder | undefined;
9166
9167
/**
9168
* The task's name
9169
*/
9170
name: string;
9171
9172
/**
9173
* A human-readable string which is rendered less prominently on a separate line in places
9174
* where the task's name is displayed. Supports rendering of {@link ThemeIcon theme icons}
9175
* via the `$(<name>)`-syntax.
9176
*/
9177
detail?: string;
9178
9179
/**
9180
* The task's execution engine
9181
*/
9182
execution?: ProcessExecution | ShellExecution | CustomExecution;
9183
9184
/**
9185
* Whether the task is a background task or not.
9186
*/
9187
isBackground: boolean;
9188
9189
/**
9190
* A human-readable string describing the source of this shell task, e.g. 'gulp'
9191
* or 'npm'. Supports rendering of {@link ThemeIcon theme icons} via the `$(<name>)`-syntax.
9192
*/
9193
source: string;
9194
9195
/**
9196
* The task group this tasks belongs to. See TaskGroup
9197
* for a predefined set of available groups.
9198
* Defaults to undefined meaning that the task doesn't
9199
* belong to any special group.
9200
*/
9201
group?: TaskGroup;
9202
9203
/**
9204
* The presentation options. Defaults to an empty literal.
9205
*/
9206
presentationOptions: TaskPresentationOptions;
9207
9208
/**
9209
* The problem matchers attached to the task. Defaults to an empty
9210
* array.
9211
*/
9212
problemMatchers: string[];
9213
9214
/**
9215
* Run options for the task
9216
*/
9217
runOptions: RunOptions;
9218
}
9219
9220
/**
9221
* A task provider allows to add tasks to the task service.
9222
* A task provider is registered via {@link tasks.registerTaskProvider}.
9223
*/
9224
export interface TaskProvider<T extends Task = Task> {
9225
/**
9226
* Provides tasks.
9227
* @param token A cancellation token.
9228
* @returns an array of tasks
9229
*/
9230
provideTasks(token: CancellationToken): ProviderResult<T[]>;
9231
9232
/**
9233
* Resolves a task that has no {@linkcode Task.execution execution} set. Tasks are
9234
* often created from information found in the `tasks.json`-file. Such tasks miss
9235
* the information on how to execute them and a task provider must fill in
9236
* the missing information in the `resolveTask`-method. This method will not be
9237
* called for tasks returned from the above `provideTasks` method since those
9238
* tasks are always fully resolved. A valid default implementation for the
9239
* `resolveTask` method is to return `undefined`.
9240
*
9241
* Note that when filling in the properties of `task`, you _must_ be sure to
9242
* use the exact same `TaskDefinition` and not create a new one. Other properties
9243
* may be changed.
9244
*
9245
* @param task The task to resolve.
9246
* @param token A cancellation token.
9247
* @returns The resolved task
9248
*/
9249
resolveTask(task: T, token: CancellationToken): ProviderResult<T>;
9250
}
9251
9252
/**
9253
* An object representing an executed Task. It can be used
9254
* to terminate a task.
9255
*
9256
* This interface is not intended to be implemented.
9257
*/
9258
export interface TaskExecution {
9259
/**
9260
* The task that got started.
9261
*/
9262
task: Task;
9263
9264
/**
9265
* Terminates the task execution.
9266
*/
9267
terminate(): void;
9268
}
9269
9270
/**
9271
* An event signaling the start of a task execution.
9272
*
9273
* This interface is not intended to be implemented.
9274
*/
9275
export interface TaskStartEvent {
9276
/**
9277
* The task item representing the task that got started.
9278
*/
9279
readonly execution: TaskExecution;
9280
}
9281
9282
/**
9283
* An event signaling the end of an executed task.
9284
*
9285
* This interface is not intended to be implemented.
9286
*/
9287
export interface TaskEndEvent {
9288
/**
9289
* The task item representing the task that finished.
9290
*/
9291
readonly execution: TaskExecution;
9292
}
9293
9294
/**
9295
* An event signaling the start of a process execution
9296
* triggered through a task
9297
*/
9298
export interface TaskProcessStartEvent {
9299
9300
/**
9301
* The task execution for which the process got started.
9302
*/
9303
readonly execution: TaskExecution;
9304
9305
/**
9306
* The underlying process id.
9307
*/
9308
readonly processId: number;
9309
}
9310
9311
/**
9312
* An event signaling the end of a process execution
9313
* triggered through a task
9314
*/
9315
export interface TaskProcessEndEvent {
9316
9317
/**
9318
* The task execution for which the process got started.
9319
*/
9320
readonly execution: TaskExecution;
9321
9322
/**
9323
* The process's exit code. Will be `undefined` when the task is terminated.
9324
*/
9325
readonly exitCode: number | undefined;
9326
}
9327
9328
/**
9329
* A task filter denotes tasks by their version and types
9330
*/
9331
export interface TaskFilter {
9332
/**
9333
* The task version as used in the tasks.json file.
9334
* The string support the package.json semver notation.
9335
*/
9336
version?: string;
9337
9338
/**
9339
* The task type to return;
9340
*/
9341
type?: string;
9342
}
9343
9344
/**
9345
* Namespace for tasks functionality.
9346
*/
9347
export namespace tasks {
9348
9349
/**
9350
* Register a task provider.
9351
*
9352
* @param type The task kind type this provider is registered for.
9353
* @param provider A task provider.
9354
* @returns A {@link Disposable} that unregisters this provider when being disposed.
9355
*/
9356
export function registerTaskProvider(type: string, provider: TaskProvider): Disposable;
9357
9358
/**
9359
* Fetches all tasks available in the systems. This includes tasks
9360
* from `tasks.json` files as well as tasks from task providers
9361
* contributed through extensions.
9362
*
9363
* @param filter Optional filter to select tasks of a certain type or version.
9364
* @returns A thenable that resolves to an array of tasks.
9365
*/
9366
export function fetchTasks(filter?: TaskFilter): Thenable<Task[]>;
9367
9368
/**
9369
* Executes a task that is managed by the editor. The returned
9370
* task execution can be used to terminate the task.
9371
*
9372
* @throws When running a ShellExecution or a ProcessExecution
9373
* task in an environment where a new process cannot be started.
9374
* In such an environment, only CustomExecution tasks can be run.
9375
*
9376
* @param task the task to execute
9377
* @returns A thenable that resolves to a task execution.
9378
*/
9379
export function executeTask(task: Task): Thenable<TaskExecution>;
9380
9381
/**
9382
* The currently active task executions or an empty array.
9383
*/
9384
export const taskExecutions: readonly TaskExecution[];
9385
9386
/**
9387
* Fires when a task starts.
9388
*/
9389
export const onDidStartTask: Event<TaskStartEvent>;
9390
9391
/**
9392
* Fires when a task ends.
9393
*/
9394
export const onDidEndTask: Event<TaskEndEvent>;
9395
9396
/**
9397
* Fires when the underlying process has been started.
9398
* This event will not fire for tasks that don't
9399
* execute an underlying process.
9400
*/
9401
export const onDidStartTaskProcess: Event<TaskProcessStartEvent>;
9402
9403
/**
9404
* Fires when the underlying process has ended.
9405
* This event will not fire for tasks that don't
9406
* execute an underlying process.
9407
*/
9408
export const onDidEndTaskProcess: Event<TaskProcessEndEvent>;
9409
}
9410
9411
/**
9412
* Enumeration of file types. The types `File` and `Directory` can also be
9413
* a symbolic links, in that case use `FileType.File | FileType.SymbolicLink` and
9414
* `FileType.Directory | FileType.SymbolicLink`.
9415
*/
9416
export enum FileType {
9417
/**
9418
* The file type is unknown.
9419
*/
9420
Unknown = 0,
9421
/**
9422
* A regular file.
9423
*/
9424
File = 1,
9425
/**
9426
* A directory.
9427
*/
9428
Directory = 2,
9429
/**
9430
* A symbolic link to a file.
9431
*/
9432
SymbolicLink = 64
9433
}
9434
9435
/**
9436
* Permissions of a file.
9437
*/
9438
export enum FilePermission {
9439
/**
9440
* The file is readonly.
9441
*
9442
* *Note:* All `FileStat` from a `FileSystemProvider` that is registered with
9443
* the option `isReadonly: true` will be implicitly handled as if `FilePermission.Readonly`
9444
* is set. As a consequence, it is not possible to have a readonly file system provider
9445
* registered where some `FileStat` are not readonly.
9446
*/
9447
Readonly = 1
9448
}
9449
9450
/**
9451
* The `FileStat`-type represents metadata about a file
9452
*/
9453
export interface FileStat {
9454
/**
9455
* The type of the file, e.g. is a regular file, a directory, or symbolic link
9456
* to a file.
9457
*
9458
* *Note:* This value might be a bitmask, e.g. `FileType.File | FileType.SymbolicLink`.
9459
*/
9460
type: FileType;
9461
/**
9462
* The creation timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC.
9463
*/
9464
ctime: number;
9465
/**
9466
* The modification timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC.
9467
*
9468
* *Note:* If the file changed, it is important to provide an updated `mtime` that advanced
9469
* from the previous value. Otherwise there may be optimizations in place that will not show
9470
* the updated file contents in an editor for example.
9471
*/
9472
mtime: number;
9473
/**
9474
* The size in bytes.
9475
*
9476
* *Note:* If the file changed, it is important to provide an updated `size`. Otherwise there
9477
* may be optimizations in place that will not show the updated file contents in an editor for
9478
* example.
9479
*/
9480
size: number;
9481
/**
9482
* The permissions of the file, e.g. whether the file is readonly.
9483
*
9484
* *Note:* This value might be a bitmask, e.g. `FilePermission.Readonly | FilePermission.Other`.
9485
*/
9486
permissions?: FilePermission;
9487
}
9488
9489
/**
9490
* A type that filesystem providers should use to signal errors.
9491
*
9492
* This class has factory methods for common error-cases, like `FileNotFound` when
9493
* a file or folder doesn't exist, use them like so: `throw vscode.FileSystemError.FileNotFound(someUri);`
9494
*/
9495
export class FileSystemError extends Error {
9496
9497
/**
9498
* Create an error to signal that a file or folder wasn't found.
9499
* @param messageOrUri Message or uri.
9500
*/
9501
static FileNotFound(messageOrUri?: string | Uri): FileSystemError;
9502
9503
/**
9504
* Create an error to signal that a file or folder already exists, e.g. when
9505
* creating but not overwriting a file.
9506
* @param messageOrUri Message or uri.
9507
*/
9508
static FileExists(messageOrUri?: string | Uri): FileSystemError;
9509
9510
/**
9511
* Create an error to signal that a file is not a folder.
9512
* @param messageOrUri Message or uri.
9513
*/
9514
static FileNotADirectory(messageOrUri?: string | Uri): FileSystemError;
9515
9516
/**
9517
* Create an error to signal that a file is a folder.
9518
* @param messageOrUri Message or uri.
9519
*/
9520
static FileIsADirectory(messageOrUri?: string | Uri): FileSystemError;
9521
9522
/**
9523
* Create an error to signal that an operation lacks required permissions.
9524
* @param messageOrUri Message or uri.
9525
*/
9526
static NoPermissions(messageOrUri?: string | Uri): FileSystemError;
9527
9528
/**
9529
* Create an error to signal that the file system is unavailable or too busy to
9530
* complete a request.
9531
* @param messageOrUri Message or uri.
9532
*/
9533
static Unavailable(messageOrUri?: string | Uri): FileSystemError;
9534
9535
/**
9536
* Creates a new filesystem error.
9537
*
9538
* @param messageOrUri Message or uri.
9539
*/
9540
constructor(messageOrUri?: string | Uri);
9541
9542
/**
9543
* A code that identifies this error.
9544
*
9545
* Possible values are names of errors, like {@linkcode FileSystemError.FileNotFound FileNotFound},
9546
* or `Unknown` for unspecified errors.
9547
*/
9548
readonly code: string;
9549
}
9550
9551
/**
9552
* Enumeration of file change types.
9553
*/
9554
export enum FileChangeType {
9555
9556
/**
9557
* The contents or metadata of a file have changed.
9558
*/
9559
Changed = 1,
9560
9561
/**
9562
* A file has been created.
9563
*/
9564
Created = 2,
9565
9566
/**
9567
* A file has been deleted.
9568
*/
9569
Deleted = 3,
9570
}
9571
9572
/**
9573
* The event filesystem providers must use to signal a file change.
9574
*/
9575
export interface FileChangeEvent {
9576
9577
/**
9578
* The type of change.
9579
*/
9580
readonly type: FileChangeType;
9581
9582
/**
9583
* The uri of the file that has changed.
9584
*/
9585
readonly uri: Uri;
9586
}
9587
9588
/**
9589
* The filesystem provider defines what the editor needs to read, write, discover,
9590
* and to manage files and folders. It allows extensions to serve files from remote places,
9591
* like ftp-servers, and to seamlessly integrate those into the editor.
9592
*
9593
* * *Note 1:* The filesystem provider API works with {@link Uri uris} and assumes hierarchical
9594
* paths, e.g. `foo:/my/path` is a child of `foo:/my/` and a parent of `foo:/my/path/deeper`.
9595
* * *Note 2:* There is an activation event `onFileSystem:<scheme>` that fires when a file
9596
* or folder is being accessed.
9597
* * *Note 3:* The word 'file' is often used to denote all {@link FileType kinds} of files, e.g.
9598
* folders, symbolic links, and regular files.
9599
*/
9600
export interface FileSystemProvider {
9601
9602
/**
9603
* An event to signal that a resource has been created, changed, or deleted. This
9604
* event should fire for resources that are being {@link FileSystemProvider.watch watched}
9605
* by clients of this provider.
9606
*
9607
* *Note:* It is important that the metadata of the file that changed provides an
9608
* updated `mtime` that advanced from the previous value in the {@link FileStat stat} and a
9609
* correct `size` value. Otherwise there may be optimizations in place that will not show
9610
* the change in an editor for example.
9611
*/
9612
readonly onDidChangeFile: Event<FileChangeEvent[]>;
9613
9614
/**
9615
* Subscribes to file change events in the file or folder denoted by `uri`. For folders,
9616
* the option `recursive` indicates whether subfolders, sub-subfolders, etc. should
9617
* be watched for file changes as well. With `recursive: false`, only changes to the
9618
* files that are direct children of the folder should trigger an event.
9619
*
9620
* The `excludes` array is used to indicate paths that should be excluded from file
9621
* watching. It is typically derived from the `files.watcherExclude` setting that
9622
* is configurable by the user. Each entry can be be:
9623
* - the absolute path to exclude
9624
* - a relative path to exclude (for example `build/output`)
9625
* - a simple glob pattern (for example `**​/build`, `output/**`)
9626
*
9627
* *Note* that case-sensitivity of the {@link excludes} patterns for built-in file system providers
9628
* will depend on the underlying file system: on Windows and macOS the matching will be case-insensitive and
9629
* on Linux it will be case-sensitive.
9630
*
9631
* It is the file system provider's job to call {@linkcode FileSystemProvider.onDidChangeFile onDidChangeFile}
9632
* for every change given these rules. No event should be emitted for files that match any of the provided
9633
* excludes.
9634
*
9635
* @param uri The uri of the file or folder to be watched.
9636
* @param options Configures the watch.
9637
* @returns A disposable that tells the provider to stop watching the `uri`.
9638
*/
9639
watch(uri: Uri, options: {
9640
/**
9641
* When enabled also watch subfolders.
9642
*/
9643
readonly recursive: boolean;
9644
/**
9645
* A list of paths and pattern to exclude from watching.
9646
*/
9647
readonly excludes: readonly string[];
9648
}): Disposable;
9649
9650
/**
9651
* Retrieve metadata about a file.
9652
*
9653
* Note that the metadata for symbolic links should be the metadata of the file they refer to.
9654
* Still, the {@link FileType.SymbolicLink SymbolicLink}-type must be used in addition to the actual type, e.g.
9655
* `FileType.SymbolicLink | FileType.Directory`.
9656
*
9657
* @param uri The uri of the file to retrieve metadata about.
9658
* @returns The file metadata about the file.
9659
* @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when `uri` doesn't exist.
9660
*/
9661
stat(uri: Uri): FileStat | Thenable<FileStat>;
9662
9663
/**
9664
* Retrieve all entries of a {@link FileType.Directory directory}.
9665
*
9666
* @param uri The uri of the folder.
9667
* @returns An array of name/type-tuples or a thenable that resolves to such.
9668
* @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when `uri` doesn't exist.
9669
*/
9670
readDirectory(uri: Uri): [string, FileType][] | Thenable<[string, FileType][]>;
9671
9672
/**
9673
* Create a new directory (Note, that new files are created via `write`-calls).
9674
*
9675
* @param uri The uri of the new folder.
9676
* @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when the parent of `uri` doesn't exist, e.g. no mkdirp-logic required.
9677
* @throws {@linkcode FileSystemError.FileExists FileExists} when `uri` already exists.
9678
* @throws {@linkcode FileSystemError.NoPermissions NoPermissions} when permissions aren't sufficient.
9679
*/
9680
createDirectory(uri: Uri): void | Thenable<void>;
9681
9682
/**
9683
* Read the entire contents of a file.
9684
*
9685
* @param uri The uri of the file.
9686
* @returns An array of bytes or a thenable that resolves to such.
9687
* @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when `uri` doesn't exist.
9688
*/
9689
readFile(uri: Uri): Uint8Array | Thenable<Uint8Array>;
9690
9691
/**
9692
* Write data to a file, replacing its entire contents.
9693
*
9694
* @param uri The uri of the file.
9695
* @param content The new content of the file.
9696
* @param options Defines if missing files should or must be created.
9697
* @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when `uri` doesn't exist and `create` is not set.
9698
* @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when the parent of `uri` doesn't exist and `create` is set, e.g. no mkdirp-logic required.
9699
* @throws {@linkcode FileSystemError.FileExists FileExists} when `uri` already exists, `create` is set but `overwrite` is not set.
9700
* @throws {@linkcode FileSystemError.NoPermissions NoPermissions} when permissions aren't sufficient.
9701
*/
9702
writeFile(uri: Uri, content: Uint8Array, options: {
9703
/**
9704
* Create the file if it does not exist already.
9705
*/
9706
readonly create: boolean;
9707
/**
9708
* Overwrite the file if it does exist.
9709
*/
9710
readonly overwrite: boolean;
9711
}): void | Thenable<void>;
9712
9713
/**
9714
* Delete a file.
9715
*
9716
* @param uri The resource that is to be deleted.
9717
* @param options Defines if deletion of folders is recursive.
9718
* @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when `uri` doesn't exist.
9719
* @throws {@linkcode FileSystemError.NoPermissions NoPermissions} when permissions aren't sufficient.
9720
*/
9721
delete(uri: Uri, options: {
9722
/**
9723
* Delete the content recursively if a folder is denoted.
9724
*/
9725
readonly recursive: boolean;
9726
}): void | Thenable<void>;
9727
9728
/**
9729
* Rename a file or folder.
9730
*
9731
* @param oldUri The existing file.
9732
* @param newUri The new location.
9733
* @param options Defines if existing files should be overwritten.
9734
* @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when `oldUri` doesn't exist.
9735
* @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when parent of `newUri` doesn't exist, e.g. no mkdirp-logic required.
9736
* @throws {@linkcode FileSystemError.FileExists FileExists} when `newUri` exists and when the `overwrite` option is not `true`.
9737
* @throws {@linkcode FileSystemError.NoPermissions NoPermissions} when permissions aren't sufficient.
9738
*/
9739
rename(oldUri: Uri, newUri: Uri, options: {
9740
/**
9741
* Overwrite the file if it does exist.
9742
*/
9743
readonly overwrite: boolean;
9744
}): void | Thenable<void>;
9745
9746
/**
9747
* Copy files or folders. Implementing this function is optional but it will speedup
9748
* the copy operation.
9749
*
9750
* @param source The existing file.
9751
* @param destination The destination location.
9752
* @param options Defines if existing files should be overwritten.
9753
* @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when `source` doesn't exist.
9754
* @throws {@linkcode FileSystemError.FileNotFound FileNotFound} when parent of `destination` doesn't exist, e.g. no mkdirp-logic required.
9755
* @throws {@linkcode FileSystemError.FileExists FileExists} when `destination` exists and when the `overwrite` option is not `true`.
9756
* @throws {@linkcode FileSystemError.NoPermissions NoPermissions} when permissions aren't sufficient.
9757
*/
9758
copy?(source: Uri, destination: Uri, options: {
9759
/**
9760
* Overwrite the file if it does exist.
9761
*/
9762
readonly overwrite: boolean;
9763
}): void | Thenable<void>;
9764
}
9765
9766
/**
9767
* The file system interface exposes the editor's built-in and contributed
9768
* {@link FileSystemProvider file system providers}. It allows extensions to work
9769
* with files from the local disk as well as files from remote places, like the
9770
* remote extension host or ftp-servers.
9771
*
9772
* *Note* that an instance of this interface is available as {@linkcode workspace.fs}.
9773
*/
9774
export interface FileSystem {
9775
9776
/**
9777
* Retrieve metadata about a file.
9778
*
9779
* @param uri The uri of the file to retrieve metadata about.
9780
* @returns The file metadata about the file.
9781
*/
9782
stat(uri: Uri): Thenable<FileStat>;
9783
9784
/**
9785
* Retrieve all entries of a {@link FileType.Directory directory}.
9786
*
9787
* @param uri The uri of the folder.
9788
* @returns An array of name/type-tuples or a thenable that resolves to such.
9789
*/
9790
readDirectory(uri: Uri): Thenable<[string, FileType][]>;
9791
9792
/**
9793
* Create a new directory (Note, that new files are created via `write`-calls).
9794
*
9795
* *Note* that missing directories are created automatically, e.g this call has
9796
* `mkdirp` semantics.
9797
*
9798
* @param uri The uri of the new folder.
9799
*/
9800
createDirectory(uri: Uri): Thenable<void>;
9801
9802
/**
9803
* Read the entire contents of a file.
9804
*
9805
* @param uri The uri of the file.
9806
* @returns An array of bytes or a thenable that resolves to such.
9807
*/
9808
readFile(uri: Uri): Thenable<Uint8Array>;
9809
9810
/**
9811
* Write data to a file, replacing its entire contents.
9812
*
9813
* @param uri The uri of the file.
9814
* @param content The new content of the file.
9815
*/
9816
writeFile(uri: Uri, content: Uint8Array): Thenable<void>;
9817
9818
/**
9819
* Delete a file.
9820
*
9821
* @param uri The resource that is to be deleted.
9822
* @param options Defines if trash can should be used and if deletion of folders is recursive
9823
*/
9824
delete(uri: Uri, options?: {
9825
/**
9826
* Delete the content recursively if a folder is denoted.
9827
*/
9828
recursive?: boolean;
9829
/**
9830
* Use the os's trashcan instead of permanently deleting files whenever possible.
9831
*/
9832
useTrash?: boolean;
9833
}): Thenable<void>;
9834
9835
/**
9836
* Rename a file or folder.
9837
*
9838
* @param source The existing file.
9839
* @param target The new location.
9840
* @param options Defines if existing files should be overwritten.
9841
*/
9842
rename(source: Uri, target: Uri, options?: {
9843
/**
9844
* Overwrite the file if it does exist.
9845
*/
9846
overwrite?: boolean;
9847
}): Thenable<void>;
9848
9849
/**
9850
* Copy files or folders.
9851
*
9852
* @param source The existing file.
9853
* @param target The destination location.
9854
* @param options Defines if existing files should be overwritten.
9855
*/
9856
copy(source: Uri, target: Uri, options?: {
9857
/**
9858
* Overwrite the file if it does exist.
9859
*/
9860
overwrite?: boolean;
9861
}): Thenable<void>;
9862
9863
/**
9864
* Check if a given file system supports writing files.
9865
*
9866
* Keep in mind that just because a file system supports writing, that does
9867
* not mean that writes will always succeed. There may be permissions issues
9868
* or other errors that prevent writing a file.
9869
*
9870
* @param scheme The scheme of the filesystem, for example `file` or `git`.
9871
*
9872
* @returns `true` if the file system supports writing, `false` if it does not
9873
* support writing (i.e. it is readonly), and `undefined` if the editor does not
9874
* know about the filesystem.
9875
*/
9876
isWritableFileSystem(scheme: string): boolean | undefined;
9877
}
9878
9879
/**
9880
* Defines a port mapping used for localhost inside the webview.
9881
*/
9882
export interface WebviewPortMapping {
9883
/**
9884
* Localhost port to remap inside the webview.
9885
*/
9886
readonly webviewPort: number;
9887
9888
/**
9889
* Destination port. The `webviewPort` is resolved to this port.
9890
*/
9891
readonly extensionHostPort: number;
9892
}
9893
9894
/**
9895
* Content settings for a webview.
9896
*/
9897
export interface WebviewOptions {
9898
/**
9899
* Controls whether scripts are enabled in the webview content or not.
9900
*
9901
* Defaults to false (scripts-disabled).
9902
*/
9903
readonly enableScripts?: boolean;
9904
9905
/**
9906
* Controls whether forms are enabled in the webview content or not.
9907
*
9908
* Defaults to true if {@link WebviewOptions.enableScripts scripts are enabled}. Otherwise defaults to false.
9909
* Explicitly setting this property to either true or false overrides the default.
9910
*/
9911
readonly enableForms?: boolean;
9912
9913
/**
9914
* Controls whether command uris are enabled in webview content or not.
9915
*
9916
* Defaults to `false` (command uris are disabled).
9917
*
9918
* If you pass in an array, only the commands in the array are allowed.
9919
*/
9920
readonly enableCommandUris?: boolean | readonly string[];
9921
9922
/**
9923
* Root paths from which the webview can load local (filesystem) resources using uris from `asWebviewUri`
9924
*
9925
* Default to the root folders of the current workspace plus the extension's install directory.
9926
*
9927
* Pass in an empty array to disallow access to any local resources.
9928
*/
9929
readonly localResourceRoots?: readonly Uri[];
9930
9931
/**
9932
* Mappings of localhost ports used inside the webview.
9933
*
9934
* Port mapping allow webviews to transparently define how localhost ports are resolved. This can be used
9935
* to allow using a static localhost port inside the webview that is resolved to random port that a service is
9936
* running on.
9937
*
9938
* If a webview accesses localhost content, we recommend that you specify port mappings even if
9939
* the `webviewPort` and `extensionHostPort` ports are the same.
9940
*
9941
* *Note* that port mappings only work for `http` or `https` urls. Websocket urls (e.g. `ws://localhost:3000`)
9942
* cannot be mapped to another port.
9943
*/
9944
readonly portMapping?: readonly WebviewPortMapping[];
9945
}
9946
9947
/**
9948
* Displays html content, similarly to an iframe.
9949
*/
9950
export interface Webview {
9951
/**
9952
* Content settings for the webview.
9953
*/
9954
options: WebviewOptions;
9955
9956
/**
9957
* HTML contents of the webview.
9958
*
9959
* This should be a complete, valid html document. Changing this property causes the webview to be reloaded.
9960
*
9961
* Webviews are sandboxed from normal extension process, so all communication with the webview must use
9962
* message passing. To send a message from the extension to the webview, use {@linkcode Webview.postMessage postMessage}.
9963
* To send message from the webview back to an extension, use the `acquireVsCodeApi` function inside the webview
9964
* to get a handle to the editor's api and then call `.postMessage()`:
9965
*
9966
* ```html
9967
* <script>
9968
* const vscode = acquireVsCodeApi(); // acquireVsCodeApi can only be invoked once
9969
* vscode.postMessage({ message: 'hello!' });
9970
* </script>
9971
* ```
9972
*
9973
* To load a resources from the workspace inside a webview, use the {@linkcode Webview.asWebviewUri asWebviewUri} method
9974
* and ensure the resource's directory is listed in {@linkcode WebviewOptions.localResourceRoots}.
9975
*
9976
* Keep in mind that even though webviews are sandboxed, they still allow running scripts and loading arbitrary content,
9977
* so extensions must follow all standard web security best practices when working with webviews. This includes
9978
* properly sanitizing all untrusted input (including content from the workspace) and
9979
* setting a [content security policy](https://aka.ms/vscode-api-webview-csp).
9980
*/
9981
html: string;
9982
9983
/**
9984
* Fired when the webview content posts a message.
9985
*
9986
* Webview content can post strings or json serializable objects back to an extension. They cannot
9987
* post `Blob`, `File`, `ImageData` and other DOM specific objects since the extension that receives the
9988
* message does not run in a browser environment.
9989
*/
9990
readonly onDidReceiveMessage: Event<any>;
9991
9992
/**
9993
* Post a message to the webview content.
9994
*
9995
* Messages are only delivered if the webview is live (either visible or in the
9996
* background with `retainContextWhenHidden`).
9997
*
9998
* @param message Body of the message. This must be a string or other json serializable object.
9999
*
10000
* For older versions of vscode, if an `ArrayBuffer` is included in `message`,
10001
* it will not be serialized properly and will not be received by the webview.
10002
* Similarly any TypedArrays, such as a `Uint8Array`, will be very inefficiently
10003
* serialized and will also not be recreated as a typed array inside the webview.
10004
*
10005
* However if your extension targets vscode 1.57+ in the `engines` field of its
10006
* `package.json`, any `ArrayBuffer` values that appear in `message` will be more
10007
* efficiently transferred to the webview and will also be correctly recreated inside
10008
* of the webview.
10009
*
10010
* @returns A promise that resolves when the message is posted to a webview or when it is
10011
* dropped because the message was not deliverable.
10012
*
10013
* Returns `true` if the message was posted to the webview. Messages can only be posted to
10014
* live webviews (i.e. either visible webviews or hidden webviews that set `retainContextWhenHidden`).
10015
*
10016
* A response of `true` does not mean that the message was actually received by the webview.
10017
* For example, no message listeners may be have been hooked up inside the webview or the webview may
10018
* have been destroyed after the message was posted but before it was received.
10019
*
10020
* If you want confirm that a message as actually received, you can try having your webview posting a
10021
* confirmation message back to your extension.
10022
*/
10023
postMessage(message: any): Thenable<boolean>;
10024
10025
/**
10026
* Convert a uri for the local file system to one that can be used inside webviews.
10027
*
10028
* Webviews cannot directly load resources from the workspace or local file system using `file:` uris. The
10029
* `asWebviewUri` function takes a local `file:` uri and converts it into a uri that can be used inside of
10030
* a webview to load the same resource:
10031
*
10032
* ```ts
10033
* webview.html = `<img src="${webview.asWebviewUri(vscode.Uri.file('/Users/codey/workspace/cat.gif'))}">`
10034
* ```
10035
*/
10036
asWebviewUri(localResource: Uri): Uri;
10037
10038
/**
10039
* Content security policy source for webview resources.
10040
*
10041
* This is the origin that should be used in a content security policy rule:
10042
*
10043
* ```ts
10044
* `img-src https: ${webview.cspSource} ...;`
10045
* ```
10046
*/
10047
readonly cspSource: string;
10048
}
10049
10050
/**
10051
* Content settings for a webview panel.
10052
*/
10053
export interface WebviewPanelOptions {
10054
/**
10055
* Controls if the find widget is enabled in the panel.
10056
*
10057
* Defaults to `false`.
10058
*/
10059
readonly enableFindWidget?: boolean;
10060
10061
/**
10062
* Controls if the webview panel's content (iframe) is kept around even when the panel
10063
* is no longer visible.
10064
*
10065
* Normally the webview panel's html context is created when the panel becomes visible
10066
* and destroyed when it is hidden. Extensions that have complex state
10067
* or UI can set the `retainContextWhenHidden` to make the editor keep the webview
10068
* context around, even when the webview moves to a background tab. When a webview using
10069
* `retainContextWhenHidden` becomes hidden, its scripts and other dynamic content are suspended.
10070
* When the panel becomes visible again, the context is automatically restored
10071
* in the exact same state it was in originally. You cannot send messages to a
10072
* hidden webview, even with `retainContextWhenHidden` enabled.
10073
*
10074
* `retainContextWhenHidden` has a high memory overhead and should only be used if
10075
* your panel's context cannot be quickly saved and restored.
10076
*/
10077
readonly retainContextWhenHidden?: boolean;
10078
}
10079
10080
/**
10081
* A panel that contains a {@linkcode Webview}.
10082
*/
10083
export interface WebviewPanel {
10084
/**
10085
* Identifies the type of the webview panel, such as `'markdown.preview'`.
10086
*/
10087
readonly viewType: string;
10088
10089
/**
10090
* Title of the panel shown in UI.
10091
*/
10092
title: string;
10093
10094
/**
10095
* Icon for the panel shown in UI.
10096
*/
10097
iconPath?: IconPath;
10098
10099
/**
10100
* {@linkcode Webview} belonging to the panel.
10101
*/
10102
readonly webview: Webview;
10103
10104
/**
10105
* Content settings for the webview panel.
10106
*/
10107
readonly options: WebviewPanelOptions;
10108
10109
/**
10110
* Editor position of the panel. This property is only set if the webview is in
10111
* one of the editor view columns.
10112
*/
10113
readonly viewColumn: ViewColumn | undefined;
10114
10115
/**
10116
* Whether the panel is active (focused by the user).
10117
*/
10118
readonly active: boolean;
10119
10120
/**
10121
* Whether the panel is visible.
10122
*/
10123
readonly visible: boolean;
10124
10125
/**
10126
* Fired when the panel's view state changes.
10127
*/
10128
readonly onDidChangeViewState: Event<WebviewPanelOnDidChangeViewStateEvent>;
10129
10130
/**
10131
* Fired when the panel is disposed.
10132
*
10133
* This may be because the user closed the panel or because {@linkcode WebviewPanel.dispose dispose} was
10134
* called on it.
10135
*
10136
* Trying to use the panel after it has been disposed throws an exception.
10137
*/
10138
readonly onDidDispose: Event<void>;
10139
10140
/**
10141
* Show the webview panel in a given column.
10142
*
10143
* A webview panel may only show in a single column at a time. If it is already showing, this
10144
* method moves it to a new column.
10145
*
10146
* @param viewColumn View column to show the panel in. Shows in the current {@linkcode WebviewPanel.viewColumn} if undefined.
10147
* @param preserveFocus When `true`, the webview will not take focus.
10148
*/
10149
reveal(viewColumn?: ViewColumn, preserveFocus?: boolean): void;
10150
10151
/**
10152
* Dispose of the webview panel.
10153
*
10154
* This closes the panel if it showing and disposes of the resources owned by the webview.
10155
* Webview panels are also disposed when the user closes the webview panel. Both cases
10156
* fire the {@linkcode onDidDispose} event.
10157
*/
10158
dispose(): any;
10159
}
10160
10161
/**
10162
* Event fired when a {@linkcode WebviewPanel webview panel's} view state changes.
10163
*/
10164
export interface WebviewPanelOnDidChangeViewStateEvent {
10165
/**
10166
* {@linkcode WebviewPanel} whose view state changed.
10167
*/
10168
readonly webviewPanel: WebviewPanel;
10169
}
10170
10171
/**
10172
* Restore webview panels that have been persisted when vscode shuts down.
10173
*
10174
* There are two types of webview persistence:
10175
*
10176
* - Persistence within a session.
10177
* - Persistence across sessions (across restarts of the editor).
10178
*
10179
* A `WebviewPanelSerializer` is only required for the second case: persisting a webview across sessions.
10180
*
10181
* Persistence within a session allows a webview to save its state when it becomes hidden
10182
* and restore its content from this state when it becomes visible again. It is powered entirely
10183
* by the webview content itself. To save off a persisted state, call `acquireVsCodeApi().setState()` with
10184
* any json serializable object. To restore the state again, call `getState()`
10185
*
10186
* ```js
10187
* // Within the webview
10188
* const vscode = acquireVsCodeApi();
10189
*
10190
* // Get existing state
10191
* const oldState = vscode.getState() || { value: 0 };
10192
*
10193
* // Update state
10194
* setState({ value: oldState.value + 1 })
10195
* ```
10196
*
10197
* A `WebviewPanelSerializer` extends this persistence across restarts of the editor. When the editor is shutdown,
10198
* it will save off the state from `setState` of all webviews that have a serializer. When the
10199
* webview first becomes visible after the restart, this state is passed to `deserializeWebviewPanel`.
10200
* The extension can then restore the old `WebviewPanel` from this state.
10201
*
10202
* @param T Type of the webview's state.
10203
*/
10204
export interface WebviewPanelSerializer<T = unknown> {
10205
/**
10206
* Restore a webview panel from its serialized `state`.
10207
*
10208
* Called when a serialized webview first becomes visible.
10209
*
10210
* @param webviewPanel Webview panel to restore. The serializer should take ownership of this panel. The
10211
* serializer must restore the webview's `.html` and hook up all webview events.
10212
* @param state Persisted state from the webview content.
10213
*
10214
* @returns Thenable indicating that the webview has been fully restored.
10215
*/
10216
deserializeWebviewPanel(webviewPanel: WebviewPanel, state: T): Thenable<void>;
10217
}
10218
10219
/**
10220
* A webview based view.
10221
*/
10222
export interface WebviewView {
10223
/**
10224
* Identifies the type of the webview view, such as `'hexEditor.dataView'`.
10225
*/
10226
readonly viewType: string;
10227
10228
/**
10229
* The underlying webview for the view.
10230
*/
10231
readonly webview: Webview;
10232
10233
/**
10234
* View title displayed in the UI.
10235
*
10236
* The view title is initially taken from the extension `package.json` contribution.
10237
*/
10238
title?: string;
10239
10240
/**
10241
* Human-readable string which is rendered less prominently in the title.
10242
*/
10243
description?: string;
10244
10245
/**
10246
* The badge to display for this webview view.
10247
* To remove the badge, set to undefined.
10248
*/
10249
badge?: ViewBadge | undefined;
10250
10251
/**
10252
* Event fired when the view is disposed.
10253
*
10254
* Views are disposed when they are explicitly hidden by a user (this happens when a user
10255
* right clicks in a view and unchecks the webview view).
10256
*
10257
* Trying to use the view after it has been disposed throws an exception.
10258
*/
10259
readonly onDidDispose: Event<void>;
10260
10261
/**
10262
* Tracks if the webview is currently visible.
10263
*
10264
* Views are visible when they are on the screen and expanded.
10265
*/
10266
readonly visible: boolean;
10267
10268
/**
10269
* Event fired when the visibility of the view changes.
10270
*
10271
* Actions that trigger a visibility change:
10272
*
10273
* - The view is collapsed or expanded.
10274
* - The user switches to a different view group in the sidebar or panel.
10275
*
10276
* Note that hiding a view using the context menu instead disposes of the view and fires `onDidDispose`.
10277
*/
10278
readonly onDidChangeVisibility: Event<void>;
10279
10280
/**
10281
* Reveal the view in the UI.
10282
*
10283
* If the view is collapsed, this will expand it.
10284
*
10285
* @param preserveFocus When `true` the view will not take focus.
10286
*/
10287
show(preserveFocus?: boolean): void;
10288
}
10289
10290
/**
10291
* Additional information the webview view being resolved.
10292
*
10293
* @param T Type of the webview's state.
10294
*/
10295
export interface WebviewViewResolveContext<T = unknown> {
10296
/**
10297
* Persisted state from the webview content.
10298
*
10299
* To save resources, the editor normally deallocates webview documents (the iframe content) that are not visible.
10300
* For example, when the user collapse a view or switches to another top level activity in the sidebar, the
10301
* {@linkcode WebviewView} itself is kept alive but the webview's underlying document is deallocated. It is recreated when
10302
* the view becomes visible again.
10303
*
10304
* You can prevent this behavior by setting {@linkcode WebviewOptions.retainContextWhenHidden retainContextWhenHidden} in the {@linkcode WebviewOptions}.
10305
* However this increases resource usage and should be avoided wherever possible. Instead, you can use
10306
* persisted state to save off a webview's state so that it can be quickly recreated as needed.
10307
*
10308
* To save off a persisted state, inside the webview call `acquireVsCodeApi().setState()` with
10309
* any json serializable object. To restore the state again, call `getState()`. For example:
10310
*
10311
* ```js
10312
* // Within the webview
10313
* const vscode = acquireVsCodeApi();
10314
*
10315
* // Get existing state
10316
* const oldState = vscode.getState() || { value: 0 };
10317
*
10318
* // Update state
10319
* setState({ value: oldState.value + 1 })
10320
* ```
10321
*
10322
* The editor ensures that the persisted state is saved correctly when a webview is hidden and across
10323
* editor restarts.
10324
*/
10325
readonly state: T | undefined;
10326
}
10327
10328
/**
10329
* Provider for creating {@linkcode WebviewView} elements.
10330
*/
10331
export interface WebviewViewProvider {
10332
/**
10333
* Resolves a webview view.
10334
*
10335
* `resolveWebviewView` is called when a view first becomes visible. This may happen when the view is
10336
* first loaded or when the user hides and then shows a view again.
10337
*
10338
* @param webviewView Webview view to restore. The provider should take ownership of this view. The
10339
* provider must set the webview's `.html` and hook up all webview events it is interested in.
10340
* @param context Additional metadata about the view being resolved.
10341
* @param token Cancellation token indicating that the view being provided is no longer needed.
10342
*
10343
* @returns Optional thenable indicating that the view has been fully resolved.
10344
*/
10345
resolveWebviewView(webviewView: WebviewView, context: WebviewViewResolveContext, token: CancellationToken): Thenable<void> | void;
10346
}
10347
10348
/**
10349
* Provider for text based custom editors.
10350
*
10351
* Text based custom editors use a {@linkcode TextDocument} as their data model. This considerably simplifies
10352
* implementing a custom editor as it allows the editor to handle many common operations such as
10353
* undo and backup. The provider is responsible for synchronizing text changes between the webview and the {@linkcode TextDocument}.
10354
*/
10355
export interface CustomTextEditorProvider {
10356
10357
/**
10358
* Resolve a custom editor for a given text resource.
10359
*
10360
* This is called when a user first opens a resource for a `CustomTextEditorProvider`, or if they reopen an
10361
* existing editor using this `CustomTextEditorProvider`.
10362
*
10363
* @param document Document for the resource to resolve.
10364
*
10365
* @param webviewPanel The webview panel used to display the editor UI for this resource.
10366
*
10367
* During resolve, the provider must fill in the initial html for the content webview panel and hook up all
10368
* the event listeners on it that it is interested in. The provider can also hold onto the {@linkcode WebviewPanel} to
10369
* use later for example in a command. See {@linkcode WebviewPanel} for additional details.
10370
*
10371
* @param token A cancellation token that indicates the result is no longer needed.
10372
*
10373
* @returns Thenable indicating that the custom editor has been resolved.
10374
*/
10375
resolveCustomTextEditor(document: TextDocument, webviewPanel: WebviewPanel, token: CancellationToken): Thenable<void> | void;
10376
}
10377
10378
/**
10379
* Represents a custom document used by a {@linkcode CustomEditorProvider}.
10380
*
10381
* Custom documents are only used within a given `CustomEditorProvider`. The lifecycle of a `CustomDocument` is
10382
* managed by the editor. When no more references remain to a `CustomDocument`, it is disposed of.
10383
*/
10384
export interface CustomDocument {
10385
/**
10386
* The associated uri for this document.
10387
*/
10388
readonly uri: Uri;
10389
10390
/**
10391
* Dispose of the custom document.
10392
*
10393
* This is invoked by the editor when there are no more references to a given `CustomDocument` (for example when
10394
* all editors associated with the document have been closed.)
10395
*/
10396
dispose(): void;
10397
}
10398
10399
/**
10400
* Event triggered by extensions to signal to the editor that an edit has occurred on an {@linkcode CustomDocument}.
10401
*
10402
* @see {@linkcode CustomEditorProvider.onDidChangeCustomDocument}.
10403
*/
10404
export interface CustomDocumentEditEvent<T extends CustomDocument = CustomDocument> {
10405
10406
/**
10407
* The document that the edit is for.
10408
*/
10409
readonly document: T;
10410
10411
/**
10412
* Undo the edit operation.
10413
*
10414
* This is invoked by the editor when the user undoes this edit. To implement `undo`, your
10415
* extension should restore the document and editor to the state they were in just before this
10416
* edit was added to the editor's internal edit stack by {@linkcode CustomEditorProvider.onDidChangeCustomDocument}.
10417
*/
10418
undo(): Thenable<void> | void;
10419
10420
/**
10421
* Redo the edit operation.
10422
*
10423
* This is invoked by the editor when the user redoes this edit. To implement `redo`, your
10424
* extension should restore the document and editor to the state they were in just after this
10425
* edit was added to the editor's internal edit stack by {@linkcode CustomEditorProvider.onDidChangeCustomDocument}.
10426
*/
10427
redo(): Thenable<void> | void;
10428
10429
/**
10430
* Display name describing the edit.
10431
*
10432
* This will be shown to users in the UI for undo/redo operations.
10433
*/
10434
readonly label?: string;
10435
}
10436
10437
/**
10438
* Event triggered by extensions to signal to the editor that the content of a {@linkcode CustomDocument}
10439
* has changed.
10440
*
10441
* @see {@linkcode CustomEditorProvider.onDidChangeCustomDocument}.
10442
*/
10443
export interface CustomDocumentContentChangeEvent<T extends CustomDocument = CustomDocument> {
10444
/**
10445
* The document that the change is for.
10446
*/
10447
readonly document: T;
10448
}
10449
10450
/**
10451
* A backup for an {@linkcode CustomDocument}.
10452
*/
10453
export interface CustomDocumentBackup {
10454
/**
10455
* Unique identifier for the backup.
10456
*
10457
* This id is passed back to your extension in {@linkcode CustomReadonlyEditorProvider.openCustomDocument openCustomDocument} when opening a custom editor from a backup.
10458
*/
10459
readonly id: string;
10460
10461
/**
10462
* Delete the current backup.
10463
*
10464
* This is called by the editor when it is clear the current backup is no longer needed, such as when a new backup
10465
* is made or when the file is saved.
10466
*/
10467
delete(): void;
10468
}
10469
10470
/**
10471
* Additional information used to implement {@linkcode CustomDocumentBackup}.
10472
*/
10473
export interface CustomDocumentBackupContext {
10474
/**
10475
* Suggested file location to write the new backup.
10476
*
10477
* Note that your extension is free to ignore this and use its own strategy for backup.
10478
*
10479
* If the editor is for a resource from the current workspace, `destination` will point to a file inside
10480
* `ExtensionContext.storagePath`. The parent folder of `destination` may not exist, so make sure to created it
10481
* before writing the backup to this location.
10482
*/
10483
readonly destination: Uri;
10484
}
10485
10486
/**
10487
* Additional information about the opening custom document.
10488
*/
10489
export interface CustomDocumentOpenContext {
10490
/**
10491
* The id of the backup to restore the document from or `undefined` if there is no backup.
10492
*
10493
* If this is provided, your extension should restore the editor from the backup instead of reading the file
10494
* from the user's workspace.
10495
*/
10496
readonly backupId: string | undefined;
10497
10498
/**
10499
* If the URI is an untitled file, this will be populated with the byte data of that file
10500
*
10501
* If this is provided, your extension should utilize this byte data rather than executing fs APIs on the URI passed in
10502
*/
10503
readonly untitledDocumentData: Uint8Array | undefined;
10504
}
10505
10506
/**
10507
* Provider for readonly custom editors that use a custom document model.
10508
*
10509
* Custom editors use {@linkcode CustomDocument} as their document model instead of a {@linkcode TextDocument}.
10510
*
10511
* You should use this type of custom editor when dealing with binary files or more complex scenarios. For simple
10512
* text based documents, use {@linkcode CustomTextEditorProvider} instead.
10513
*
10514
* @param T Type of the custom document returned by this provider.
10515
*/
10516
export interface CustomReadonlyEditorProvider<T extends CustomDocument = CustomDocument> {
10517
10518
/**
10519
* Create a new document for a given resource.
10520
*
10521
* `openCustomDocument` is called when the first time an editor for a given resource is opened. The opened
10522
* document is then passed to {@link resolveCustomEditor} so that the editor can be shown to the user.
10523
*
10524
* Already opened {@linkcode CustomDocument CustomDocuments} are re-used if the user opened additional editors. When all editors for a
10525
* given resource are closed, the {@linkcode CustomDocument CustomDocuments} is disposed of. Opening an editor at this point will
10526
* trigger another call to `openCustomDocument`.
10527
*
10528
* @param uri Uri of the document to open.
10529
* @param openContext Additional information about the opening custom document.
10530
* @param token A cancellation token that indicates the result is no longer needed.
10531
*
10532
* @returns The custom document.
10533
*/
10534
openCustomDocument(uri: Uri, openContext: CustomDocumentOpenContext, token: CancellationToken): Thenable<T> | T;
10535
10536
/**
10537
* Resolve a custom editor for a given resource.
10538
*
10539
* This is called whenever the user opens a new editor for this `CustomEditorProvider`.
10540
*
10541
* @param document Document for the resource being resolved.
10542
*
10543
* @param webviewPanel The webview panel used to display the editor UI for this resource.
10544
*
10545
* During resolve, the provider must fill in the initial html for the content webview panel and hook up all
10546
* the event listeners on it that it is interested in. The provider can also hold onto the `WebviewPanel` to
10547
* use later for example in a command. See {@linkcode WebviewPanel} for additional details.
10548
*
10549
* @param token A cancellation token that indicates the result is no longer needed.
10550
*
10551
* @returns Optional thenable indicating that the custom editor has been resolved.
10552
*/
10553
resolveCustomEditor(document: T, webviewPanel: WebviewPanel, token: CancellationToken): Thenable<void> | void;
10554
}
10555
10556
/**
10557
* Provider for editable custom editors that use a custom document model.
10558
*
10559
* Custom editors use {@linkcode CustomDocument} as their document model instead of a {@linkcode TextDocument}.
10560
* This gives extensions full control over actions such as edit, save, and backup.
10561
*
10562
* You should use this type of custom editor when dealing with binary files or more complex scenarios. For simple
10563
* text based documents, use {@linkcode CustomTextEditorProvider} instead.
10564
*
10565
* @param T Type of the custom document returned by this provider.
10566
*/
10567
export interface CustomEditorProvider<T extends CustomDocument = CustomDocument> extends CustomReadonlyEditorProvider<T> {
10568
/**
10569
* Signal that an edit has occurred inside a custom editor.
10570
*
10571
* This event must be fired by your extension whenever an edit happens in a custom editor. An edit can be
10572
* anything from changing some text, to cropping an image, to reordering a list. Your extension is free to
10573
* define what an edit is and what data is stored on each edit.
10574
*
10575
* Firing {@linkcode CustomEditorProvider.onDidChangeCustomDocument onDidChangeCustomDocument} causes the
10576
* editors to be marked as being dirty. This is cleared when the user either saves or reverts the file.
10577
*
10578
* Editors that support undo/redo must fire a {@linkcode CustomDocumentEditEvent} whenever an edit happens. This allows
10579
* users to undo and redo the edit using the editor's standard keyboard shortcuts. The editor will also mark
10580
* the editor as no longer being dirty if the user undoes all edits to the last saved state.
10581
*
10582
* Editors that support editing but cannot use the editor's standard undo/redo mechanism must fire a {@linkcode CustomDocumentContentChangeEvent}.
10583
* The only way for a user to clear the dirty state of an editor that does not support undo/redo is to either
10584
* `save` or `revert` the file.
10585
*
10586
* An editor should only ever fire {@linkcode CustomDocumentEditEvent} events, or only ever fire {@linkcode CustomDocumentContentChangeEvent} events.
10587
*/
10588
readonly onDidChangeCustomDocument: Event<CustomDocumentEditEvent<T>> | Event<CustomDocumentContentChangeEvent<T>>;
10589
10590
/**
10591
* Save a custom document.
10592
*
10593
* This method is invoked by the editor when the user saves a custom editor. This can happen when the user
10594
* triggers save while the custom editor is active, by commands such as `save all`, or by auto save if enabled.
10595
*
10596
* The implementer must persist the custom editor. This usually means writing the
10597
* file data for the custom document to disk. After {@linkcode saveCustomDocument} completes, any associated
10598
* editor instances will no longer be marked as dirty.
10599
*
10600
* @param document Document to save.
10601
* @param cancellation Token that signals the save is no longer required (for example, if another save was triggered).
10602
*
10603
* @returns A {@linkcode Thenable} that saving has completed.
10604
*/
10605
saveCustomDocument(document: T, cancellation: CancellationToken): Thenable<void>;
10606
10607
/**
10608
* Save a custom document to a different location.
10609
*
10610
* This method is invoked by the editor when the user triggers 'save as' on a custom editor. The implementer must
10611
* persist the custom editor to {@linkcode destination}.
10612
*
10613
* When the user accepts save as, the current editor is be replaced by an non-dirty editor for the newly saved file.
10614
*
10615
* @param document Document to save.
10616
* @param destination Location to save to.
10617
* @param cancellation Token that signals the save is no longer required.
10618
*
10619
* @returns A {@linkcode Thenable} signaling that saving has completed.
10620
*/
10621
saveCustomDocumentAs(document: T, destination: Uri, cancellation: CancellationToken): Thenable<void>;
10622
10623
/**
10624
* Revert a custom document to its last saved state.
10625
*
10626
* This method is invoked by the editor when the user triggers `File: Revert File` in a custom editor. (Note that
10627
* this is only used using the editor's `File: Revert File` command and not on a `git revert` of the file).
10628
*
10629
* The implementer must make sure all editor instances (webviews) for {@linkcode document}
10630
* are displaying the document in the same state is saved in. This usually means reloading the file from the
10631
* workspace.
10632
*
10633
* @param document Document to revert.
10634
* @param cancellation Token that signals the revert is no longer required.
10635
*
10636
* @returns A {@linkcode Thenable} signaling that the revert has completed.
10637
*/
10638
revertCustomDocument(document: T, cancellation: CancellationToken): Thenable<void>;
10639
10640
/**
10641
* Back up a dirty custom document.
10642
*
10643
* Backups are used for hot exit and to prevent data loss. Your {@linkcode backupCustomDocument} method should persist the resource in
10644
* its current state, i.e. with the edits applied. Most commonly this means saving the resource to disk in
10645
* the `ExtensionContext.storagePath`. When the editor reloads and your custom editor is opened for a resource,
10646
* your extension should first check to see if any backups exist for the resource. If there is a backup, your
10647
* extension should load the file contents from there instead of from the resource in the workspace.
10648
*
10649
* {@linkcode backupCustomDocument} is triggered approximately one second after the user stops editing the document. If the user
10650
* rapidly edits the document, {@linkcode backupCustomDocument} will not be invoked until the editing stops.
10651
*
10652
* {@linkcode backupCustomDocument} is not invoked when `auto save` is enabled (since auto save already persists the resource).
10653
*
10654
* @param document Document to backup.
10655
* @param context Information that can be used to backup the document.
10656
* @param cancellation Token that signals the current backup since a new backup is coming in. It is up to your
10657
* extension to decided how to respond to cancellation. If for example your extension is backing up a large file
10658
* in an operation that takes time to complete, your extension may decide to finish the ongoing backup rather
10659
* than cancelling it to ensure that the editor has some valid backup.
10660
*
10661
* @returns A {@linkcode Thenable} signaling that the backup has completed.
10662
*/
10663
backupCustomDocument(document: T, context: CustomDocumentBackupContext, cancellation: CancellationToken): Thenable<CustomDocumentBackup>;
10664
}
10665
10666
/**
10667
* The clipboard provides read and write access to the system's clipboard.
10668
*/
10669
export interface Clipboard {
10670
10671
/**
10672
* Read the current clipboard contents as text.
10673
* @returns A thenable that resolves to a string.
10674
*/
10675
readText(): Thenable<string>;
10676
10677
/**
10678
* Writes text into the clipboard.
10679
* @returns A thenable that resolves when writing happened.
10680
*/
10681
writeText(value: string): Thenable<void>;
10682
}
10683
10684
/**
10685
* Possible kinds of UI that can use extensions.
10686
*/
10687
export enum UIKind {
10688
10689
/**
10690
* Extensions are accessed from a desktop application.
10691
*/
10692
Desktop = 1,
10693
10694
/**
10695
* Extensions are accessed from a web browser.
10696
*/
10697
Web = 2
10698
}
10699
10700
/**
10701
* Log levels
10702
*/
10703
export enum LogLevel {
10704
10705
/**
10706
* No messages are logged with this level.
10707
*/
10708
Off = 0,
10709
10710
/**
10711
* All messages are logged with this level.
10712
*/
10713
Trace = 1,
10714
10715
/**
10716
* Messages with debug and higher log level are logged with this level.
10717
*/
10718
Debug = 2,
10719
10720
/**
10721
* Messages with info and higher log level are logged with this level.
10722
*/
10723
Info = 3,
10724
10725
/**
10726
* Messages with warning and higher log level are logged with this level.
10727
*/
10728
Warning = 4,
10729
10730
/**
10731
* Only error messages are logged with this level.
10732
*/
10733
Error = 5
10734
}
10735
10736
/**
10737
* Namespace describing the environment the editor runs in.
10738
*/
10739
export namespace env {
10740
10741
/**
10742
* The application name of the editor, like 'VS Code'.
10743
*/
10744
export const appName: string;
10745
10746
/**
10747
* The application root folder from which the editor is running.
10748
*
10749
* *Note* that the value is the empty string when running in an
10750
* environment that has no representation of an application root folder.
10751
*/
10752
export const appRoot: string;
10753
10754
/**
10755
* The hosted location of the application
10756
* On desktop this is 'desktop'
10757
* In the web this is the specified embedder i.e. 'github.dev', 'codespaces', or 'web' if the embedder
10758
* does not provide that information
10759
*/
10760
export const appHost: string;
10761
10762
/**
10763
* The custom uri scheme the editor registers to in the operating system.
10764
*/
10765
export const uriScheme: string;
10766
10767
/**
10768
* Represents the preferred user-language, like `de-CH`, `fr`, or `en-US`.
10769
*/
10770
export const language: string;
10771
10772
/**
10773
* The system clipboard.
10774
*/
10775
export const clipboard: Clipboard;
10776
10777
/**
10778
* A unique identifier for the computer.
10779
*/
10780
export const machineId: string;
10781
10782
/**
10783
* A unique identifier for the current session.
10784
* Changes each time the editor is started.
10785
*/
10786
export const sessionId: string;
10787
10788
/**
10789
* Indicates that this is a fresh install of the application.
10790
* `true` if within the first day of installation otherwise `false`.
10791
*/
10792
export const isNewAppInstall: boolean;
10793
10794
/**
10795
* Indicates whether the users has telemetry enabled.
10796
* Can be observed to determine if the extension should send telemetry.
10797
*/
10798
export const isTelemetryEnabled: boolean;
10799
10800
/**
10801
* An {@link Event} which fires when the user enabled or disables telemetry.
10802
* `true` if the user has enabled telemetry or `false` if the user has disabled telemetry.
10803
*/
10804
export const onDidChangeTelemetryEnabled: Event<boolean>;
10805
10806
/**
10807
* An {@link Event} which fires when the default shell changes. This fires with the new
10808
* shell path.
10809
*/
10810
export const onDidChangeShell: Event<string>;
10811
10812
/**
10813
* Creates a new {@link TelemetryLogger telemetry logger}.
10814
*
10815
* @param sender The telemetry sender that is used by the telemetry logger.
10816
* @param options Options for the telemetry logger.
10817
* @returns A new telemetry logger
10818
*/
10819
export function createTelemetryLogger(sender: TelemetrySender, options?: TelemetryLoggerOptions): TelemetryLogger;
10820
10821
/**
10822
* The name of a remote. Defined by extensions, popular samples are `wsl` for the Windows
10823
* Subsystem for Linux or `ssh-remote` for remotes using a secure shell.
10824
*
10825
* *Note* that the value is `undefined` when there is no remote extension host but that the
10826
* value is defined in all extension hosts (local and remote) in case a remote extension host
10827
* exists. Use {@link Extension.extensionKind} to know if
10828
* a specific extension runs remote or not.
10829
*/
10830
export const remoteName: string | undefined;
10831
10832
/**
10833
* The detected default shell for the extension host, this is overridden by the
10834
* `terminal.integrated.defaultProfile` setting for the extension host's platform. Note that in
10835
* environments that do not support a shell the value is the empty string.
10836
*/
10837
export const shell: string;
10838
10839
/**
10840
* The UI kind property indicates from which UI extensions
10841
* are accessed from. For example, extensions could be accessed
10842
* from a desktop application or a web browser.
10843
*/
10844
export const uiKind: UIKind;
10845
10846
/**
10847
* Opens a link externally using the default application. Depending on the
10848
* used scheme this can be:
10849
* * a browser (`http:`, `https:`)
10850
* * a mail client (`mailto:`)
10851
* * VSCode itself (`vscode:` from `vscode.env.uriScheme`)
10852
*
10853
* *Note* that {@linkcode window.showTextDocument showTextDocument} is the right
10854
* way to open a text document inside the editor, not this function.
10855
*
10856
* @param target The uri that should be opened.
10857
* @returns A promise indicating if open was successful.
10858
*/
10859
export function openExternal(target: Uri): Thenable<boolean>;
10860
10861
/**
10862
* Resolves a uri to a form that is accessible externally.
10863
*
10864
* #### `http:` or `https:` scheme
10865
*
10866
* Resolves an *external* uri, such as a `http:` or `https:` link, from where the extension is running to a
10867
* uri to the same resource on the client machine.
10868
*
10869
* This is a no-op if the extension is running on the client machine.
10870
*
10871
* If the extension is running remotely, this function automatically establishes a port forwarding tunnel
10872
* from the local machine to `target` on the remote and returns a local uri to the tunnel. The lifetime of
10873
* the port forwarding tunnel is managed by the editor and the tunnel can be closed by the user.
10874
*
10875
* *Note* that uris passed through `openExternal` are automatically resolved and you should not call `asExternalUri` on them.
10876
*
10877
* #### `vscode.env.uriScheme`
10878
*
10879
* Creates a uri that - if opened in a browser (e.g. via `openExternal`) - will result in a registered {@link UriHandler}
10880
* to trigger.
10881
*
10882
* Extensions should not make any assumptions about the resulting uri and should not alter it in any way.
10883
* Rather, extensions can e.g. use this uri in an authentication flow, by adding the uri as callback query
10884
* argument to the server to authenticate to.
10885
*
10886
* *Note* that if the server decides to add additional query parameters to the uri (e.g. a token or secret), it
10887
* will appear in the uri that is passed to the {@link UriHandler}.
10888
*
10889
* **Example** of an authentication flow:
10890
* ```typescript
10891
* vscode.window.registerUriHandler({
10892
* handleUri(uri: vscode.Uri): vscode.ProviderResult<void> {
10893
* if (uri.path === '/did-authenticate') {
10894
* console.log(uri.toString());
10895
* }
10896
* }
10897
* });
10898
*
10899
* const callableUri = await vscode.env.asExternalUri(vscode.Uri.parse(vscode.env.uriScheme + '://my.extension/did-authenticate'));
10900
* await vscode.env.openExternal(callableUri);
10901
* ```
10902
*
10903
* *Note* that extensions should not cache the result of `asExternalUri` as the resolved uri may become invalid due to
10904
* a system or user action — for example, in remote cases, a user may close a port forwarding tunnel that was opened by
10905
* `asExternalUri`.
10906
*
10907
* #### Any other scheme
10908
*
10909
* Any other scheme will be handled as if the provided URI is a workspace URI. In that case, the method will return
10910
* a URI which, when handled, will make the editor open the workspace.
10911
*
10912
* @returns A uri that can be used on the client machine.
10913
*/
10914
export function asExternalUri(target: Uri): Thenable<Uri>;
10915
10916
/**
10917
* The current log level of the editor.
10918
*/
10919
export const logLevel: LogLevel;
10920
10921
/**
10922
* An {@link Event} which fires when the log level of the editor changes.
10923
*/
10924
export const onDidChangeLogLevel: Event<LogLevel>;
10925
}
10926
10927
/**
10928
* Namespace for dealing with commands. In short, a command is a function with a
10929
* unique identifier. The function is sometimes also called _command handler_.
10930
*
10931
* Commands can be added to the editor using the {@link commands.registerCommand registerCommand}
10932
* and {@link commands.registerTextEditorCommand registerTextEditorCommand} functions. Commands
10933
* can be executed {@link commands.executeCommand manually} or from a UI gesture. Those are:
10934
*
10935
* * palette - Use the `commands`-section in `package.json` to make a command show in
10936
* the [command palette](https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette).
10937
* * keybinding - Use the `keybindings`-section in `package.json` to enable
10938
* [keybindings](https://code.visualstudio.com/docs/getstarted/keybindings#_advanced-customization)
10939
* for your extension.
10940
*
10941
* Commands from other extensions and from the editor itself are accessible to an extension. However,
10942
* when invoking an editor command not all argument types are supported.
10943
*
10944
* This is a sample that registers a command handler and adds an entry for that command to the palette. First
10945
* register a command handler with the identifier `extension.sayHello`.
10946
* ```javascript
10947
* commands.registerCommand('extension.sayHello', () => {
10948
* window.showInformationMessage('Hello World!');
10949
* });
10950
* ```
10951
* Second, bind the command identifier to a title under which it will show in the palette (`package.json`).
10952
* ```json
10953
* {
10954
* "contributes": {
10955
* "commands": [{
10956
* "command": "extension.sayHello",
10957
* "title": "Hello World"
10958
* }]
10959
* }
10960
* }
10961
* ```
10962
*/
10963
export namespace commands {
10964
10965
/**
10966
* Registers a command that can be invoked via a keyboard shortcut,
10967
* a menu item, an action, or directly.
10968
*
10969
* Registering a command with an existing command identifier twice
10970
* will cause an error.
10971
*
10972
* @param command A unique identifier for the command.
10973
* @param callback A command handler function.
10974
* @param thisArg The `this` context used when invoking the handler function.
10975
* @returns Disposable which unregisters this command on disposal.
10976
*/
10977
export function registerCommand(command: string, callback: (...args: any[]) => any, thisArg?: any): Disposable;
10978
10979
/**
10980
* Registers a text editor command that can be invoked via a keyboard shortcut,
10981
* a menu item, an action, or directly.
10982
*
10983
* Text editor commands are different from ordinary {@link commands.registerCommand commands} as
10984
* they only execute when there is an active editor when the command is called. Also, the
10985
* command handler of an editor command has access to the active editor and to an
10986
* {@link TextEditorEdit edit}-builder. Note that the edit-builder is only valid while the
10987
* callback executes.
10988
*
10989
* @param command A unique identifier for the command.
10990
* @param callback A command handler function with access to an {@link TextEditor editor} and an {@link TextEditorEdit edit}.
10991
* @param thisArg The `this` context used when invoking the handler function.
10992
* @returns Disposable which unregisters this command on disposal.
10993
*/
10994
export function registerTextEditorCommand(command: string, callback: (textEditor: TextEditor, edit: TextEditorEdit, ...args: any[]) => void, thisArg?: any): Disposable;
10995
10996
/**
10997
* Executes the command denoted by the given command identifier.
10998
*
10999
* * *Note 1:* When executing an editor command not all types are allowed to
11000
* be passed as arguments. Allowed are the primitive types `string`, `boolean`,
11001
* `number`, `undefined`, and `null`, as well as {@linkcode Position}, {@linkcode Range}, {@linkcode Uri} and {@linkcode Location}.
11002
* * *Note 2:* There are no restrictions when executing commands that have been contributed
11003
* by extensions.
11004
*
11005
* @param command Identifier of the command to execute.
11006
* @param rest Parameters passed to the command function.
11007
* @returns A thenable that resolves to the returned value of the given command. Returns `undefined` when
11008
* the command handler function doesn't return anything.
11009
*/
11010
export function executeCommand<T = unknown>(command: string, ...rest: any[]): Thenable<T>;
11011
11012
/**
11013
* Retrieve the list of all available commands. Commands starting with an underscore are
11014
* treated as internal commands.
11015
*
11016
* @param filterInternal Set `true` to not see internal commands (starting with an underscore)
11017
* @returns Thenable that resolves to a list of command ids.
11018
*/
11019
export function getCommands(filterInternal?: boolean): Thenable<string[]>;
11020
}
11021
11022
/**
11023
* Represents the state of a window.
11024
*/
11025
export interface WindowState {
11026
11027
/**
11028
* Whether the current window is focused.
11029
*/
11030
readonly focused: boolean;
11031
11032
/**
11033
* Whether the window has been interacted with recently. This will change
11034
* immediately on activity, or after a short time of user inactivity.
11035
*/
11036
readonly active: boolean;
11037
}
11038
11039
/**
11040
* A uri handler is responsible for handling system-wide {@link Uri uris}.
11041
*
11042
* @see {@link window.registerUriHandler}.
11043
*/
11044
export interface UriHandler {
11045
11046
/**
11047
* Handle the provided system-wide {@link Uri}.
11048
*
11049
* @see {@link window.registerUriHandler}.
11050
*/
11051
handleUri(uri: Uri): ProviderResult<void>;
11052
}
11053
11054
/**
11055
* Namespace for dealing with the current window of the editor. That is visible
11056
* and active editors, as well as, UI elements to show messages, selections, and
11057
* asking for user input.
11058
*/
11059
export namespace window {
11060
11061
/**
11062
* Represents the grid widget within the main editor area
11063
*/
11064
export const tabGroups: TabGroups;
11065
11066
/**
11067
* The currently active editor or `undefined`. The active editor is the one
11068
* that currently has focus or, when none has focus, the one that has changed
11069
* input most recently.
11070
*/
11071
export let activeTextEditor: TextEditor | undefined;
11072
11073
/**
11074
* The currently visible editors or an empty array.
11075
*/
11076
export let visibleTextEditors: readonly TextEditor[];
11077
11078
/**
11079
* An {@link Event} which fires when the {@link window.activeTextEditor active editor}
11080
* has changed. *Note* that the event also fires when the active editor changes
11081
* to `undefined`.
11082
*/
11083
export const onDidChangeActiveTextEditor: Event<TextEditor | undefined>;
11084
11085
/**
11086
* An {@link Event} which fires when the array of {@link window.visibleTextEditors visible editors}
11087
* has changed.
11088
*/
11089
export const onDidChangeVisibleTextEditors: Event<readonly TextEditor[]>;
11090
11091
/**
11092
* An {@link Event} which fires when the selection in an editor has changed.
11093
*/
11094
export const onDidChangeTextEditorSelection: Event<TextEditorSelectionChangeEvent>;
11095
11096
/**
11097
* An {@link Event} which fires when the visible ranges of an editor has changed.
11098
*/
11099
export const onDidChangeTextEditorVisibleRanges: Event<TextEditorVisibleRangesChangeEvent>;
11100
11101
/**
11102
* An {@link Event} which fires when the options of an editor have changed.
11103
*/
11104
export const onDidChangeTextEditorOptions: Event<TextEditorOptionsChangeEvent>;
11105
11106
/**
11107
* An {@link Event} which fires when the view column of an editor has changed.
11108
*/
11109
export const onDidChangeTextEditorViewColumn: Event<TextEditorViewColumnChangeEvent>;
11110
11111
/**
11112
* The currently visible {@link NotebookEditor notebook editors} or an empty array.
11113
*/
11114
export const visibleNotebookEditors: readonly NotebookEditor[];
11115
11116
/**
11117
* An {@link Event} which fires when the {@link window.visibleNotebookEditors visible notebook editors}
11118
* has changed.
11119
*/
11120
export const onDidChangeVisibleNotebookEditors: Event<readonly NotebookEditor[]>;
11121
11122
/**
11123
* The currently active {@link NotebookEditor notebook editor} or `undefined`. The active editor is the one
11124
* that currently has focus or, when none has focus, the one that has changed
11125
* input most recently.
11126
*/
11127
export const activeNotebookEditor: NotebookEditor | undefined;
11128
11129
/**
11130
* An {@link Event} which fires when the {@link window.activeNotebookEditor active notebook editor}
11131
* has changed. *Note* that the event also fires when the active editor changes
11132
* to `undefined`.
11133
*/
11134
export const onDidChangeActiveNotebookEditor: Event<NotebookEditor | undefined>;
11135
11136
/**
11137
* An {@link Event} which fires when the {@link NotebookEditor.selections notebook editor selections}
11138
* have changed.
11139
*/
11140
export const onDidChangeNotebookEditorSelection: Event<NotebookEditorSelectionChangeEvent>;
11141
11142
/**
11143
* An {@link Event} which fires when the {@link NotebookEditor.visibleRanges notebook editor visible ranges}
11144
* have changed.
11145
*/
11146
export const onDidChangeNotebookEditorVisibleRanges: Event<NotebookEditorVisibleRangesChangeEvent>;
11147
11148
/**
11149
* The currently opened terminals or an empty array.
11150
*/
11151
export const terminals: readonly Terminal[];
11152
11153
/**
11154
* The currently active terminal or `undefined`. The active terminal is the one that
11155
* currently has focus or most recently had focus.
11156
*/
11157
export const activeTerminal: Terminal | undefined;
11158
11159
/**
11160
* An {@link Event} which fires when the {@link window.activeTerminal active terminal}
11161
* has changed. *Note* that the event also fires when the active terminal changes
11162
* to `undefined`.
11163
*/
11164
export const onDidChangeActiveTerminal: Event<Terminal | undefined>;
11165
11166
/**
11167
* An {@link Event} which fires when a terminal has been created, either through the
11168
* {@link window.createTerminal createTerminal} API or commands.
11169
*/
11170
export const onDidOpenTerminal: Event<Terminal>;
11171
11172
/**
11173
* An {@link Event} which fires when a terminal is disposed.
11174
*/
11175
export const onDidCloseTerminal: Event<Terminal>;
11176
11177
/**
11178
* An {@link Event} which fires when a {@link Terminal.state terminal's state} has changed.
11179
*/
11180
export const onDidChangeTerminalState: Event<Terminal>;
11181
11182
/**
11183
* Fires when shell integration activates or one of its properties changes in a terminal.
11184
*/
11185
export const onDidChangeTerminalShellIntegration: Event<TerminalShellIntegrationChangeEvent>;
11186
11187
/**
11188
* This will be fired when a terminal command is started. This event will fire only when
11189
* [shell integration](https://code.visualstudio.com/docs/terminal/shell-integration) is
11190
* activated for the terminal.
11191
*/
11192
export const onDidStartTerminalShellExecution: Event<TerminalShellExecutionStartEvent>;
11193
11194
/**
11195
* This will be fired when a terminal command is ended. This event will fire only when
11196
* [shell integration](https://code.visualstudio.com/docs/terminal/shell-integration) is
11197
* activated for the terminal.
11198
*/
11199
export const onDidEndTerminalShellExecution: Event<TerminalShellExecutionEndEvent>;
11200
11201
/**
11202
* Represents the current window's state.
11203
*/
11204
export const state: WindowState;
11205
11206
/**
11207
* An {@link Event} which fires when the focus or activity state of the current window
11208
* changes. The value of the event represents whether the window is focused.
11209
*/
11210
export const onDidChangeWindowState: Event<WindowState>;
11211
11212
/**
11213
* Show the given document in a text editor. A {@link ViewColumn column} can be provided
11214
* to control where the editor is being shown. Might change the {@link window.activeTextEditor active editor}.
11215
*
11216
* @param document A text document to be shown.
11217
* @param column A view column in which the {@link TextEditor editor} should be shown. The default is the {@link ViewColumn.Active active}.
11218
* Columns that do not exist will be created as needed up to the maximum of {@linkcode ViewColumn.Nine}. Use {@linkcode ViewColumn.Beside}
11219
* to open the editor to the side of the currently active one.
11220
* @param preserveFocus When `true` the editor will not take focus.
11221
* @returns A promise that resolves to an {@link TextEditor editor}.
11222
*/
11223
export function showTextDocument(document: TextDocument, column?: ViewColumn, preserveFocus?: boolean): Thenable<TextEditor>;
11224
11225
/**
11226
* Show the given document in a text editor. {@link TextDocumentShowOptions Options} can be provided
11227
* to control options of the editor is being shown. Might change the {@link window.activeTextEditor active editor}.
11228
*
11229
* @param document A text document to be shown.
11230
* @param options {@link TextDocumentShowOptions Editor options} to configure the behavior of showing the {@link TextEditor editor}.
11231
* @returns A promise that resolves to an {@link TextEditor editor}.
11232
*/
11233
export function showTextDocument(document: TextDocument, options?: TextDocumentShowOptions): Thenable<TextEditor>;
11234
11235
/**
11236
* A short-hand for `openTextDocument(uri).then(document => showTextDocument(document, options))`.
11237
*
11238
* @see {@link workspace.openTextDocument}
11239
*
11240
* @param uri A resource identifier.
11241
* @param options {@link TextDocumentShowOptions Editor options} to configure the behavior of showing the {@link TextEditor editor}.
11242
* @returns A promise that resolves to an {@link TextEditor editor}.
11243
*/
11244
export function showTextDocument(uri: Uri, options?: TextDocumentShowOptions): Thenable<TextEditor>;
11245
11246
/**
11247
* Show the given {@link NotebookDocument} in a {@link NotebookEditor notebook editor}.
11248
*
11249
* @param document A text document to be shown.
11250
* @param options {@link NotebookDocumentShowOptions Editor options} to configure the behavior of showing the {@link NotebookEditor notebook editor}.
11251
*
11252
* @returns A promise that resolves to an {@link NotebookEditor notebook editor}.
11253
*/
11254
export function showNotebookDocument(document: NotebookDocument, options?: NotebookDocumentShowOptions): Thenable<NotebookEditor>;
11255
11256
/**
11257
* Create a TextEditorDecorationType that can be used to add decorations to text editors.
11258
*
11259
* @param options Rendering options for the decoration type.
11260
* @returns A new decoration type instance.
11261
*/
11262
export function createTextEditorDecorationType(options: DecorationRenderOptions): TextEditorDecorationType;
11263
11264
/**
11265
* Show an information message to users. Optionally provide an array of items which will be presented as
11266
* clickable buttons.
11267
*
11268
* @param message The message to show.
11269
* @param items A set of items that will be rendered as actions in the message.
11270
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11271
*/
11272
export function showInformationMessage<T extends string>(message: string, ...items: T[]): Thenable<T | undefined>;
11273
11274
/**
11275
* Show an information message to users. Optionally provide an array of items which will be presented as
11276
* clickable buttons.
11277
*
11278
* @param message The message to show.
11279
* @param options Configures the behaviour of the message.
11280
* @param items A set of items that will be rendered as actions in the message.
11281
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11282
*/
11283
export function showInformationMessage<T extends string>(message: string, options: MessageOptions, ...items: T[]): Thenable<T | undefined>;
11284
11285
/**
11286
* Show an information message.
11287
*
11288
* @see {@link window.showInformationMessage showInformationMessage}
11289
*
11290
* @param message The message to show.
11291
* @param items A set of items that will be rendered as actions in the message.
11292
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11293
*/
11294
export function showInformationMessage<T extends MessageItem>(message: string, ...items: T[]): Thenable<T | undefined>;
11295
11296
/**
11297
* Show an information message.
11298
*
11299
* @see {@link window.showInformationMessage showInformationMessage}
11300
*
11301
* @param message The message to show.
11302
* @param options Configures the behaviour of the message.
11303
* @param items A set of items that will be rendered as actions in the message.
11304
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11305
*/
11306
export function showInformationMessage<T extends MessageItem>(message: string, options: MessageOptions, ...items: T[]): Thenable<T | undefined>;
11307
11308
/**
11309
* Show a warning message.
11310
*
11311
* @see {@link window.showInformationMessage showInformationMessage}
11312
*
11313
* @param message The message to show.
11314
* @param items A set of items that will be rendered as actions in the message.
11315
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11316
*/
11317
export function showWarningMessage<T extends string>(message: string, ...items: T[]): Thenable<T | undefined>;
11318
11319
/**
11320
* Show a warning message.
11321
*
11322
* @see {@link window.showInformationMessage showInformationMessage}
11323
*
11324
* @param message The message to show.
11325
* @param options Configures the behaviour of the message.
11326
* @param items A set of items that will be rendered as actions in the message.
11327
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11328
*/
11329
export function showWarningMessage<T extends string>(message: string, options: MessageOptions, ...items: T[]): Thenable<T | undefined>;
11330
11331
/**
11332
* Show a warning message.
11333
*
11334
* @see {@link window.showInformationMessage showInformationMessage}
11335
*
11336
* @param message The message to show.
11337
* @param items A set of items that will be rendered as actions in the message.
11338
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11339
*/
11340
export function showWarningMessage<T extends MessageItem>(message: string, ...items: T[]): Thenable<T | undefined>;
11341
11342
/**
11343
* Show a warning message.
11344
*
11345
* @see {@link window.showInformationMessage showInformationMessage}
11346
*
11347
* @param message The message to show.
11348
* @param options Configures the behaviour of the message.
11349
* @param items A set of items that will be rendered as actions in the message.
11350
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11351
*/
11352
export function showWarningMessage<T extends MessageItem>(message: string, options: MessageOptions, ...items: T[]): Thenable<T | undefined>;
11353
11354
/**
11355
* Show an error message.
11356
*
11357
* @see {@link window.showInformationMessage showInformationMessage}
11358
*
11359
* @param message The message to show.
11360
* @param items A set of items that will be rendered as actions in the message.
11361
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11362
*/
11363
export function showErrorMessage<T extends string>(message: string, ...items: T[]): Thenable<T | undefined>;
11364
11365
/**
11366
* Show an error message.
11367
*
11368
* @see {@link window.showInformationMessage showInformationMessage}
11369
*
11370
* @param message The message to show.
11371
* @param options Configures the behaviour of the message.
11372
* @param items A set of items that will be rendered as actions in the message.
11373
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11374
*/
11375
export function showErrorMessage<T extends string>(message: string, options: MessageOptions, ...items: T[]): Thenable<T | undefined>;
11376
11377
/**
11378
* Show an error message.
11379
*
11380
* @see {@link window.showInformationMessage showInformationMessage}
11381
*
11382
* @param message The message to show.
11383
* @param items A set of items that will be rendered as actions in the message.
11384
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11385
*/
11386
export function showErrorMessage<T extends MessageItem>(message: string, ...items: T[]): Thenable<T | undefined>;
11387
11388
/**
11389
* Show an error message.
11390
*
11391
* @see {@link window.showInformationMessage showInformationMessage}
11392
*
11393
* @param message The message to show.
11394
* @param options Configures the behaviour of the message.
11395
* @param items A set of items that will be rendered as actions in the message.
11396
* @returns A thenable that resolves to the selected item or `undefined` when being dismissed.
11397
*/
11398
export function showErrorMessage<T extends MessageItem>(message: string, options: MessageOptions, ...items: T[]): Thenable<T | undefined>;
11399
11400
/**
11401
* Shows a selection list allowing multiple selections.
11402
*
11403
* @param items An array of strings, or a promise that resolves to an array of strings.
11404
* @param options Configures the behavior of the selection list.
11405
* @param token A token that can be used to signal cancellation.
11406
* @returns A thenable that resolves to the selected items or `undefined`.
11407
*/
11408
export function showQuickPick(items: readonly string[] | Thenable<readonly string[]>, options: QuickPickOptions & { /** literal-type defines return type */canPickMany: true }, token?: CancellationToken): Thenable<string[] | undefined>;
11409
11410
/**
11411
* Shows a selection list.
11412
*
11413
* @param items An array of strings, or a promise that resolves to an array of strings.
11414
* @param options Configures the behavior of the selection list.
11415
* @param token A token that can be used to signal cancellation.
11416
* @returns A thenable that resolves to the selected string or `undefined`.
11417
*/
11418
export function showQuickPick(items: readonly string[] | Thenable<readonly string[]>, options?: QuickPickOptions, token?: CancellationToken): Thenable<string | undefined>;
11419
11420
/**
11421
* Shows a selection list allowing multiple selections.
11422
*
11423
* @param items An array of items, or a promise that resolves to an array of items.
11424
* @param options Configures the behavior of the selection list.
11425
* @param token A token that can be used to signal cancellation.
11426
* @returns A thenable that resolves to the selected items or `undefined`.
11427
*/
11428
export function showQuickPick<T extends QuickPickItem>(items: readonly T[] | Thenable<readonly T[]>, options: QuickPickOptions & { /** literal-type defines return type */ canPickMany: true }, token?: CancellationToken): Thenable<T[] | undefined>;
11429
11430
/**
11431
* Shows a selection list.
11432
*
11433
* @param items An array of items, or a promise that resolves to an array of items.
11434
* @param options Configures the behavior of the selection list.
11435
* @param token A token that can be used to signal cancellation.
11436
* @returns A thenable that resolves to the selected item or `undefined`.
11437
*/
11438
export function showQuickPick<T extends QuickPickItem>(items: readonly T[] | Thenable<readonly T[]>, options?: QuickPickOptions, token?: CancellationToken): Thenable<T | undefined>;
11439
11440
/**
11441
* Shows a selection list of {@link workspace.workspaceFolders workspace folders} to pick from.
11442
* Returns `undefined` if no folder is open.
11443
*
11444
* @param options Configures the behavior of the workspace folder list.
11445
* @returns A promise that resolves to the workspace folder or `undefined`.
11446
*/
11447
export function showWorkspaceFolderPick(options?: WorkspaceFolderPickOptions): Thenable<WorkspaceFolder | undefined>;
11448
11449
/**
11450
* Shows a file open dialog to the user which allows to select a file
11451
* for opening-purposes.
11452
*
11453
* @param options Options that control the dialog.
11454
* @returns A promise that resolves to the selected resources or `undefined`.
11455
*/
11456
export function showOpenDialog(options?: OpenDialogOptions): Thenable<Uri[] | undefined>;
11457
11458
/**
11459
* Shows a file save dialog to the user which allows to select a file
11460
* for saving-purposes.
11461
*
11462
* @param options Options that control the dialog.
11463
* @returns A promise that resolves to the selected resource or `undefined`.
11464
*/
11465
export function showSaveDialog(options?: SaveDialogOptions): Thenable<Uri | undefined>;
11466
11467
/**
11468
* Opens an input box to ask the user for input.
11469
*
11470
* The returned value will be `undefined` if the input box was canceled (e.g., pressing ESC). Otherwise the
11471
* returned value will be the string typed by the user or an empty string if the user did not type
11472
* anything but dismissed the input box with OK.
11473
*
11474
* @param options Configures the behavior of the input box.
11475
* @param token A token that can be used to signal cancellation.
11476
* @returns A thenable that resolves to a string the user provided or to `undefined` in case of dismissal.
11477
*/
11478
export function showInputBox(options?: InputBoxOptions, token?: CancellationToken): Thenable<string | undefined>;
11479
11480
/**
11481
* Creates a {@link QuickPick} to let the user pick an item from a list of items of type `T`.
11482
*
11483
* Note that in many cases the more convenient {@link window.showQuickPick} is easier to use.
11484
* {@link window.createQuickPick} should be used when {@link window.showQuickPick} does not offer
11485
* the required flexibility.
11486
*
11487
* @returns A new {@link QuickPick}.
11488
*/
11489
export function createQuickPick<T extends QuickPickItem>(): QuickPick<T>;
11490
11491
/**
11492
* Creates a {@link InputBox} to let the user enter some text input.
11493
*
11494
* Note that in many cases the more convenient {@link window.showInputBox} is easier to use.
11495
* {@link window.createInputBox} should be used when {@link window.showInputBox} does not offer
11496
* the required flexibility.
11497
*
11498
* @returns A new {@link InputBox}.
11499
*/
11500
export function createInputBox(): InputBox;
11501
11502
/**
11503
* Creates a new {@link OutputChannel output channel} with the given name and language id
11504
* If language id is not provided, then **Log** is used as default language id.
11505
*
11506
* You can access the visible or active output channel as a {@link TextDocument text document} from {@link window.visibleTextEditors visible editors} or {@link window.activeTextEditor active editor}
11507
* and use the language id to contribute language features like syntax coloring, code lens etc.,
11508
*
11509
* @param name Human-readable string which will be used to represent the channel in the UI.
11510
* @param languageId The identifier of the language associated with the channel.
11511
* @returns A new output channel.
11512
*/
11513
export function createOutputChannel(name: string, languageId?: string): OutputChannel;
11514
11515
/**
11516
* Creates a new {@link LogOutputChannel log output channel} with the given name.
11517
*
11518
* @param name Human-readable string which will be used to represent the channel in the UI.
11519
* @param options Options for the log output channel.
11520
* @returns A new log output channel.
11521
*/
11522
export function createOutputChannel(name: string, options: { /** literal-type defines return type */log: true }): LogOutputChannel;
11523
11524
/**
11525
* Create and show a new webview panel.
11526
*
11527
* @param viewType Identifies the type of the webview panel.
11528
* @param title Title of the panel.
11529
* @param showOptions Where to show the webview in the editor. If preserveFocus is set, the new webview will not take focus.
11530
* @param options Settings for the new panel.
11531
*
11532
* @returns New webview panel.
11533
*/
11534
export function createWebviewPanel(viewType: string, title: string, showOptions: ViewColumn | {
11535
/**
11536
* The view column in which the {@link WebviewPanel} should be shown.
11537
*/
11538
readonly viewColumn: ViewColumn;
11539
/**
11540
* An optional flag that when `true` will stop the panel from taking focus.
11541
*/
11542
readonly preserveFocus?: boolean;
11543
}, options?: WebviewPanelOptions & WebviewOptions): WebviewPanel;
11544
11545
/**
11546
* Set a message to the status bar. This is a short hand for the more powerful
11547
* status bar {@link window.createStatusBarItem items}.
11548
*
11549
* @param text The message to show, supports icon substitution as in status bar {@link StatusBarItem.text items}.
11550
* @param hideAfterTimeout Timeout in milliseconds after which the message will be disposed.
11551
* @returns A disposable which hides the status bar message.
11552
*/
11553
export function setStatusBarMessage(text: string, hideAfterTimeout: number): Disposable;
11554
11555
/**
11556
* Set a message to the status bar. This is a short hand for the more powerful
11557
* status bar {@link window.createStatusBarItem items}.
11558
*
11559
* @param text The message to show, supports icon substitution as in status bar {@link StatusBarItem.text items}.
11560
* @param hideWhenDone Thenable on which completion (resolve or reject) the message will be disposed.
11561
* @returns A disposable which hides the status bar message.
11562
*/
11563
export function setStatusBarMessage(text: string, hideWhenDone: Thenable<any>): Disposable;
11564
11565
/**
11566
* Set a message to the status bar. This is a short hand for the more powerful
11567
* status bar {@link window.createStatusBarItem items}.
11568
*
11569
* *Note* that status bar messages stack and that they must be disposed when no
11570
* longer used.
11571
*
11572
* @param text The message to show, supports icon substitution as in status bar {@link StatusBarItem.text items}.
11573
* @returns A disposable which hides the status bar message.
11574
*/
11575
export function setStatusBarMessage(text: string): Disposable;
11576
11577
/**
11578
* Show progress in the Source Control viewlet while running the given callback and while
11579
* its returned promise isn't resolve or rejected.
11580
*
11581
* @deprecated Use `withProgress` instead.
11582
*
11583
* @param task A callback returning a promise. Progress increments can be reported with
11584
* the provided {@link Progress}-object.
11585
* @returns The thenable the task did return.
11586
*/
11587
export function withScmProgress<R>(task: (progress: Progress<number>) => Thenable<R>): Thenable<R>;
11588
11589
/**
11590
* Show progress in the editor. Progress is shown while running the given callback
11591
* and while the promise it returned isn't resolved nor rejected. The location at which
11592
* progress should show (and other details) is defined via the passed {@linkcode ProgressOptions}.
11593
*
11594
* @param options A {@linkcode ProgressOptions}-object describing the options to use for showing progress, like its location
11595
* @param task A callback returning a promise. Progress state can be reported with
11596
* the provided {@link Progress}-object.
11597
*
11598
* To report discrete progress, use `increment` to indicate how much work has been completed. Each call with
11599
* a `increment` value will be summed up and reflected as overall progress until 100% is reached (a value of
11600
* e.g. `10` accounts for `10%` of work done).
11601
* Note that currently only `ProgressLocation.Notification` is capable of showing discrete progress.
11602
*
11603
* To monitor if the operation has been cancelled by the user, use the provided {@linkcode CancellationToken}.
11604
* Note that currently only `ProgressLocation.Notification` is supporting to show a cancel button to cancel the
11605
* long running operation.
11606
*
11607
* @returns The thenable the task-callback returned.
11608
*/
11609
export function withProgress<R>(options: ProgressOptions, task: (progress: Progress<{
11610
/**
11611
* A progress message that represents a chunk of work
11612
*/
11613
message?: string;
11614
/**
11615
* An increment for discrete progress. Increments will be summed up until 100% is reached
11616
*/
11617
increment?: number;
11618
}>, token: CancellationToken) => Thenable<R>): Thenable<R>;
11619
11620
/**
11621
* Creates a status bar {@link StatusBarItem item}.
11622
*
11623
* @param id The identifier of the item. Must be unique within the extension.
11624
* @param alignment The alignment of the item.
11625
* @param priority The priority of the item. Higher values mean the item should be shown more to the left.
11626
* @returns A new status bar item.
11627
*/
11628
export function createStatusBarItem(id: string, alignment?: StatusBarAlignment, priority?: number): StatusBarItem;
11629
11630
/**
11631
* Creates a status bar {@link StatusBarItem item}.
11632
*
11633
* @see {@link createStatusBarItem} for creating a status bar item with an identifier.
11634
* @param alignment The alignment of the item.
11635
* @param priority The priority of the item. Higher values mean the item should be shown more to the left.
11636
* @returns A new status bar item.
11637
*/
11638
export function createStatusBarItem(alignment?: StatusBarAlignment, priority?: number): StatusBarItem;
11639
11640
/**
11641
* Creates a {@link Terminal} with a backing shell process. The cwd of the terminal will be the workspace
11642
* directory if it exists.
11643
*
11644
* @param name Optional human-readable string which will be used to represent the terminal in the UI.
11645
* @param shellPath Optional path to a custom shell executable to be used in the terminal.
11646
* @param shellArgs Optional args for the custom shell executable. A string can be used on Windows only which
11647
* allows specifying shell args in
11648
* [command-line format](https://msdn.microsoft.com/en-au/08dfcab2-eb6e-49a4-80eb-87d4076c98c6).
11649
* @returns A new Terminal.
11650
* @throws When running in an environment where a new process cannot be started.
11651
*/
11652
export function createTerminal(name?: string, shellPath?: string, shellArgs?: readonly string[] | string): Terminal;
11653
11654
/**
11655
* Creates a {@link Terminal} with a backing shell process.
11656
*
11657
* @param options A TerminalOptions object describing the characteristics of the new terminal.
11658
* @returns A new Terminal.
11659
* @throws When running in an environment where a new process cannot be started.
11660
*/
11661
export function createTerminal(options: TerminalOptions): Terminal;
11662
11663
/**
11664
* Creates a {@link Terminal} where an extension controls its input and output.
11665
*
11666
* @param options An {@link ExtensionTerminalOptions} object describing
11667
* the characteristics of the new terminal.
11668
* @returns A new Terminal.
11669
*/
11670
export function createTerminal(options: ExtensionTerminalOptions): Terminal;
11671
11672
/**
11673
* Register a {@link TreeDataProvider} for the view contributed using the extension point `views`.
11674
* This will allow you to contribute data to the {@link TreeView} and update if the data changes.
11675
*
11676
* **Note:** To get access to the {@link TreeView} and perform operations on it, use {@link window.createTreeView createTreeView}.
11677
*
11678
* @param viewId Id of the view contributed using the extension point `views`.
11679
* @param treeDataProvider A {@link TreeDataProvider} that provides tree data for the view
11680
* @returns A {@link Disposable disposable} that unregisters the {@link TreeDataProvider}.
11681
*/
11682
export function registerTreeDataProvider<T>(viewId: string, treeDataProvider: TreeDataProvider<T>): Disposable;
11683
11684
/**
11685
* Create a {@link TreeView} for the view contributed using the extension point `views`.
11686
* @param viewId Id of the view contributed using the extension point `views`.
11687
* @param options Options for creating the {@link TreeView}
11688
* @returns a {@link TreeView}.
11689
*/
11690
export function createTreeView<T>(viewId: string, options: TreeViewOptions<T>): TreeView<T>;
11691
11692
/**
11693
* Registers a {@link UriHandler uri handler} capable of handling system-wide {@link Uri uris}.
11694
* In case there are multiple windows open, the topmost window will handle the uri.
11695
* A uri handler is scoped to the extension it is contributed from; it will only
11696
* be able to handle uris which are directed to the extension itself. A uri must respect
11697
* the following rules:
11698
*
11699
* - The uri-scheme must be `vscode.env.uriScheme`;
11700
* - The uri-authority must be the extension id (e.g. `my.extension`);
11701
* - The uri-path, -query and -fragment parts are arbitrary.
11702
*
11703
* For example, if the `my.extension` extension registers a uri handler, it will only
11704
* be allowed to handle uris with the prefix `product-name://my.extension`.
11705
*
11706
* An extension can only register a single uri handler in its entire activation lifetime.
11707
*
11708
* * *Note:* There is an activation event `onUri` that fires when a uri directed for
11709
* the current extension is about to be handled.
11710
*
11711
* @param handler The uri handler to register for this extension.
11712
* @returns A {@link Disposable disposable} that unregisters the handler.
11713
*/
11714
export function registerUriHandler(handler: UriHandler): Disposable;
11715
11716
/**
11717
* Registers a webview panel serializer.
11718
*
11719
* Extensions that support reviving should have an `"onWebviewPanel:viewType"` activation event and
11720
* make sure that `registerWebviewPanelSerializer` is called during activation.
11721
*
11722
* Only a single serializer may be registered at a time for a given `viewType`.
11723
*
11724
* @param viewType Type of the webview panel that can be serialized.
11725
* @param serializer Webview serializer.
11726
* @returns A {@link Disposable disposable} that unregisters the serializer.
11727
*/
11728
export function registerWebviewPanelSerializer(viewType: string, serializer: WebviewPanelSerializer): Disposable;
11729
11730
/**
11731
* Register a new provider for webview views.
11732
*
11733
* @param viewId Unique id of the view. This should match the `id` from the
11734
* `views` contribution in the package.json.
11735
* @param provider Provider for the webview views.
11736
*
11737
* @returns Disposable that unregisters the provider.
11738
*/
11739
export function registerWebviewViewProvider(viewId: string, provider: WebviewViewProvider, options?: {
11740
/**
11741
* Content settings for the webview created for this view.
11742
*/
11743
readonly webviewOptions?: {
11744
/**
11745
* Controls if the webview element itself (iframe) is kept around even when the view
11746
* is no longer visible.
11747
*
11748
* Normally the webview's html context is created when the view becomes visible
11749
* and destroyed when it is hidden. Extensions that have complex state
11750
* or UI can set the `retainContextWhenHidden` to make the editor keep the webview
11751
* context around, even when the webview moves to a background tab. When a webview using
11752
* `retainContextWhenHidden` becomes hidden, its scripts and other dynamic content are suspended.
11753
* When the view becomes visible again, the context is automatically restored
11754
* in the exact same state it was in originally. You cannot send messages to a
11755
* hidden webview, even with `retainContextWhenHidden` enabled.
11756
*
11757
* `retainContextWhenHidden` has a high memory overhead and should only be used if
11758
* your view's context cannot be quickly saved and restored.
11759
*/
11760
readonly retainContextWhenHidden?: boolean;
11761
};
11762
}): Disposable;
11763
11764
/**
11765
* Register a provider for custom editors for the `viewType` contributed by the `customEditors` extension point.
11766
*
11767
* When a custom editor is opened, an `onCustomEditor:viewType` activation event is fired. Your extension
11768
* must register a {@linkcode CustomTextEditorProvider}, {@linkcode CustomReadonlyEditorProvider},
11769
* {@linkcode CustomEditorProvider}for `viewType` as part of activation.
11770
*
11771
* @param viewType Unique identifier for the custom editor provider. This should match the `viewType` from the
11772
* `customEditors` contribution point.
11773
* @param provider Provider that resolves custom editors.
11774
* @param options Options for the provider.
11775
*
11776
* @returns Disposable that unregisters the provider.
11777
*/
11778
export function registerCustomEditorProvider(viewType: string, provider: CustomTextEditorProvider | CustomReadonlyEditorProvider | CustomEditorProvider, options?: {
11779
/**
11780
* Content settings for the webview panels created for this custom editor.
11781
*/
11782
readonly webviewOptions?: WebviewPanelOptions;
11783
11784
/**
11785
* Only applies to `CustomReadonlyEditorProvider | CustomEditorProvider`.
11786
*
11787
* Indicates that the provider allows multiple editor instances to be open at the same time for
11788
* the same resource.
11789
*
11790
* By default, the editor only allows one editor instance to be open at a time for each resource. If the
11791
* user tries to open a second editor instance for the resource, the first one is instead moved to where
11792
* the second one was to be opened.
11793
*
11794
* When `supportsMultipleEditorsPerDocument` is enabled, users can split and create copies of the custom
11795
* editor. In this case, the custom editor must make sure it can properly synchronize the states of all
11796
* editor instances for a resource so that they are consistent.
11797
*/
11798
readonly supportsMultipleEditorsPerDocument?: boolean;
11799
}): Disposable;
11800
11801
/**
11802
* Register provider that enables the detection and handling of links within the terminal.
11803
* @param provider The provider that provides the terminal links.
11804
* @returns Disposable that unregisters the provider.
11805
*/
11806
export function registerTerminalLinkProvider(provider: TerminalLinkProvider): Disposable;
11807
11808
/**
11809
* Registers a provider for a contributed terminal profile.
11810
*
11811
* @param id The ID of the contributed terminal profile.
11812
* @param provider The terminal profile provider.
11813
* @returns A {@link Disposable disposable} that unregisters the provider.
11814
*/
11815
export function registerTerminalProfileProvider(id: string, provider: TerminalProfileProvider): Disposable;
11816
/**
11817
* Register a file decoration provider.
11818
*
11819
* @param provider A {@link FileDecorationProvider}.
11820
* @returns A {@link Disposable} that unregisters the provider.
11821
*/
11822
export function registerFileDecorationProvider(provider: FileDecorationProvider): Disposable;
11823
11824
/**
11825
* The currently active color theme as configured in the settings. The active
11826
* theme can be changed via the `workbench.colorTheme` setting.
11827
*/
11828
export let activeColorTheme: ColorTheme;
11829
11830
/**
11831
* An {@link Event} which fires when the active color theme is changed or has changes.
11832
*/
11833
export const onDidChangeActiveColorTheme: Event<ColorTheme>;
11834
}
11835
11836
/**
11837
* Options for creating a {@link TreeView}
11838
*/
11839
export interface TreeViewOptions<T> {
11840
11841
/**
11842
* A data provider that provides tree data.
11843
*/
11844
treeDataProvider: TreeDataProvider<T>;
11845
11846
/**
11847
* Whether to show collapse all action or not.
11848
*/
11849
showCollapseAll?: boolean;
11850
11851
/**
11852
* Whether the tree supports multi-select. When the tree supports multi-select and a command is executed from the tree,
11853
* the first argument to the command is the tree item that the command was executed on and the second argument is an
11854
* array containing all selected tree items.
11855
*/
11856
canSelectMany?: boolean;
11857
11858
/**
11859
* An optional interface to implement drag and drop in the tree view.
11860
*/
11861
dragAndDropController?: TreeDragAndDropController<T>;
11862
11863
/**
11864
* 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.
11865
* If the tree item is collapsed by default (meaning that the children haven't yet been fetched) then child checkboxes will not be updated.
11866
* To override this behavior and manage child and parent checkbox state in the extension, set this to `true`.
11867
*
11868
* Examples where {@link TreeViewOptions.manageCheckboxStateManually} is false, the default behavior:
11869
*
11870
* 1. A tree item is checked, then its children are fetched. The children will be checked.
11871
*
11872
* 2. A tree item's parent is checked. The tree item and all of it's siblings will be checked.
11873
* - [ ] Parent
11874
* - [ ] Child 1
11875
* - [ ] Child 2
11876
* When the user checks Parent, the tree will look like this:
11877
* - [x] Parent
11878
* - [x] Child 1
11879
* - [x] Child 2
11880
*
11881
* 3. A tree item and all of it's siblings are checked. The parent will be checked.
11882
* - [ ] Parent
11883
* - [ ] Child 1
11884
* - [ ] Child 2
11885
* When the user checks Child 1 and Child 2, the tree will look like this:
11886
* - [x] Parent
11887
* - [x] Child 1
11888
* - [x] Child 2
11889
*
11890
* 4. A tree item is unchecked. The parent will be unchecked.
11891
* - [x] Parent
11892
* - [x] Child 1
11893
* - [x] Child 2
11894
* When the user unchecks Child 1, the tree will look like this:
11895
* - [ ] Parent
11896
* - [ ] Child 1
11897
* - [x] Child 2
11898
*/
11899
manageCheckboxStateManually?: boolean;
11900
}
11901
11902
/**
11903
* The event that is fired when an element in the {@link TreeView} is expanded or collapsed
11904
*/
11905
export interface TreeViewExpansionEvent<T> {
11906
11907
/**
11908
* Element that is expanded or collapsed.
11909
*/
11910
readonly element: T;
11911
11912
}
11913
11914
/**
11915
* The event that is fired when there is a change in {@link TreeView.selection tree view's selection}
11916
*/
11917
export interface TreeViewSelectionChangeEvent<T> {
11918
11919
/**
11920
* Selected elements.
11921
*/
11922
readonly selection: readonly T[];
11923
11924
}
11925
11926
/**
11927
* The event that is fired when there is a change in {@link TreeView.visible tree view's visibility}
11928
*/
11929
export interface TreeViewVisibilityChangeEvent {
11930
11931
/**
11932
* `true` if the {@link TreeView tree view} is visible otherwise `false`.
11933
*/
11934
readonly visible: boolean;
11935
}
11936
11937
/**
11938
* A file associated with a {@linkcode DataTransferItem}.
11939
*
11940
* Instances of this type can only be created by the editor and not by extensions.
11941
*/
11942
export interface DataTransferFile {
11943
/**
11944
* The name of the file.
11945
*/
11946
readonly name: string;
11947
11948
/**
11949
* The full file path of the file.
11950
*
11951
* May be `undefined` on web.
11952
*/
11953
readonly uri?: Uri;
11954
11955
/**
11956
* The full file contents of the file.
11957
*/
11958
data(): Thenable<Uint8Array>;
11959
}
11960
11961
/**
11962
* Encapsulates data transferred during drag and drop operations.
11963
*/
11964
export class DataTransferItem {
11965
/**
11966
* Get a string representation of this item.
11967
*
11968
* If {@linkcode DataTransferItem.value} is an object, this returns the result of json stringifying {@linkcode DataTransferItem.value} value.
11969
*/
11970
asString(): Thenable<string>;
11971
11972
/**
11973
* Try getting the {@link DataTransferFile file} associated with this data transfer item.
11974
*
11975
* Note that the file object is only valid for the scope of the drag and drop operation.
11976
*
11977
* @returns The file for the data transfer or `undefined` if the item is either not a file or the
11978
* file data cannot be accessed.
11979
*/
11980
asFile(): DataTransferFile | undefined;
11981
11982
/**
11983
* Custom data stored on this item.
11984
*
11985
* You can use `value` to share data across operations. The original object can be retrieved so long as the extension that
11986
* created the `DataTransferItem` runs in the same extension host.
11987
*/
11988
readonly value: any;
11989
11990
/**
11991
* @param value Custom data stored on this item. Can be retrieved using {@linkcode DataTransferItem.value}.
11992
*/
11993
constructor(value: any);
11994
}
11995
11996
/**
11997
* A map containing a mapping of the mime type of the corresponding transferred data.
11998
*
11999
* Drag and drop controllers that implement {@link TreeDragAndDropController.handleDrag `handleDrag`} can add additional mime types to the
12000
* data transfer. These additional mime types will only be included in the `handleDrop` when the drag was initiated from
12001
* an element in the same drag and drop controller.
12002
*/
12003
export class DataTransfer implements Iterable<[mimeType: string, item: DataTransferItem]> {
12004
/**
12005
* Retrieves the data transfer item for a given mime type.
12006
*
12007
* @param mimeType The mime type to get the data transfer item for, such as `text/plain` or `image/png`.
12008
* Mimes type look ups are case-insensitive.
12009
*
12010
* Special mime types:
12011
* - `text/uri-list` — A string with `toString()`ed Uris separated by `\r\n`. To specify a cursor position in the file,
12012
* set the Uri's fragment to `L3,5`, where 3 is the line number and 5 is the column number.
12013
*/
12014
get(mimeType: string): DataTransferItem | undefined;
12015
12016
/**
12017
* Sets a mime type to data transfer item mapping.
12018
*
12019
* @param mimeType The mime type to set the data for. Mimes types stored in lower case, with case-insensitive looks up.
12020
* @param value The data transfer item for the given mime type.
12021
*/
12022
set(mimeType: string, value: DataTransferItem): void;
12023
12024
/**
12025
* Allows iteration through the data transfer items.
12026
*
12027
* @param callbackfn Callback for iteration through the data transfer items.
12028
* @param thisArg The `this` context used when invoking the handler function.
12029
*/
12030
forEach(callbackfn: (item: DataTransferItem, mimeType: string, dataTransfer: DataTransfer) => void, thisArg?: any): void;
12031
12032
/**
12033
* Get a new iterator with the `[mime, item]` pairs for each element in this data transfer.
12034
*/
12035
[Symbol.iterator](): IterableIterator<[mimeType: string, item: DataTransferItem]>;
12036
}
12037
12038
/**
12039
* Provides support for drag and drop in `TreeView`.
12040
*/
12041
export interface TreeDragAndDropController<T> {
12042
12043
/**
12044
* The mime types that the {@link TreeDragAndDropController.handleDrop `handleDrop`} method of this `DragAndDropController` supports.
12045
* This could be well-defined, existing, mime types, and also mime types defined by the extension.
12046
*
12047
* To support drops from trees, you will need to add the mime type of that tree.
12048
* This includes drops from within the same tree.
12049
* The mime type of a tree is recommended to be of the format `application/vnd.code.tree.<treeidlowercase>`.
12050
*
12051
* Use the special `files` mime type to support all types of dropped files {@link DataTransferFile files}, regardless of the file's actual mime type.
12052
*
12053
* To learn the mime type of a dragged item:
12054
* 1. Set up your `DragAndDropController`
12055
* 2. Use the Developer: Set Log Level... command to set the level to "Debug"
12056
* 3. Open the developer tools and drag the item with unknown mime type over your tree. The mime types will be logged to the developer console
12057
*
12058
* Note that mime types that cannot be sent to the extension will be omitted.
12059
*/
12060
readonly dropMimeTypes: readonly string[];
12061
12062
/**
12063
* The mime types that the {@link TreeDragAndDropController.handleDrag `handleDrag`} method of this `TreeDragAndDropController` may add to the tree data transfer.
12064
* This could be well-defined, existing, mime types, and also mime types defined by the extension.
12065
*
12066
* The recommended mime type of the tree (`application/vnd.code.tree.<treeidlowercase>`) will be automatically added.
12067
*/
12068
readonly dragMimeTypes: readonly string[];
12069
12070
/**
12071
* When the user starts dragging items from this `DragAndDropController`, `handleDrag` will be called.
12072
* Extensions can use `handleDrag` to add their {@link DataTransferItem `DataTransferItem`} items to the drag and drop.
12073
*
12074
* Mime types added in `handleDrag` won't be available outside the application.
12075
*
12076
* When the items are dropped on **another tree item** in **the same tree**, your `DataTransferItem` objects
12077
* will be preserved. Use the recommended mime type for the tree (`application/vnd.code.tree.<treeidlowercase>`) to add
12078
* tree objects in a data transfer. See the documentation for `DataTransferItem` for how best to take advantage of this.
12079
*
12080
* To add a data transfer item that can be dragged into the editor, use the application specific mime type "text/uri-list".
12081
* 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,
12082
* set the Uri's fragment to `L3,5`, where 3 is the line number and 5 is the column number.
12083
*
12084
* @param source The source items for the drag and drop operation.
12085
* @param dataTransfer The data transfer associated with this drag.
12086
* @param token A cancellation token indicating that drag has been cancelled.
12087
*/
12088
handleDrag?(source: readonly T[], dataTransfer: DataTransfer, token: CancellationToken): Thenable<void> | void;
12089
12090
/**
12091
* Called when a drag and drop action results in a drop on the tree that this `DragAndDropController` belongs to.
12092
*
12093
* Extensions should fire {@link TreeDataProvider.onDidChangeTreeData onDidChangeTreeData} for any elements that need to be refreshed.
12094
*
12095
* @param target The target tree element that the drop is occurring on. When undefined, the target is the root.
12096
* @param dataTransfer The data transfer items of the source of the drag.
12097
* @param token A cancellation token indicating that the drop has been cancelled.
12098
*/
12099
handleDrop?(target: T | undefined, dataTransfer: DataTransfer, token: CancellationToken): Thenable<void> | void;
12100
}
12101
12102
/**
12103
* A badge presenting a value for a view
12104
*/
12105
export interface ViewBadge {
12106
12107
/**
12108
* A label to present in tooltip for the badge.
12109
*/
12110
readonly tooltip: string;
12111
12112
/**
12113
* The value to present in the badge.
12114
*/
12115
readonly value: number;
12116
}
12117
12118
/**
12119
* An event describing the change in a tree item's checkbox state.
12120
*/
12121
export interface TreeCheckboxChangeEvent<T> {
12122
/**
12123
* The items that were checked or unchecked.
12124
*/
12125
readonly items: ReadonlyArray<[T, TreeItemCheckboxState]>;
12126
}
12127
12128
/**
12129
* Represents a Tree view
12130
*/
12131
export interface TreeView<T> extends Disposable {
12132
12133
/**
12134
* Event that is fired when an element is expanded
12135
*/
12136
readonly onDidExpandElement: Event<TreeViewExpansionEvent<T>>;
12137
12138
/**
12139
* Event that is fired when an element is collapsed
12140
*/
12141
readonly onDidCollapseElement: Event<TreeViewExpansionEvent<T>>;
12142
12143
/**
12144
* Currently selected elements.
12145
*/
12146
readonly selection: readonly T[];
12147
12148
/**
12149
* Event that is fired when the {@link TreeView.selection selection} has changed
12150
*/
12151
readonly onDidChangeSelection: Event<TreeViewSelectionChangeEvent<T>>;
12152
12153
/**
12154
* `true` if the {@link TreeView tree view} is visible otherwise `false`.
12155
*/
12156
readonly visible: boolean;
12157
12158
/**
12159
* Event that is fired when {@link TreeView.visible visibility} has changed
12160
*/
12161
readonly onDidChangeVisibility: Event<TreeViewVisibilityChangeEvent>;
12162
12163
/**
12164
* An event to signal that an element or root has either been checked or unchecked.
12165
*/
12166
readonly onDidChangeCheckboxState: Event<TreeCheckboxChangeEvent<T>>;
12167
12168
/**
12169
* An optional human-readable message that will be rendered in the view.
12170
* Setting the message to null, undefined, or empty string will remove the message from the view.
12171
*/
12172
message?: string;
12173
12174
/**
12175
* The tree view title is initially taken from the extension package.json
12176
* Changes to the title property will be properly reflected in the UI in the title of the view.
12177
*/
12178
title?: string;
12179
12180
/**
12181
* An optional human-readable description which is rendered less prominently in the title of the view.
12182
* Setting the title description to null, undefined, or empty string will remove the description from the view.
12183
*/
12184
description?: string;
12185
12186
/**
12187
* The badge to display for this TreeView.
12188
* To remove the badge, set to undefined.
12189
*/
12190
badge?: ViewBadge | undefined;
12191
12192
/**
12193
* Reveals the given element in the tree view.
12194
* If the tree view is not visible then the tree view is shown and element is revealed.
12195
*
12196
* By default revealed element is selected.
12197
* In order to not to select, set the option `select` to `false`.
12198
* In order to focus, set the option `focus` to `true`.
12199
* 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.
12200
*
12201
* * *NOTE:* You can expand only to 3 levels maximum.
12202
* * *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.
12203
*/
12204
reveal(element: T, options?: {
12205
/**
12206
* If true, then the element will be selected.
12207
*/
12208
readonly select?: boolean;
12209
/**
12210
* If true, then the element will be focused.
12211
*/
12212
readonly focus?: boolean;
12213
/**
12214
* 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
12215
*/
12216
readonly expand?: boolean | number;
12217
}): Thenable<void>;
12218
}
12219
12220
/**
12221
* A data provider that provides tree data
12222
*/
12223
export interface TreeDataProvider<T> {
12224
/**
12225
* An optional event to signal that an element or root has changed.
12226
* This will trigger the view to update the changed element/root and its children recursively (if shown).
12227
* To signal that root has changed, do not pass any argument or pass `undefined` or `null`.
12228
*/
12229
onDidChangeTreeData?: Event<T | T[] | undefined | null | void>;
12230
12231
/**
12232
* Get {@link TreeItem} representation of the `element`
12233
*
12234
* @param element The element for which {@link TreeItem} representation is asked for.
12235
* @returns TreeItem representation of the element.
12236
*/
12237
getTreeItem(element: T): TreeItem | Thenable<TreeItem>;
12238
12239
/**
12240
* Get the children of `element` or root if no element is passed.
12241
*
12242
* @param element The element from which the provider gets children. Can be `undefined`.
12243
* @returns Children of `element` or root if no element is passed.
12244
*/
12245
getChildren(element?: T): ProviderResult<T[]>;
12246
12247
/**
12248
* Optional method to return the parent of `element`.
12249
* Return `null` or `undefined` if `element` is a child of root.
12250
*
12251
* **NOTE:** This method should be implemented in order to access {@link TreeView.reveal reveal} API.
12252
*
12253
* @param element The element for which the parent has to be returned.
12254
* @returns Parent of `element`.
12255
*/
12256
getParent?(element: T): ProviderResult<T>;
12257
12258
/**
12259
* Called on hover to resolve the {@link TreeItem.tooltip TreeItem} property if it is undefined.
12260
* Called on tree item click/open to resolve the {@link TreeItem.command TreeItem} property if it is undefined.
12261
* Only properties that were undefined can be resolved in `resolveTreeItem`.
12262
* Functionality may be expanded later to include being called to resolve other missing
12263
* properties on selection and/or on open.
12264
*
12265
* Will only ever be called once per TreeItem.
12266
*
12267
* onDidChangeTreeData should not be triggered from within resolveTreeItem.
12268
*
12269
* *Note* that this function is called when tree items are already showing in the UI.
12270
* Because of that, no property that changes the presentation (label, description, etc.)
12271
* can be changed.
12272
*
12273
* @param item Undefined properties of `item` should be set then `item` should be returned.
12274
* @param element The object associated with the TreeItem.
12275
* @param token A cancellation token.
12276
* @returns The resolved tree item or a thenable that resolves to such. It is OK to return the given
12277
* `item`. When no result is returned, the given `item` will be used.
12278
*/
12279
resolveTreeItem?(item: TreeItem, element: T, token: CancellationToken): ProviderResult<TreeItem>;
12280
}
12281
12282
/**
12283
* A tree item is an UI element of the tree. Tree items are created by the {@link TreeDataProvider data provider}.
12284
*/
12285
export class TreeItem {
12286
/**
12287
* A human-readable string describing this item. When `falsy`, it is derived from {@link TreeItem.resourceUri resourceUri}.
12288
*/
12289
label?: string | TreeItemLabel;
12290
12291
/**
12292
* Optional id for the tree item that has to be unique across tree. The id is used to preserve the selection and expansion state of the tree item.
12293
*
12294
* If not provided, an id is generated using the tree item's label. **Note** that when labels change, ids will change and that selection and expansion state cannot be kept stable anymore.
12295
*/
12296
id?: string;
12297
12298
/**
12299
* The icon path or {@link ThemeIcon} for the tree item.
12300
* When `falsy`, {@link ThemeIcon.Folder Folder Theme Icon} is assigned, if item is collapsible otherwise {@link ThemeIcon.File File Theme Icon}.
12301
* 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).
12302
*/
12303
iconPath?: string | IconPath;
12304
12305
/**
12306
* A human-readable string which is rendered less prominent.
12307
* When `true`, it is derived from {@link TreeItem.resourceUri resourceUri} and when `falsy`, it is not shown.
12308
*/
12309
description?: string | boolean;
12310
12311
/**
12312
* A {@link Uri} representing the resource associated with this item.
12313
*
12314
* When set, this property is used to automatically derive several item properties if they are not explicitly provided:
12315
* - **Label**: Derived from the resource's file name when {@link TreeItem.label label} is not provided.
12316
* - **Description**: Derived from the resource's path when {@link TreeItem.description description} is set to `true`.
12317
* - **Icon**: Derived from the current file icon theme when {@link TreeItem.iconPath iconPath} is set to
12318
* {@link ThemeIcon.File} or {@link ThemeIcon.Folder}.
12319
*/
12320
resourceUri?: Uri;
12321
12322
/**
12323
* The tooltip text when you hover over this item.
12324
*/
12325
tooltip?: string | MarkdownString | undefined;
12326
12327
/**
12328
* The {@link Command} that should be executed when the tree item is selected.
12329
*
12330
* Please use `vscode.open` or `vscode.diff` as command IDs when the tree item is opening
12331
* something in the editor. Using these commands ensures that the resulting editor will
12332
* appear consistent with how other built-in trees open editors.
12333
*/
12334
command?: Command;
12335
12336
/**
12337
* {@link TreeItemCollapsibleState} of the tree item.
12338
*/
12339
collapsibleState?: TreeItemCollapsibleState;
12340
12341
/**
12342
* Context value of the tree item. This can be used to contribute item specific actions in the tree.
12343
* For example, a tree item is given a context value as `folder`. When contributing actions to `view/item/context`
12344
* using `menus` extension point, you can specify context value for key `viewItem` in `when` expression like `viewItem == folder`.
12345
* ```json
12346
* "contributes": {
12347
* "menus": {
12348
* "view/item/context": [
12349
* {
12350
* "command": "extension.deleteFolder",
12351
* "when": "viewItem == folder"
12352
* }
12353
* ]
12354
* }
12355
* }
12356
* ```
12357
* This will show action `extension.deleteFolder` only for items with `contextValue` is `folder`.
12358
*/
12359
contextValue?: string;
12360
12361
/**
12362
* Accessibility information used when screen reader interacts with this tree item.
12363
* Generally, a TreeItem has no need to set the `role` of the accessibilityInformation;
12364
* however, there are cases where a TreeItem is not displayed in a tree-like way where setting the `role` may make sense.
12365
*/
12366
accessibilityInformation?: AccessibilityInformation;
12367
12368
/**
12369
* {@link TreeItemCheckboxState TreeItemCheckboxState} of the tree item.
12370
* {@link TreeDataProvider.onDidChangeTreeData onDidChangeTreeData} should be fired when {@link TreeItem.checkboxState checkboxState} changes.
12371
*/
12372
checkboxState?: TreeItemCheckboxState | {
12373
/**
12374
* The {@link TreeItemCheckboxState} of the tree item
12375
*/
12376
readonly state: TreeItemCheckboxState;
12377
/**
12378
* A tooltip for the checkbox
12379
*/
12380
readonly tooltip?: string;
12381
/**
12382
* Accessibility information used when screen readers interact with this checkbox
12383
*/
12384
readonly accessibilityInformation?: AccessibilityInformation;
12385
};
12386
12387
/**
12388
* @param label A human-readable string describing this item
12389
* @param collapsibleState {@link TreeItemCollapsibleState} of the tree item. Default is {@link TreeItemCollapsibleState.None}
12390
*/
12391
constructor(label: string | TreeItemLabel, collapsibleState?: TreeItemCollapsibleState);
12392
12393
/**
12394
* @param resourceUri The {@link Uri} of the resource representing this item.
12395
* @param collapsibleState {@link TreeItemCollapsibleState} of the tree item. Default is {@link TreeItemCollapsibleState.None}
12396
*/
12397
constructor(resourceUri: Uri, collapsibleState?: TreeItemCollapsibleState);
12398
}
12399
12400
/**
12401
* Collapsible state of the tree item
12402
*/
12403
export enum TreeItemCollapsibleState {
12404
/**
12405
* Determines an item can be neither collapsed nor expanded. Implies it has no children.
12406
*/
12407
None = 0,
12408
/**
12409
* Determines an item is collapsed
12410
*/
12411
Collapsed = 1,
12412
/**
12413
* Determines an item is expanded
12414
*/
12415
Expanded = 2
12416
}
12417
12418
/**
12419
* Label describing the {@link TreeItem Tree item}
12420
*/
12421
export interface TreeItemLabel {
12422
12423
/**
12424
* A human-readable string describing the {@link TreeItem Tree item}.
12425
*/
12426
label: string;
12427
12428
/**
12429
* Ranges in the label to highlight. A range is defined as a tuple of two number where the
12430
* first is the inclusive start index and the second the exclusive end index
12431
*/
12432
highlights?: [number, number][];
12433
}
12434
12435
/**
12436
* Checkbox state of the tree item
12437
*/
12438
export enum TreeItemCheckboxState {
12439
/**
12440
* Determines an item is unchecked
12441
*/
12442
Unchecked = 0,
12443
/**
12444
* Determines an item is checked
12445
*/
12446
Checked = 1
12447
}
12448
12449
/**
12450
* Value-object describing what options a terminal should use.
12451
*/
12452
export interface TerminalOptions {
12453
/**
12454
* A human-readable string which will be used to represent the terminal in the UI.
12455
*/
12456
name?: string;
12457
12458
/**
12459
* A path to a custom shell executable to be used in the terminal.
12460
*/
12461
shellPath?: string;
12462
12463
/**
12464
* Args for the custom shell executable. A string can be used on Windows only which allows
12465
* specifying shell args in [command-line format](https://msdn.microsoft.com/en-au/08dfcab2-eb6e-49a4-80eb-87d4076c98c6).
12466
*/
12467
shellArgs?: string[] | string;
12468
12469
/**
12470
* A path or Uri for the current working directory to be used for the terminal.
12471
*/
12472
cwd?: string | Uri;
12473
12474
/**
12475
* Object with environment variables that will be added to the editor process.
12476
*/
12477
env?: { [key: string]: string | null | undefined };
12478
12479
/**
12480
* Whether the terminal process environment should be exactly as provided in
12481
* `TerminalOptions.env`. When this is false (default), the environment will be based on the
12482
* window's environment and also apply configured platform settings like
12483
* `terminal.integrated.env.windows` on top. When this is true, the complete environment
12484
* must be provided as nothing will be inherited from the process or any configuration.
12485
*/
12486
strictEnv?: boolean;
12487
12488
/**
12489
* When enabled the terminal will run the process as normal but not be surfaced to the user
12490
* until `Terminal.show` is called. The typical usage for this is when you need to run
12491
* something that may need interactivity but only want to tell the user about it when
12492
* interaction is needed. Note that the terminals will still be exposed to all extensions
12493
* as normal. The hidden terminals will not be restored when the workspace is next opened.
12494
*/
12495
hideFromUser?: boolean;
12496
12497
/**
12498
* A message to write to the terminal on first launch, note that this is not sent to the
12499
* process but, rather written directly to the terminal. This supports escape sequences such
12500
* a setting text style.
12501
*/
12502
message?: string;
12503
12504
/**
12505
* The icon path or {@link ThemeIcon} for the terminal.
12506
*/
12507
iconPath?: IconPath;
12508
12509
/**
12510
* The icon {@link ThemeColor} for the terminal.
12511
* The `terminal.ansi*` theme keys are
12512
* recommended for the best contrast and consistency across themes.
12513
*/
12514
color?: ThemeColor;
12515
12516
/**
12517
* The {@link TerminalLocation} or {@link TerminalEditorLocationOptions} or {@link TerminalSplitLocationOptions} for the terminal.
12518
*/
12519
location?: TerminalLocation | TerminalEditorLocationOptions | TerminalSplitLocationOptions;
12520
12521
/**
12522
* Opt-out of the default terminal persistence on restart and reload.
12523
* This will only take effect when `terminal.integrated.enablePersistentSessions` is enabled.
12524
*/
12525
isTransient?: boolean;
12526
12527
/**
12528
* The nonce to use to verify shell integration sequences are coming from a trusted source.
12529
* An example impact of UX of this is if the command line is reported with a nonce, it will
12530
* not need to verify with the user that the command line is correct before rerunning it
12531
* via the [shell integration command decoration](https://code.visualstudio.com/docs/terminal/shell-integration#_command-decorations-and-the-overview-ruler).
12532
*
12533
* This should be used if the terminal includes [custom shell integration support](https://code.visualstudio.com/docs/terminal/shell-integration#_supported-escape-sequences).
12534
* It should be set to a random GUID which will then set the `VSCODE_NONCE` environment
12535
* variable. Inside the shell, this should then be removed from the environment so as to
12536
* protect it from general access. Once that is done it can be passed through in the
12537
* relevant sequences to make them trusted.
12538
*/
12539
shellIntegrationNonce?: string;
12540
}
12541
12542
/**
12543
* Value-object describing what options a virtual process terminal should use.
12544
*/
12545
export interface ExtensionTerminalOptions {
12546
/**
12547
* A human-readable string which will be used to represent the terminal in the UI.
12548
*/
12549
name: string;
12550
12551
/**
12552
* An implementation of {@link Pseudoterminal} that allows an extension to
12553
* control a terminal.
12554
*/
12555
pty: Pseudoterminal;
12556
12557
/**
12558
* The icon path or {@link ThemeIcon} for the terminal.
12559
*/
12560
iconPath?: IconPath;
12561
12562
/**
12563
* The icon {@link ThemeColor} for the terminal.
12564
* The standard `terminal.ansi*` theme keys are
12565
* recommended for the best contrast and consistency across themes.
12566
*/
12567
color?: ThemeColor;
12568
12569
/**
12570
* The {@link TerminalLocation} or {@link TerminalEditorLocationOptions} or {@link TerminalSplitLocationOptions} for the terminal.
12571
*/
12572
location?: TerminalLocation | TerminalEditorLocationOptions | TerminalSplitLocationOptions;
12573
12574
/**
12575
* Opt-out of the default terminal persistence on restart and reload.
12576
* This will only take effect when `terminal.integrated.enablePersistentSessions` is enabled.
12577
*/
12578
isTransient?: boolean;
12579
12580
/**
12581
* The nonce to use to verify shell integration sequences are coming from a trusted source.
12582
* An example impact of UX of this is if the command line is reported with a nonce, it will
12583
* not need to verify with the user that the command line is correct before rerunning it
12584
* via the [shell integration command decoration](https://code.visualstudio.com/docs/terminal/shell-integration#_command-decorations-and-the-overview-ruler).
12585
*
12586
* This should be used if the terminal includes [custom shell integration support](https://code.visualstudio.com/docs/terminal/shell-integration#_supported-escape-sequences).
12587
* It should be set to a random GUID. Inside the {@link Pseudoterminal} implementation, this value
12588
* can be passed through in the relevant sequences to make them trusted.
12589
*/
12590
shellIntegrationNonce?: string;
12591
}
12592
12593
/**
12594
* Defines the interface of a terminal pty, enabling extensions to control a terminal.
12595
*/
12596
export interface Pseudoterminal {
12597
/**
12598
* An event that when fired will write data to the terminal. Unlike
12599
* {@link Terminal.sendText} which sends text to the underlying child
12600
* pseudo-device (the child), this will write the text to parent pseudo-device (the
12601
* _terminal_ itself).
12602
*
12603
* Note writing `\n` will just move the cursor down 1 row, you need to write `\r` as well
12604
* to move the cursor to the left-most cell.
12605
*
12606
* Events fired before {@link Pseudoterminal.open} is called will be be ignored.
12607
*
12608
* **Example:** Write red text to the terminal
12609
* ```typescript
12610
* const writeEmitter = new vscode.EventEmitter<string>();
12611
* const pty: vscode.Pseudoterminal = {
12612
* onDidWrite: writeEmitter.event,
12613
* open: () => writeEmitter.fire('\x1b[31mHello world\x1b[0m'),
12614
* close: () => {}
12615
* };
12616
* vscode.window.createTerminal({ name: 'My terminal', pty });
12617
* ```
12618
*
12619
* **Example:** Move the cursor to the 10th row and 20th column and write an asterisk
12620
* ```typescript
12621
* writeEmitter.fire('\x1b[10;20H*');
12622
* ```
12623
*/
12624
onDidWrite: Event<string>;
12625
12626
/**
12627
* An event that when fired allows overriding the {@link Pseudoterminal.setDimensions dimensions} of the
12628
* terminal. Note that when set, the overridden dimensions will only take effect when they
12629
* are lower than the actual dimensions of the terminal (ie. there will never be a scroll
12630
* bar). Set to `undefined` for the terminal to go back to the regular dimensions (fit to
12631
* the size of the panel).
12632
*
12633
* Events fired before {@link Pseudoterminal.open} is called will be be ignored.
12634
*
12635
* **Example:** Override the dimensions of a terminal to 20 columns and 10 rows
12636
* ```typescript
12637
* const dimensionsEmitter = new vscode.EventEmitter<vscode.TerminalDimensions>();
12638
* const pty: vscode.Pseudoterminal = {
12639
* onDidWrite: writeEmitter.event,
12640
* onDidOverrideDimensions: dimensionsEmitter.event,
12641
* open: () => {
12642
* dimensionsEmitter.fire({
12643
* columns: 20,
12644
* rows: 10
12645
* });
12646
* },
12647
* close: () => {}
12648
* };
12649
* vscode.window.createTerminal({ name: 'My terminal', pty });
12650
* ```
12651
*/
12652
onDidOverrideDimensions?: Event<TerminalDimensions | undefined>;
12653
12654
/**
12655
* An event that when fired will signal that the pty is closed and dispose of the terminal.
12656
*
12657
* Events fired before {@link Pseudoterminal.open} is called will be be ignored.
12658
*
12659
* A number can be used to provide an exit code for the terminal. Exit codes must be
12660
* positive and a non-zero exit codes signals failure which shows a notification for a
12661
* regular terminal and allows dependent tasks to proceed when used with the
12662
* `CustomExecution` API.
12663
*
12664
* **Example:** Exit the terminal when "y" is pressed, otherwise show a notification.
12665
* ```typescript
12666
* const writeEmitter = new vscode.EventEmitter<string>();
12667
* const closeEmitter = new vscode.EventEmitter<void>();
12668
* const pty: vscode.Pseudoterminal = {
12669
* onDidWrite: writeEmitter.event,
12670
* onDidClose: closeEmitter.event,
12671
* open: () => writeEmitter.fire('Press y to exit successfully'),
12672
* close: () => {},
12673
* handleInput: data => {
12674
* if (data !== 'y') {
12675
* vscode.window.showInformationMessage('Something went wrong');
12676
* }
12677
* closeEmitter.fire();
12678
* }
12679
* };
12680
* const terminal = vscode.window.createTerminal({ name: 'Exit example', pty });
12681
* terminal.show(true);
12682
* ```
12683
*/
12684
onDidClose?: Event<void | number>;
12685
12686
/**
12687
* An event that when fired allows changing the name of the terminal.
12688
*
12689
* Events fired before {@link Pseudoterminal.open} is called will be be ignored.
12690
*
12691
* **Example:** Change the terminal name to "My new terminal".
12692
* ```typescript
12693
* const writeEmitter = new vscode.EventEmitter<string>();
12694
* const changeNameEmitter = new vscode.EventEmitter<string>();
12695
* const pty: vscode.Pseudoterminal = {
12696
* onDidWrite: writeEmitter.event,
12697
* onDidChangeName: changeNameEmitter.event,
12698
* open: () => changeNameEmitter.fire('My new terminal'),
12699
* close: () => {}
12700
* };
12701
* vscode.window.createTerminal({ name: 'My terminal', pty });
12702
* ```
12703
*/
12704
onDidChangeName?: Event<string>;
12705
12706
/**
12707
* Implement to handle when the pty is open and ready to start firing events.
12708
*
12709
* @param initialDimensions The dimensions of the terminal, this will be undefined if the
12710
* terminal panel has not been opened before this is called.
12711
*/
12712
open(initialDimensions: TerminalDimensions | undefined): void;
12713
12714
/**
12715
* Implement to handle when the terminal is closed by an act of the user.
12716
*/
12717
close(): void;
12718
12719
/**
12720
* Implement to handle incoming keystrokes in the terminal or when an extension calls
12721
* {@link Terminal.sendText}. `data` contains the keystrokes/text serialized into
12722
* their corresponding VT sequence representation.
12723
*
12724
* @param data The incoming data.
12725
*
12726
* **Example:** Echo input in the terminal. The sequence for enter (`\r`) is translated to
12727
* CRLF to go to a new line and move the cursor to the start of the line.
12728
* ```typescript
12729
* const writeEmitter = new vscode.EventEmitter<string>();
12730
* const pty: vscode.Pseudoterminal = {
12731
* onDidWrite: writeEmitter.event,
12732
* open: () => {},
12733
* close: () => {},
12734
* handleInput: data => writeEmitter.fire(data === '\r' ? '\r\n' : data)
12735
* };
12736
* vscode.window.createTerminal({ name: 'Local echo', pty });
12737
* ```
12738
*/
12739
handleInput?(data: string): void;
12740
12741
/**
12742
* Implement to handle when the number of rows and columns that fit into the terminal panel
12743
* changes, for example when font size changes or when the panel is resized. The initial
12744
* state of a terminal's dimensions should be treated as `undefined` until this is triggered
12745
* as the size of a terminal isn't known until it shows up in the user interface.
12746
*
12747
* When dimensions are overridden by
12748
* {@link Pseudoterminal.onDidOverrideDimensions onDidOverrideDimensions}, `setDimensions` will
12749
* continue to be called with the regular panel dimensions, allowing the extension continue
12750
* to react dimension changes.
12751
*
12752
* @param dimensions The new dimensions.
12753
*/
12754
setDimensions?(dimensions: TerminalDimensions): void;
12755
}
12756
12757
/**
12758
* Represents the dimensions of a terminal.
12759
*/
12760
export interface TerminalDimensions {
12761
/**
12762
* The number of columns in the terminal.
12763
*/
12764
readonly columns: number;
12765
12766
/**
12767
* The number of rows in the terminal.
12768
*/
12769
readonly rows: number;
12770
}
12771
12772
/**
12773
* Represents how a terminal exited.
12774
*/
12775
export interface TerminalExitStatus {
12776
/**
12777
* The exit code that a terminal exited with, it can have the following values:
12778
* - Zero: the terminal process or custom execution succeeded.
12779
* - Non-zero: the terminal process or custom execution failed.
12780
* - `undefined`: the user forcibly closed the terminal or a custom execution exited
12781
* without providing an exit code.
12782
*/
12783
readonly code: number | undefined;
12784
12785
/**
12786
* The reason that triggered the exit of a terminal.
12787
*/
12788
readonly reason: TerminalExitReason;
12789
}
12790
12791
/**
12792
* Terminal exit reason kind.
12793
*/
12794
export enum TerminalExitReason {
12795
/**
12796
* Unknown reason.
12797
*/
12798
Unknown = 0,
12799
12800
/**
12801
* The window closed/reloaded.
12802
*/
12803
Shutdown = 1,
12804
12805
/**
12806
* The shell process exited.
12807
*/
12808
Process = 2,
12809
12810
/**
12811
* The user closed the terminal.
12812
*/
12813
User = 3,
12814
12815
/**
12816
* An extension disposed the terminal.
12817
*/
12818
Extension = 4,
12819
}
12820
12821
/**
12822
* A type of mutation that can be applied to an environment variable.
12823
*/
12824
export enum EnvironmentVariableMutatorType {
12825
/**
12826
* Replace the variable's existing value.
12827
*/
12828
Replace = 1,
12829
/**
12830
* Append to the end of the variable's existing value.
12831
*/
12832
Append = 2,
12833
/**
12834
* Prepend to the start of the variable's existing value.
12835
*/
12836
Prepend = 3
12837
}
12838
12839
/**
12840
* Options applied to the mutator.
12841
*/
12842
export interface EnvironmentVariableMutatorOptions {
12843
/**
12844
* Apply to the environment just before the process is created. Defaults to false.
12845
*/
12846
applyAtProcessCreation?: boolean;
12847
12848
/**
12849
* Apply to the environment in the shell integration script. Note that this _will not_ apply
12850
* the mutator if shell integration is disabled or not working for some reason. Defaults to
12851
* false.
12852
*/
12853
applyAtShellIntegration?: boolean;
12854
}
12855
12856
/**
12857
* A type of mutation and its value to be applied to an environment variable.
12858
*/
12859
export interface EnvironmentVariableMutator {
12860
/**
12861
* The type of mutation that will occur to the variable.
12862
*/
12863
readonly type: EnvironmentVariableMutatorType;
12864
12865
/**
12866
* The value to use for the variable.
12867
*/
12868
readonly value: string;
12869
12870
/**
12871
* Options applied to the mutator.
12872
*/
12873
readonly options: EnvironmentVariableMutatorOptions;
12874
}
12875
12876
/**
12877
* A collection of mutations that an extension can apply to a process environment.
12878
*/
12879
export interface EnvironmentVariableCollection extends Iterable<[variable: string, mutator: EnvironmentVariableMutator]> {
12880
/**
12881
* Whether the collection should be cached for the workspace and applied to the terminal
12882
* across window reloads. When true the collection will be active immediately such when the
12883
* window reloads. Additionally, this API will return the cached version if it exists. The
12884
* collection will be invalidated when the extension is uninstalled or when the collection
12885
* is cleared. Defaults to true.
12886
*/
12887
persistent: boolean;
12888
12889
/**
12890
* A description for the environment variable collection, this will be used to describe the
12891
* changes in the UI.
12892
*/
12893
description: string | MarkdownString | undefined;
12894
12895
/**
12896
* Replace an environment variable with a value.
12897
*
12898
* Note that an extension can only make a single change to any one variable, so this will
12899
* overwrite any previous calls to replace, append or prepend.
12900
*
12901
* @param variable The variable to replace.
12902
* @param value The value to replace the variable with.
12903
* @param options Options applied to the mutator, when no options are provided this will
12904
* default to `{ applyAtProcessCreation: true }`.
12905
*/
12906
replace(variable: string, value: string, options?: EnvironmentVariableMutatorOptions): void;
12907
12908
/**
12909
* Append a value to an environment variable.
12910
*
12911
* Note that an extension can only make a single change to any one variable, so this will
12912
* overwrite any previous calls to replace, append or prepend.
12913
*
12914
* @param variable The variable to append to.
12915
* @param value The value to append to the variable.
12916
* @param options Options applied to the mutator, when no options are provided this will
12917
* default to `{ applyAtProcessCreation: true }`.
12918
*/
12919
append(variable: string, value: string, options?: EnvironmentVariableMutatorOptions): void;
12920
12921
/**
12922
* Prepend a value to an environment variable.
12923
*
12924
* Note that an extension can only make a single change to any one variable, so this will
12925
* overwrite any previous calls to replace, append or prepend.
12926
*
12927
* @param variable The variable to prepend.
12928
* @param value The value to prepend to the variable.
12929
* @param options Options applied to the mutator, when no options are provided this will
12930
* default to `{ applyAtProcessCreation: true }`.
12931
*/
12932
prepend(variable: string, value: string, options?: EnvironmentVariableMutatorOptions): void;
12933
12934
/**
12935
* Gets the mutator that this collection applies to a variable, if any.
12936
*
12937
* @param variable The variable to get the mutator for.
12938
*/
12939
get(variable: string): EnvironmentVariableMutator | undefined;
12940
12941
/**
12942
* Iterate over each mutator in this collection.
12943
*
12944
* @param callback Function to execute for each entry.
12945
* @param thisArg The `this` context used when invoking the handler function.
12946
*/
12947
forEach(callback: (variable: string, mutator: EnvironmentVariableMutator, collection: EnvironmentVariableCollection) => any, thisArg?: any): void;
12948
12949
/**
12950
* Deletes this collection's mutator for a variable.
12951
*
12952
* @param variable The variable to delete the mutator for.
12953
*/
12954
delete(variable: string): void;
12955
12956
/**
12957
* Clears all mutators from this collection.
12958
*/
12959
clear(): void;
12960
}
12961
12962
/**
12963
* A collection of mutations that an extension can apply to a process environment. Applies to all scopes.
12964
*/
12965
export interface GlobalEnvironmentVariableCollection extends EnvironmentVariableCollection {
12966
/**
12967
* Gets scope-specific environment variable collection for the extension. This enables alterations to
12968
* terminal environment variables solely within the designated scope, and is applied in addition to (and
12969
* after) the global collection.
12970
*
12971
* Each object obtained through this method is isolated and does not impact objects for other scopes,
12972
* including the global collection.
12973
*
12974
* @param scope The scope to which the environment variable collection applies to.
12975
*
12976
* If a scope parameter is omitted, collection applicable to all relevant scopes for that parameter is
12977
* returned. For instance, if the 'workspaceFolder' parameter is not specified, the collection that applies
12978
* across all workspace folders will be returned.
12979
*
12980
* @returns Environment variable collection for the passed in scope.
12981
*/
12982
getScoped(scope: EnvironmentVariableScope): EnvironmentVariableCollection;
12983
}
12984
12985
/**
12986
* The scope object to which the environment variable collection applies.
12987
*/
12988
export interface EnvironmentVariableScope {
12989
/**
12990
* Any specific workspace folder to get collection for.
12991
*/
12992
workspaceFolder?: WorkspaceFolder;
12993
}
12994
12995
/**
12996
* A location in the editor at which progress information can be shown. It depends on the
12997
* location how progress is visually represented.
12998
*/
12999
export enum ProgressLocation {
13000
13001
/**
13002
* Show progress for the source control viewlet, as overlay for the icon and as progress bar
13003
* inside the viewlet (when visible). Neither supports cancellation nor discrete progress nor
13004
* a label to describe the operation.
13005
*/
13006
SourceControl = 1,
13007
13008
/**
13009
* Show progress in the status bar of the editor. Neither supports cancellation nor discrete progress.
13010
* Supports rendering of {@link ThemeIcon theme icons} via the `$(<name>)`-syntax in the progress label.
13011
*/
13012
Window = 10,
13013
13014
/**
13015
* Show progress as notification with an optional cancel button. Supports to show infinite and discrete
13016
* progress but does not support rendering of icons.
13017
*/
13018
Notification = 15
13019
}
13020
13021
/**
13022
* Value-object describing where and how progress should show.
13023
*/
13024
export interface ProgressOptions {
13025
13026
/**
13027
* The location at which progress should show.
13028
*/
13029
location: ProgressLocation | {
13030
/**
13031
* The identifier of a view for which progress should be shown.
13032
*/
13033
viewId: string;
13034
};
13035
13036
/**
13037
* A human-readable string which will be used to describe the
13038
* operation.
13039
*/
13040
title?: string;
13041
13042
/**
13043
* Controls if a cancel button should show to allow the user to
13044
* cancel the long running operation. Note that currently only
13045
* `ProgressLocation.Notification` is supporting to show a cancel
13046
* button.
13047
*/
13048
cancellable?: boolean;
13049
}
13050
13051
/**
13052
* The base interface for all quick input types.
13053
*
13054
* Quick input provides a unified way for extensions to interact with users through simple UI elements.
13055
* A quick input UI is initially not visible. After configuring it through its properties the extension
13056
* can make it visible by calling {@link QuickInput.show show}.
13057
*
13058
* There are several reasons why this UI might have to be hidden and the extension will be notified
13059
* through {@link QuickInput.onDidHide onDidHide}. Examples include: an explicit call to
13060
* {@link QuickInput.hide hide}, the user pressing Esc, some other input UI opening, etc.
13061
*
13062
* A user pressing Enter or some other gesture implying acceptance of the current state does not
13063
* automatically hide this UI component. It is up to the extension to decide whether to accept the
13064
* user's input and if the UI should indeed be hidden through a call to {@link QuickInput.hide hide}.
13065
*
13066
* When the extension no longer needs this input UI, it should {@link QuickInput.dispose dispose} it
13067
* to allow for freeing up any resources associated with it.
13068
*
13069
* See {@link QuickPick} and {@link InputBox} for concrete UIs.
13070
*/
13071
export interface QuickInput {
13072
13073
/**
13074
* An optional title for the input UI.
13075
*/
13076
title: string | undefined;
13077
13078
/**
13079
* An optional current step count for multi-step input flows.
13080
*/
13081
step: number | undefined;
13082
13083
/**
13084
* An optional total step count for multi-step input flows.
13085
*/
13086
totalSteps: number | undefined;
13087
13088
/**
13089
* Determines if the UI should allow for user input. Defaults to `true`.
13090
*
13091
* Change this to `false`, for example, while validating user input or loading data for the next
13092
* step in user input.
13093
*/
13094
enabled: boolean;
13095
13096
/**
13097
* Determines if the UI should show a progress indicator. Defaults to `false`.
13098
*
13099
* Change this to `true`, for example, while loading more data or validating user input.
13100
*/
13101
busy: boolean;
13102
13103
/**
13104
* Determines if the UI should stay open even when losing UI focus. Defaults to `false`.
13105
* This setting is ignored on iPad and is always `false`.
13106
*/
13107
ignoreFocusOut: boolean;
13108
13109
/**
13110
* Makes the input UI visible in its current configuration.
13111
*
13112
* Any other input UI will first fire an {@link QuickInput.onDidHide onDidHide} event.
13113
*/
13114
show(): void;
13115
13116
/**
13117
* Hides this input UI.
13118
*
13119
* This will also fire an {@link QuickInput.onDidHide onDidHide} event.
13120
*/
13121
hide(): void;
13122
13123
/**
13124
* An event signaling when this input UI is hidden.
13125
*
13126
* There are several reasons why this UI might have to be hidden and the extension will be notified
13127
* through {@link QuickInput.onDidHide onDidHide}. Examples include: an explicit call to
13128
* {@link QuickInput.hide hide}, the user pressing Esc, some other input UI opening, etc.
13129
*/
13130
readonly onDidHide: Event<void>;
13131
13132
/**
13133
* Dispose of this input UI and any associated resources.
13134
*
13135
* If it is still visible, it is first hidden. After this call the input UI is no longer functional
13136
* and no additional methods or properties on it should be accessed. Instead a new input UI should
13137
* be created.
13138
*/
13139
dispose(): void;
13140
}
13141
13142
/**
13143
* A concrete {@link QuickInput} to let the user pick an item from a list of items of type `T`.
13144
*
13145
* The items can be filtered through a filter text field and there is an option
13146
* {@link QuickPick.canSelectMany canSelectMany} to allow for selecting multiple items.
13147
*
13148
* Note that in many cases the more convenient {@link window.showQuickPick} is easier to use.
13149
* {@link window.createQuickPick} should be used when {@link window.showQuickPick} does not offer
13150
* the required flexibility.
13151
*/
13152
export interface QuickPick<T extends QuickPickItem> extends QuickInput {
13153
13154
/**
13155
* The current value of the filter text.
13156
*/
13157
value: string;
13158
13159
/**
13160
* Optional placeholder text displayed in the filter text box when no value has been entered.
13161
*/
13162
placeholder: string | undefined;
13163
13164
/**
13165
* Optional text that provides instructions or context to the user.
13166
*
13167
* The prompt is displayed below the input box and above the list of items.
13168
*/
13169
prompt: string | undefined;
13170
13171
/**
13172
* An event signaling when the value of the filter text has changed.
13173
*/
13174
readonly onDidChangeValue: Event<string>;
13175
13176
/**
13177
* An event signaling when the user indicated acceptance of the selected item(s).
13178
*/
13179
readonly onDidAccept: Event<void>;
13180
13181
/**
13182
* Buttons for actions in the UI.
13183
*/
13184
buttons: readonly QuickInputButton[];
13185
13186
/**
13187
* An event signaling when a button was triggered.
13188
*
13189
* This event fires for buttons stored in the {@link QuickPick.buttons buttons} array. This event does
13190
* not fire for buttons on a {@link QuickPickItem}.
13191
*/
13192
readonly onDidTriggerButton: Event<QuickInputButton>;
13193
13194
/**
13195
* An event signaling when a button in a particular {@link QuickPickItem} was triggered.
13196
*
13197
* This event does not fire for buttons in the title bar which are part of {@link QuickPick.buttons buttons}.
13198
*/
13199
readonly onDidTriggerItemButton: Event<QuickPickItemButtonEvent<T>>;
13200
13201
/**
13202
* Items to pick from. This can be read and updated by the extension.
13203
*/
13204
items: readonly T[];
13205
13206
/**
13207
* Determines if multiple items can be selected at the same time. Defaults to `false`.
13208
*/
13209
canSelectMany: boolean;
13210
13211
/**
13212
* Determines if the filter text should also be matched against the {@link QuickPickItem.description description} of the items. Defaults to `false`.
13213
*/
13214
matchOnDescription: boolean;
13215
13216
/**
13217
* Determines if the filter text should also be matched against the {@link QuickPickItem.detail detail} of the items. Defaults to `false`.
13218
*/
13219
matchOnDetail: boolean;
13220
13221
/**
13222
* Determines if the scroll position is maintained when the quick pick items are updated. Defaults to `false`.
13223
*/
13224
keepScrollPosition?: boolean;
13225
13226
/**
13227
* Active items. This can be read and updated by the extension.
13228
*/
13229
activeItems: readonly T[];
13230
13231
/**
13232
* An event signaling when the active items have changed.
13233
*/
13234
readonly onDidChangeActive: Event<readonly T[]>;
13235
13236
/**
13237
* Selected items. This can be read and updated by the extension.
13238
*/
13239
selectedItems: readonly T[];
13240
13241
/**
13242
* An event signaling when the selected items have changed.
13243
*/
13244
readonly onDidChangeSelection: Event<readonly T[]>;
13245
}
13246
13247
/**
13248
* A concrete {@link QuickInput} to let the user input a text value.
13249
*
13250
* Note that in many cases the more convenient {@link window.showInputBox} is easier to use.
13251
* {@link window.createInputBox} should be used when {@link window.showInputBox} does not offer
13252
* the required flexibility.
13253
*/
13254
export interface InputBox extends QuickInput {
13255
13256
/**
13257
* The current input value.
13258
*/
13259
value: string;
13260
13261
/**
13262
* Selection range in the input value.
13263
*
13264
* Defined as tuple of two numbers where the first is the inclusive start index and the second the
13265
* exclusive end index. When `undefined` the whole pre-filled value will be selected, when empty
13266
* (start equals end) only the cursor will be set, otherwise the defined range will be selected.
13267
*
13268
* This property does not get updated when the user types or makes a selection, but it can be updated
13269
* by the extension.
13270
*/
13271
valueSelection: readonly [number, number] | undefined;
13272
13273
/**
13274
* Optional placeholder text shown when no value has been input.
13275
*/
13276
placeholder: string | undefined;
13277
13278
/**
13279
* Determines if the input value should be hidden. Defaults to `false`.
13280
*/
13281
password: boolean;
13282
13283
/**
13284
* An event signaling when the value has changed.
13285
*/
13286
readonly onDidChangeValue: Event<string>;
13287
13288
/**
13289
* An event signaling when the user indicated acceptance of the input value.
13290
*/
13291
readonly onDidAccept: Event<void>;
13292
13293
/**
13294
* Buttons for actions in the UI.
13295
*/
13296
buttons: readonly QuickInputButton[];
13297
13298
/**
13299
* An event signaling when a button was triggered.
13300
*/
13301
readonly onDidTriggerButton: Event<QuickInputButton>;
13302
13303
/**
13304
* An optional prompt text providing some ask or explanation to the user.
13305
*/
13306
prompt: string | undefined;
13307
13308
/**
13309
* An optional validation message indicating a problem with the current input value.
13310
*
13311
* By setting a string, the InputBox will use a default {@link InputBoxValidationSeverity} of Error.
13312
* Returning `undefined` clears the validation message.
13313
*/
13314
validationMessage: string | InputBoxValidationMessage | undefined;
13315
}
13316
13317
/**
13318
* Specifies the location where a {@link QuickInputButton} should be rendered.
13319
*/
13320
export enum QuickInputButtonLocation {
13321
/**
13322
* The button is rendered in the title bar.
13323
*/
13324
Title = 1,
13325
13326
/**
13327
* The button is rendered inline to the right of the input box.
13328
*/
13329
Inline = 2,
13330
13331
/**
13332
* The button is rendered at the far end inside the input box.
13333
*/
13334
Input = 3
13335
}
13336
13337
/**
13338
* A button for an action in a {@link QuickPick} or {@link InputBox}.
13339
*/
13340
export interface QuickInputButton {
13341
/**
13342
* The icon for the button.
13343
*/
13344
readonly iconPath: IconPath;
13345
13346
/**
13347
* An optional tooltip displayed when hovering over the button.
13348
*/
13349
readonly tooltip?: string | undefined;
13350
13351
/**
13352
* The location where the button should be rendered.
13353
*
13354
* Defaults to {@link QuickInputButtonLocation.Title}.
13355
*
13356
* **Note:** This property is ignored if the button was added to a {@link QuickPickItem}.
13357
*/
13358
location?: QuickInputButtonLocation;
13359
13360
/**
13361
* When present, indicates that the button is a toggle button that can be checked or unchecked.
13362
*/
13363
readonly toggle?: {
13364
/**
13365
* Indicates whether the toggle button is currently checked.
13366
* This property will be updated when the button is toggled.
13367
*/
13368
checked: boolean;
13369
};
13370
}
13371
13372
/**
13373
* Predefined buttons for {@link QuickPick} and {@link InputBox}.
13374
*/
13375
export class QuickInputButtons {
13376
/**
13377
* A predefined back button for {@link QuickPick} and {@link InputBox}.
13378
*
13379
* This button should be used for consistency when a navigation back button is needed. It comes
13380
* with a predefined icon, tooltip, and location.
13381
*/
13382
static readonly Back: QuickInputButton;
13383
13384
/**
13385
* @hidden
13386
*/
13387
private constructor();
13388
}
13389
13390
/**
13391
* An event describing a button that was pressed on a {@link QuickPickItem}.
13392
*/
13393
export interface QuickPickItemButtonEvent<T extends QuickPickItem> {
13394
/**
13395
* The button that was pressed.
13396
*/
13397
readonly button: QuickInputButton;
13398
/**
13399
* The item that the button belongs to.
13400
*/
13401
readonly item: T;
13402
}
13403
13404
/**
13405
* An event describing an individual change in the text of a {@link TextDocument document}.
13406
*/
13407
export interface TextDocumentContentChangeEvent {
13408
/**
13409
* The range that got replaced.
13410
*/
13411
readonly range: Range;
13412
/**
13413
* The offset of the range that got replaced.
13414
*/
13415
readonly rangeOffset: number;
13416
/**
13417
* The length of the range that got replaced.
13418
*/
13419
readonly rangeLength: number;
13420
/**
13421
* The new text for the range.
13422
*/
13423
readonly text: string;
13424
}
13425
13426
/**
13427
* Reasons for why a text document has changed.
13428
*/
13429
export enum TextDocumentChangeReason {
13430
/** The text change is caused by an undo operation. */
13431
Undo = 1,
13432
13433
/** The text change is caused by an redo operation. */
13434
Redo = 2,
13435
}
13436
13437
/**
13438
* An event describing a transactional {@link TextDocument document} change.
13439
*/
13440
export interface TextDocumentChangeEvent {
13441
13442
/**
13443
* The affected document.
13444
*/
13445
readonly document: TextDocument;
13446
13447
/**
13448
* An array of content changes.
13449
*/
13450
readonly contentChanges: readonly TextDocumentContentChangeEvent[];
13451
13452
/**
13453
* The reason why the document was changed.
13454
* Is `undefined` if the reason is not known.
13455
*/
13456
readonly reason: TextDocumentChangeReason | undefined;
13457
}
13458
13459
/**
13460
* Represents reasons why a text document is saved.
13461
*/
13462
export enum TextDocumentSaveReason {
13463
13464
/**
13465
* Manually triggered, e.g. by the user pressing save, by starting debugging,
13466
* or by an API call.
13467
*/
13468
Manual = 1,
13469
13470
/**
13471
* Automatic after a delay.
13472
*/
13473
AfterDelay = 2,
13474
13475
/**
13476
* When the editor lost focus.
13477
*/
13478
FocusOut = 3
13479
}
13480
13481
/**
13482
* An event that is fired when a {@link TextDocument document} will be saved.
13483
*
13484
* To make modifications to the document before it is being saved, call the
13485
* {@linkcode TextDocumentWillSaveEvent.waitUntil waitUntil}-function with a thenable
13486
* that resolves to an array of {@link TextEdit text edits}.
13487
*/
13488
export interface TextDocumentWillSaveEvent {
13489
13490
/**
13491
* The document that will be saved.
13492
*/
13493
readonly document: TextDocument;
13494
13495
/**
13496
* The reason why save was triggered.
13497
*/
13498
readonly reason: TextDocumentSaveReason;
13499
13500
/**
13501
* Allows to pause the event loop and to apply {@link TextEdit pre-save-edits}.
13502
* Edits of subsequent calls to this function will be applied in order. The
13503
* edits will be *ignored* if concurrent modifications of the document happened.
13504
*
13505
* *Note:* This function can only be called during event dispatch and not
13506
* in an asynchronous manner:
13507
*
13508
* ```ts
13509
* workspace.onWillSaveTextDocument(event => {
13510
* // async, will *throw* an error
13511
* setTimeout(() => event.waitUntil(promise));
13512
*
13513
* // sync, OK
13514
* event.waitUntil(promise);
13515
* })
13516
* ```
13517
*
13518
* @param thenable A thenable that resolves to {@link TextEdit pre-save-edits}.
13519
*/
13520
waitUntil(thenable: Thenable<readonly TextEdit[]>): void;
13521
13522
/**
13523
* Allows to pause the event loop until the provided thenable resolved.
13524
*
13525
* *Note:* This function can only be called during event dispatch.
13526
*
13527
* @param thenable A thenable that delays saving.
13528
*/
13529
waitUntil(thenable: Thenable<any>): void;
13530
}
13531
13532
/**
13533
* An event that is fired when files are going to be created.
13534
*
13535
* To make modifications to the workspace before the files are created,
13536
* call the {@linkcode FileWillCreateEvent.waitUntil waitUntil}-function with a
13537
* thenable that resolves to a {@link WorkspaceEdit workspace edit}.
13538
*/
13539
export interface FileWillCreateEvent {
13540
13541
/**
13542
* A cancellation token.
13543
*/
13544
readonly token: CancellationToken;
13545
13546
/**
13547
* The files that are going to be created.
13548
*/
13549
readonly files: readonly Uri[];
13550
13551
/**
13552
* Allows to pause the event and to apply a {@link WorkspaceEdit workspace edit}.
13553
*
13554
* *Note:* This function can only be called during event dispatch and not
13555
* in an asynchronous manner:
13556
*
13557
* ```ts
13558
* workspace.onWillCreateFiles(event => {
13559
* // async, will *throw* an error
13560
* setTimeout(() => event.waitUntil(promise));
13561
*
13562
* // sync, OK
13563
* event.waitUntil(promise);
13564
* })
13565
* ```
13566
*
13567
* @param thenable A thenable that delays saving.
13568
*/
13569
waitUntil(thenable: Thenable<WorkspaceEdit>): void;
13570
13571
/**
13572
* Allows to pause the event until the provided thenable resolves.
13573
*
13574
* *Note:* This function can only be called during event dispatch.
13575
*
13576
* @param thenable A thenable that delays saving.
13577
*/
13578
waitUntil(thenable: Thenable<any>): void;
13579
}
13580
13581
/**
13582
* An event that is fired after files are created.
13583
*/
13584
export interface FileCreateEvent {
13585
13586
/**
13587
* The files that got created.
13588
*/
13589
readonly files: readonly Uri[];
13590
}
13591
13592
/**
13593
* An event that is fired when files are going to be deleted.
13594
*
13595
* To make modifications to the workspace before the files are deleted,
13596
* call the {@link FileWillCreateEvent.waitUntil `waitUntil`}-function with a
13597
* thenable that resolves to a {@link WorkspaceEdit workspace edit}.
13598
*/
13599
export interface FileWillDeleteEvent {
13600
13601
/**
13602
* A cancellation token.
13603
*/
13604
readonly token: CancellationToken;
13605
13606
/**
13607
* The files that are going to be deleted.
13608
*/
13609
readonly files: readonly Uri[];
13610
13611
/**
13612
* Allows to pause the event and to apply a {@link WorkspaceEdit workspace edit}.
13613
*
13614
* *Note:* This function can only be called during event dispatch and not
13615
* in an asynchronous manner:
13616
*
13617
* ```ts
13618
* workspace.onWillCreateFiles(event => {
13619
* // async, will *throw* an error
13620
* setTimeout(() => event.waitUntil(promise));
13621
*
13622
* // sync, OK
13623
* event.waitUntil(promise);
13624
* })
13625
* ```
13626
*
13627
* @param thenable A thenable that delays saving.
13628
*/
13629
waitUntil(thenable: Thenable<WorkspaceEdit>): void;
13630
13631
/**
13632
* Allows to pause the event until the provided thenable resolves.
13633
*
13634
* *Note:* This function can only be called during event dispatch.
13635
*
13636
* @param thenable A thenable that delays saving.
13637
*/
13638
waitUntil(thenable: Thenable<any>): void;
13639
}
13640
13641
/**
13642
* An event that is fired after files are deleted.
13643
*/
13644
export interface FileDeleteEvent {
13645
13646
/**
13647
* The files that got deleted.
13648
*/
13649
readonly files: readonly Uri[];
13650
}
13651
13652
/**
13653
* An event that is fired when files are going to be renamed.
13654
*
13655
* To make modifications to the workspace before the files are renamed,
13656
* call the {@link FileWillCreateEvent.waitUntil `waitUntil`}-function with a
13657
* thenable that resolves to a {@link WorkspaceEdit workspace edit}.
13658
*/
13659
export interface FileWillRenameEvent {
13660
13661
/**
13662
* A cancellation token.
13663
*/
13664
readonly token: CancellationToken;
13665
13666
/**
13667
* The files that are going to be renamed.
13668
*/
13669
readonly files: ReadonlyArray<{
13670
/**
13671
* The old uri of a file.
13672
*/
13673
readonly oldUri: Uri;
13674
/**
13675
* The new uri of a file.
13676
*/
13677
readonly newUri: Uri;
13678
}>;
13679
13680
/**
13681
* Allows to pause the event and to apply a {@link WorkspaceEdit workspace edit}.
13682
*
13683
* *Note:* This function can only be called during event dispatch and not
13684
* in an asynchronous manner:
13685
*
13686
* ```ts
13687
* workspace.onWillCreateFiles(event => {
13688
* // async, will *throw* an error
13689
* setTimeout(() => event.waitUntil(promise));
13690
*
13691
* // sync, OK
13692
* event.waitUntil(promise);
13693
* })
13694
* ```
13695
*
13696
* @param thenable A thenable that delays saving.
13697
*/
13698
waitUntil(thenable: Thenable<WorkspaceEdit>): void;
13699
13700
/**
13701
* Allows to pause the event until the provided thenable resolves.
13702
*
13703
* *Note:* This function can only be called during event dispatch.
13704
*
13705
* @param thenable A thenable that delays saving.
13706
*/
13707
waitUntil(thenable: Thenable<any>): void;
13708
}
13709
13710
/**
13711
* An event that is fired after files are renamed.
13712
*/
13713
export interface FileRenameEvent {
13714
13715
/**
13716
* The files that got renamed.
13717
*/
13718
readonly files: ReadonlyArray<{
13719
/**
13720
* The old uri of a file.
13721
*/
13722
readonly oldUri: Uri;
13723
/**
13724
* The new uri of a file.
13725
*/
13726
readonly newUri: Uri;
13727
}>;
13728
}
13729
13730
/**
13731
* An event describing a change to the set of {@link workspace.workspaceFolders workspace folders}.
13732
*/
13733
export interface WorkspaceFoldersChangeEvent {
13734
/**
13735
* Added workspace folders.
13736
*/
13737
readonly added: readonly WorkspaceFolder[];
13738
13739
/**
13740
* Removed workspace folders.
13741
*/
13742
readonly removed: readonly WorkspaceFolder[];
13743
}
13744
13745
/**
13746
* A workspace folder is one of potentially many roots opened by the editor. All workspace folders
13747
* are equal which means there is no notion of an active or primary workspace folder.
13748
*/
13749
export interface WorkspaceFolder {
13750
13751
/**
13752
* The associated uri for this workspace folder.
13753
*
13754
* *Note:* The {@link Uri}-type was intentionally chosen such that future releases of the editor can support
13755
* workspace folders that are not stored on the local disk, e.g. `ftp://server/workspaces/foo`.
13756
*/
13757
readonly uri: Uri;
13758
13759
/**
13760
* The name of this workspace folder. Defaults to
13761
* the basename of its {@link Uri.path uri-path}
13762
*/
13763
readonly name: string;
13764
13765
/**
13766
* The ordinal number of this workspace folder.
13767
*/
13768
readonly index: number;
13769
}
13770
13771
/**
13772
* Namespace for dealing with the current workspace. A workspace is the collection of one
13773
* or more folders that are opened in an editor window (instance).
13774
*
13775
* It is also possible to open an editor without a workspace. For example, when you open a
13776
* new editor window by selecting a file from your platform's File menu, you will not be
13777
* inside a workspace. In this mode, some of the editor's capabilities are reduced but you can
13778
* still open text files and edit them.
13779
*
13780
* Refer to https://code.visualstudio.com/docs/editor/workspaces for more information on
13781
* the concept of workspaces.
13782
*
13783
* The workspace offers support for {@link workspace.createFileSystemWatcher listening} to fs
13784
* events and for {@link workspace.findFiles finding} files. Both perform well and run _outside_
13785
* the editor-process so that they should be always used instead of nodejs-equivalents.
13786
*/
13787
export namespace workspace {
13788
13789
/**
13790
* A {@link FileSystem file system} instance that allows to interact with local and remote
13791
* files, e.g. `vscode.workspace.fs.readDirectory(someUri)` allows to retrieve all entries
13792
* of a directory or `vscode.workspace.fs.stat(anotherUri)` returns the meta data for a
13793
* file.
13794
*/
13795
export const fs: FileSystem;
13796
13797
/**
13798
* The uri of the first entry of {@linkcode workspace.workspaceFolders workspaceFolders}
13799
* as `string`. `undefined` if there is no first entry.
13800
*
13801
* Refer to https://code.visualstudio.com/docs/editor/workspaces for more information
13802
* on workspaces.
13803
*
13804
* @deprecated Use {@linkcode workspace.workspaceFolders workspaceFolders} instead.
13805
*/
13806
export const rootPath: string | undefined;
13807
13808
/**
13809
* List of workspace folders (0-N) that are open in the editor. `undefined` when no workspace
13810
* has been opened.
13811
*
13812
* Refer to https://code.visualstudio.com/docs/editor/workspaces for more information
13813
* on workspaces.
13814
*/
13815
export const workspaceFolders: readonly WorkspaceFolder[] | undefined;
13816
13817
/**
13818
* The name of the workspace. `undefined` when no workspace
13819
* has been opened.
13820
*
13821
* Refer to https://code.visualstudio.com/docs/editor/workspaces for more information on
13822
* the concept of workspaces.
13823
*/
13824
export const name: string | undefined;
13825
13826
/**
13827
* The location of the workspace file, for example:
13828
*
13829
* `file:///Users/name/Development/myProject.code-workspace`
13830
*
13831
* or
13832
*
13833
* `untitled:1555503116870`
13834
*
13835
* for a workspace that is untitled and not yet saved.
13836
*
13837
* Depending on the workspace that is opened, the value will be:
13838
* * `undefined` when no workspace is opened
13839
* * the path of the workspace file as `Uri` otherwise. if the workspace
13840
* is untitled, the returned URI will use the `untitled:` scheme
13841
*
13842
* The location can e.g. be used with the `vscode.openFolder` command to
13843
* open the workspace again after it has been closed.
13844
*
13845
* **Example:**
13846
* ```typescript
13847
* vscode.commands.executeCommand('vscode.openFolder', uriOfWorkspace);
13848
* ```
13849
*
13850
* Refer to https://code.visualstudio.com/docs/editor/workspaces for more information on
13851
* the concept of workspaces.
13852
*
13853
* **Note:** it is not advised to use `workspace.workspaceFile` to write
13854
* configuration data into the file. You can use `workspace.getConfiguration().update()`
13855
* for that purpose which will work both when a single folder is opened as
13856
* well as an untitled or saved workspace.
13857
*/
13858
export const workspaceFile: Uri | undefined;
13859
13860
/**
13861
* An event that is emitted when a workspace folder is added or removed.
13862
*
13863
* **Note:** this event will not fire if the first workspace folder is added, removed or changed,
13864
* because in that case the currently executing extensions (including the one that listens to this
13865
* event) will be terminated and restarted so that the (deprecated) `rootPath` property is updated
13866
* to point to the first workspace folder.
13867
*/
13868
export const onDidChangeWorkspaceFolders: Event<WorkspaceFoldersChangeEvent>;
13869
13870
/**
13871
* Returns the {@link WorkspaceFolder workspace folder} that contains a given uri.
13872
* * returns `undefined` when the given uri doesn't match any workspace folder
13873
* * returns the *input* when the given uri is a workspace folder itself
13874
*
13875
* @param uri An uri.
13876
* @returns A workspace folder or `undefined`
13877
*/
13878
export function getWorkspaceFolder(uri: Uri): WorkspaceFolder | undefined;
13879
13880
/**
13881
* Returns a path that is relative to the workspace folder or folders.
13882
*
13883
* When there are no {@link workspace.workspaceFolders workspace folders} or when the path
13884
* is not contained in them, the input is returned.
13885
*
13886
* @param pathOrUri A path or uri. When a uri is given its {@link Uri.fsPath fsPath} is used.
13887
* @param includeWorkspaceFolder When `true` and when the given path is contained inside a
13888
* workspace folder the name of the workspace is prepended. Defaults to `true` when there are
13889
* multiple workspace folders and `false` otherwise.
13890
* @returns A path relative to the root or the input.
13891
*/
13892
export function asRelativePath(pathOrUri: string | Uri, includeWorkspaceFolder?: boolean): string;
13893
13894
/**
13895
* This method replaces `deleteCount` {@link workspace.workspaceFolders workspace folders} starting at index `start`
13896
* by an optional set of `workspaceFoldersToAdd` on the `vscode.workspace.workspaceFolders` array. This "splice"
13897
* behavior can be used to add, remove and change workspace folders in a single operation.
13898
*
13899
* **Note:** in some cases calling this method may result in the currently executing extensions (including the
13900
* one that called this method) to be terminated and restarted. For example when the first workspace folder is
13901
* added, removed or changed the (deprecated) `rootPath` property is updated to point to the first workspace
13902
* folder. Another case is when transitioning from an empty or single-folder workspace into a multi-folder
13903
* workspace (see also: https://code.visualstudio.com/docs/editor/workspaces).
13904
*
13905
* Use the {@linkcode onDidChangeWorkspaceFolders onDidChangeWorkspaceFolders()} event to get notified when the
13906
* workspace folders have been updated.
13907
*
13908
* **Example:** adding a new workspace folder at the end of workspace folders
13909
* ```typescript
13910
* workspace.updateWorkspaceFolders(workspace.workspaceFolders ? workspace.workspaceFolders.length : 0, null, { uri: ...});
13911
* ```
13912
*
13913
* **Example:** removing the first workspace folder
13914
* ```typescript
13915
* workspace.updateWorkspaceFolders(0, 1);
13916
* ```
13917
*
13918
* **Example:** replacing an existing workspace folder with a new one
13919
* ```typescript
13920
* workspace.updateWorkspaceFolders(0, 1, { uri: ...});
13921
* ```
13922
*
13923
* It is valid to remove an existing workspace folder and add it again with a different name
13924
* to rename that folder.
13925
*
13926
* **Note:** it is not valid to call {@link updateWorkspaceFolders updateWorkspaceFolders()} multiple times
13927
* without waiting for the {@linkcode onDidChangeWorkspaceFolders onDidChangeWorkspaceFolders()} to fire.
13928
*
13929
* @param start the zero-based location in the list of currently opened {@link WorkspaceFolder workspace folders}
13930
* from which to start deleting workspace folders.
13931
* @param deleteCount the optional number of workspace folders to remove.
13932
* @param workspaceFoldersToAdd the optional variable set of workspace folders to add in place of the deleted ones.
13933
* Each workspace is identified with a mandatory URI and an optional name.
13934
* @returns true if the operation was successfully started and false otherwise if arguments were used that would result
13935
* in invalid workspace folder state (e.g. 2 folders with the same URI).
13936
*/
13937
export function updateWorkspaceFolders(start: number, deleteCount: number | undefined | null, ...workspaceFoldersToAdd: {
13938
/**
13939
* The uri of a workspace folder that's to be added.
13940
*/
13941
readonly uri: Uri;
13942
/**
13943
* The name of a workspace folder that's to be added.
13944
*/
13945
readonly name?: string;
13946
}[]): boolean;
13947
13948
/**
13949
* Creates a file system watcher that is notified on file events (create, change, delete)
13950
* depending on the parameters provided.
13951
*
13952
* By default, all opened {@link workspace.workspaceFolders workspace folders} will be watched
13953
* for file changes recursively.
13954
*
13955
* Additional paths can be added for file watching by providing a {@link RelativePattern} with
13956
* a `base` path to watch. If the path is a folder and the `pattern` is complex (e.g. contains
13957
* `**` or path segments), it will be watched recursively and otherwise will be watched
13958
* non-recursively (i.e. only changes to the first level of the path will be reported).
13959
*
13960
* *Note* that paths that do not exist in the file system will be monitored with a delay until
13961
* created and then watched depending on the parameters provided. If a watched path is deleted,
13962
* the watcher will suspend and not report any events until the path is created again.
13963
*
13964
* If possible, keep the use of recursive watchers to a minimum because recursive file watching
13965
* is quite resource intense.
13966
*
13967
* Providing a `string` as `globPattern` acts as convenience method for watching file events in
13968
* all opened workspace folders. It cannot be used to add more folders for file watching, nor will
13969
* it report any file events from folders that are not part of the opened workspace folders.
13970
*
13971
* *Note* that case-sensitivity of the {@link globPattern} parameter will depend on the file system
13972
* where the watcher is running: on Windows and macOS the matching will be case-insensitive and
13973
* on Linux it will be case-sensitive.
13974
*
13975
* Optionally, flags to ignore certain kinds of events can be provided.
13976
*
13977
* To stop listening to events the watcher must be disposed.
13978
*
13979
* *Note* that file events from deleting a folder may not include events for the contained files.
13980
* For example, when a folder is moved to the trash, only one event is reported because technically
13981
* this is a rename/move operation and not a delete operation for each files within.
13982
* On top of that, performance optimizations are in place to fold multiple events that all belong
13983
* to the same parent operation (e.g. delete folder) into one event for that parent. As such, if
13984
* you need to know about all deleted files, you have to watch with `**` and deal with all file
13985
* events yourself.
13986
*
13987
* *Note* that file events from recursive file watchers may be excluded based on user configuration.
13988
* The setting `files.watcherExclude` helps to reduce the overhead of file events from folders
13989
* that are known to produce many file changes at once (such as `.git` folders). As such,
13990
* it is highly recommended to watch with simple patterns that do not require recursive watchers
13991
* where the exclude settings are ignored and you have full control over the events.
13992
*
13993
* *Note* that symbolic links are not automatically followed for file watching unless the path to
13994
* watch itself is a symbolic link.
13995
*
13996
* *Note* that the file paths that are reported for having changed may have a different path casing
13997
* compared to the actual casing on disk on case-insensitive platforms (typically macOS and Windows
13998
* but not Linux). We allow a user to open a workspace folder with any desired path casing and try
13999
* to preserve that. This means:
14000
* * if the path is within any of the workspace folders, the path will match the casing of the
14001
* workspace folder up to that portion of the path and match the casing on disk for children
14002
* * if the path is outside of any of the workspace folders, the casing will match the case of the
14003
* path that was provided for watching
14004
* In the same way, symbolic links are preserved, i.e. the file event will report the path of the
14005
* symbolic link as it was provided for watching and not the target.
14006
*
14007
* ### Examples
14008
*
14009
* The basic anatomy of a file watcher is as follows:
14010
*
14011
* ```ts
14012
* const watcher = vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(<folder>, <pattern>));
14013
*
14014
* watcher.onDidChange(uri => { ... }); // listen to files being changed
14015
* watcher.onDidCreate(uri => { ... }); // listen to files/folders being created
14016
* watcher.onDidDelete(uri => { ... }); // listen to files/folders getting deleted
14017
*
14018
* watcher.dispose(); // dispose after usage
14019
* ```
14020
*
14021
* #### Workspace file watching
14022
*
14023
* If you only care about file events in a specific workspace folder:
14024
*
14025
* ```ts
14026
* vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(vscode.workspace.workspaceFolders[0], '**​/*.js'));
14027
* ```
14028
*
14029
* If you want to monitor file events across all opened workspace folders:
14030
*
14031
* ```ts
14032
* vscode.workspace.createFileSystemWatcher('**​/*.js');
14033
* ```
14034
*
14035
* *Note:* the array of workspace folders can be empty if no workspace is opened (empty window).
14036
*
14037
* #### Out of workspace file watching
14038
*
14039
* To watch a folder for changes to *.js files outside the workspace (non recursively), pass in a `Uri` to such
14040
* a folder:
14041
*
14042
* ```ts
14043
* vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(vscode.Uri.file(<path to folder outside workspace>), '*.js'));
14044
* ```
14045
*
14046
* And use a complex glob pattern to watch recursively:
14047
*
14048
* ```ts
14049
* vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(vscode.Uri.file(<path to folder outside workspace>), '**​/*.js'));
14050
* ```
14051
*
14052
* Here is an example for watching the active editor for file changes:
14053
*
14054
* ```ts
14055
* vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(vscode.window.activeTextEditor.document.uri, '*'));
14056
* ```
14057
*
14058
* @param globPattern A {@link GlobPattern glob pattern} that controls which file events the watcher should report.
14059
* @param ignoreCreateEvents Ignore when files have been created.
14060
* @param ignoreChangeEvents Ignore when files have been changed.
14061
* @param ignoreDeleteEvents Ignore when files have been deleted.
14062
* @returns A new file system watcher instance. Must be disposed when no longer needed.
14063
*/
14064
export function createFileSystemWatcher(globPattern: GlobPattern, ignoreCreateEvents?: boolean, ignoreChangeEvents?: boolean, ignoreDeleteEvents?: boolean): FileSystemWatcher;
14065
14066
/**
14067
* Find files across all {@link workspace.workspaceFolders workspace folders} in the workspace.
14068
*
14069
* @example
14070
* findFiles('**​/*.js', '**​/node_modules/**', 10)
14071
*
14072
* @param include A {@link GlobPattern glob pattern} that defines the files to search for. The glob pattern
14073
* will be matched against the file paths of resulting matches relative to their workspace. Use a {@link RelativePattern relative pattern}
14074
* to restrict the search results to a {@link WorkspaceFolder workspace folder}.
14075
* @param exclude A {@link GlobPattern glob pattern} that defines files and folders to exclude. The glob pattern
14076
* will be matched against the file paths of resulting matches relative to their workspace. When `undefined`, default file-excludes (e.g. the `files.exclude`-setting
14077
* but not `search.exclude`) will apply. When `null`, no excludes will apply.
14078
* @param maxResults An upper-bound for the result.
14079
* @param token A token that can be used to signal cancellation to the underlying search engine.
14080
* @returns A thenable that resolves to an array of resource identifiers. Will return no results if no
14081
* {@link workspace.workspaceFolders workspace folders} are opened.
14082
*/
14083
export function findFiles(include: GlobPattern, exclude?: GlobPattern | null, maxResults?: number, token?: CancellationToken): Thenable<Uri[]>;
14084
14085
/**
14086
* Saves the editor identified by the given resource and returns the resulting resource or `undefined`
14087
* if save was not successful or no editor with the given resource was found.
14088
*
14089
* **Note** that an editor with the provided resource must be opened in order to be saved.
14090
*
14091
* @param uri the associated uri for the opened editor to save.
14092
* @returns A thenable that resolves when the save operation has finished.
14093
*/
14094
export function save(uri: Uri): Thenable<Uri | undefined>;
14095
14096
/**
14097
* Saves the editor identified by the given resource to a new file name as provided by the user and
14098
* returns the resulting resource or `undefined` if save was not successful or cancelled or no editor
14099
* with the given resource was found.
14100
*
14101
* **Note** that an editor with the provided resource must be opened in order to be saved as.
14102
*
14103
* @param uri the associated uri for the opened editor to save as.
14104
* @returns A thenable that resolves when the save-as operation has finished.
14105
*/
14106
export function saveAs(uri: Uri): Thenable<Uri | undefined>;
14107
14108
/**
14109
* Save all dirty files.
14110
*
14111
* @param includeUntitled Also save files that have been created during this session.
14112
* @returns A thenable that resolves when the files have been saved. Will return `false`
14113
* for any file that failed to save.
14114
*/
14115
export function saveAll(includeUntitled?: boolean): Thenable<boolean>;
14116
14117
/**
14118
* Make changes to one or many resources or create, delete, and rename resources as defined by the given
14119
* {@link WorkspaceEdit workspace edit}.
14120
*
14121
* All changes of a workspace edit are applied in the same order in which they have been added. If
14122
* multiple textual inserts are made at the same position, these strings appear in the resulting text
14123
* in the order the 'inserts' were made, unless that are interleaved with resource edits. Invalid sequences
14124
* like 'delete file a' -> 'insert text in file a' cause failure of the operation.
14125
*
14126
* When applying a workspace edit that consists only of text edits an 'all-or-nothing'-strategy is used.
14127
* A workspace edit with resource creations or deletions aborts the operation, e.g. consecutive edits will
14128
* not be attempted, when a single edit fails.
14129
*
14130
* @param edit A workspace edit.
14131
* @param metadata Optional {@link WorkspaceEditMetadata metadata} for the edit.
14132
* @returns A thenable that resolves when the edit could be applied.
14133
*/
14134
export function applyEdit(edit: WorkspaceEdit, metadata?: WorkspaceEditMetadata): Thenable<boolean>;
14135
14136
/**
14137
* All text documents currently known to the editor.
14138
*/
14139
export const textDocuments: readonly TextDocument[];
14140
14141
/**
14142
* Opens a document. Will return early if this document is already open. Otherwise
14143
* the document is loaded and the {@link workspace.onDidOpenTextDocument didOpen}-event fires.
14144
*
14145
* The document is denoted by an {@link Uri}. Depending on the {@link Uri.scheme scheme} the
14146
* following rules apply:
14147
* * `file`-scheme: Open a file on disk (`openTextDocument(Uri.file(path))`). Will be rejected if the file
14148
* does not exist or cannot be loaded.
14149
* * `untitled`-scheme: Open a blank untitled file with associated path (`openTextDocument(Uri.file(path).with({ scheme: 'untitled' }))`).
14150
* The language will be derived from the file name.
14151
* * For all other schemes contributed {@link TextDocumentContentProvider text document content providers} and
14152
* {@link FileSystemProvider file system providers} are consulted.
14153
*
14154
* *Note* that the lifecycle of the returned document is owned by the editor and not by the extension. That means an
14155
* {@linkcode workspace.onDidCloseTextDocument onDidClose}-event can occur at any time after opening it.
14156
*
14157
* @param uri Identifies the resource to open.
14158
* @returns A promise that resolves to a {@link TextDocument document}.
14159
*/
14160
export function openTextDocument(uri: Uri, options?: {
14161
/**
14162
* The {@link TextDocument.encoding encoding} of the document to use
14163
* for decoding the underlying buffer to text. If omitted, the encoding
14164
* will be guessed based on the file content and/or the editor settings
14165
* unless the document is already opened.
14166
*
14167
* Opening a text document that was already opened with a different encoding
14168
* has the potential of changing the text contents of the text document.
14169
* Specifically, when the encoding results in a different set of characters
14170
* than the previous encoding. As such, an error is thrown for dirty documents
14171
* when the specified encoding is different from the encoding of the document.
14172
*
14173
* See {@link TextDocument.encoding} for more information about valid
14174
* values for encoding. Using an unsupported encoding will fallback to the
14175
* default encoding for the document.
14176
*
14177
* *Note* that if you open a document with an encoding that does not
14178
* support decoding the underlying bytes, content may be replaced with
14179
* substitution characters as appropriate.
14180
*/
14181
readonly encoding?: string;
14182
}): Thenable<TextDocument>;
14183
14184
/**
14185
* A short-hand for `openTextDocument(Uri.file(path))`.
14186
*
14187
* @see {@link workspace.openTextDocument}
14188
* @param path A path of a file on disk.
14189
* @returns A promise that resolves to a {@link TextDocument document}.
14190
*/
14191
export function openTextDocument(path: string, options?: {
14192
/**
14193
* The {@link TextDocument.encoding encoding} of the document to use
14194
* for decoding the underlying buffer to text. If omitted, the encoding
14195
* will be guessed based on the file content and/or the editor settings
14196
* unless the document is already opened.
14197
*
14198
* Opening a text document that was already opened with a different encoding
14199
* has the potential of changing the text contents of the text document.
14200
* Specifically, when the encoding results in a different set of characters
14201
* than the previous encoding. As such, an error is thrown for dirty documents
14202
* when the specified encoding is different from the encoding of the document.
14203
*
14204
* See {@link TextDocument.encoding} for more information about valid
14205
* values for encoding. Using an unsupported encoding will fallback to the
14206
* default encoding for the document.
14207
*
14208
* *Note* that if you open a document with an encoding that does not
14209
* support decoding the underlying bytes, content may be replaced with
14210
* substitution characters as appropriate.
14211
*/
14212
readonly encoding?: string;
14213
}): Thenable<TextDocument>;
14214
14215
/**
14216
* Opens an untitled text document. The editor will prompt the user for a file
14217
* path when the document is to be saved. The `options` parameter allows to
14218
* specify the *language* and/or the *content* of the document.
14219
*
14220
* @param options Options to control how the document will be created.
14221
* @returns A promise that resolves to a {@link TextDocument document}.
14222
*/
14223
export function openTextDocument(options?: {
14224
/**
14225
* The {@link TextDocument.languageId language} of the document.
14226
*/
14227
language?: string;
14228
/**
14229
* The initial contents of the document.
14230
*/
14231
content?: string;
14232
/**
14233
* The {@link TextDocument.encoding encoding} of the document.
14234
*
14235
* See {@link TextDocument.encoding} for more information about valid
14236
* values for encoding. Using an unsupported encoding will fallback to the
14237
* default encoding for the document.
14238
*/
14239
readonly encoding?: string;
14240
}): Thenable<TextDocument>;
14241
14242
/**
14243
* Register a text document content provider.
14244
*
14245
* Only one provider can be registered per scheme.
14246
*
14247
* @param scheme The uri-scheme to register for.
14248
* @param provider A content provider.
14249
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14250
*/
14251
export function registerTextDocumentContentProvider(scheme: string, provider: TextDocumentContentProvider): Disposable;
14252
14253
/**
14254
* An event that is emitted when a {@link TextDocument text document} is opened or when the language id
14255
* of a text document {@link languages.setTextDocumentLanguage has been changed}.
14256
*
14257
* To add an event listener when a visible text document is opened, use the {@link TextEditor} events in the
14258
* {@link window} namespace. Note that:
14259
*
14260
* - The event is emitted before the {@link TextDocument document} is updated in the
14261
* {@link window.activeTextEditor active text editor}
14262
* - When a {@link TextDocument text document} is already open (e.g.: open in another {@link window.visibleTextEditors visible text editor}) this event is not emitted
14263
*
14264
*/
14265
export const onDidOpenTextDocument: Event<TextDocument>;
14266
14267
/**
14268
* An event that is emitted when a {@link TextDocument text document} is disposed or when the language id
14269
* of a text document {@link languages.setTextDocumentLanguage has been changed}.
14270
*
14271
* *Note 1:* There is no guarantee that this event fires when an editor tab is closed, use the
14272
* {@linkcode window.onDidChangeVisibleTextEditors onDidChangeVisibleTextEditors}-event to know when editors change.
14273
*
14274
* *Note 2:* A document can be open but not shown in an editor which means this event can fire
14275
* for a document that has not been shown in an editor.
14276
*/
14277
export const onDidCloseTextDocument: Event<TextDocument>;
14278
14279
/**
14280
* An event that is emitted when a {@link TextDocument text document} is changed. This usually happens
14281
* when the {@link TextDocument.getText contents} changes but also when other things like the
14282
* {@link TextDocument.isDirty dirty}-state changes.
14283
*/
14284
export const onDidChangeTextDocument: Event<TextDocumentChangeEvent>;
14285
14286
/**
14287
* An event that is emitted when a {@link TextDocument text document} will be saved to disk.
14288
*
14289
* *Note 1:* Subscribers can delay saving by registering asynchronous work. For the sake of data integrity the editor
14290
* might save without firing this event. For instance when shutting down with dirty files.
14291
*
14292
* *Note 2:* Subscribers are called sequentially and they can {@link TextDocumentWillSaveEvent.waitUntil delay} saving
14293
* by registering asynchronous work. Protection against misbehaving listeners is implemented as such:
14294
* * there is an overall time budget that all listeners share and if that is exhausted no further listener is called
14295
* * listeners that take a long time or produce errors frequently will not be called anymore
14296
*
14297
* The current thresholds are 1.5 seconds as overall time budget and a listener can misbehave 3 times before being ignored.
14298
*/
14299
export const onWillSaveTextDocument: Event<TextDocumentWillSaveEvent>;
14300
14301
/**
14302
* An event that is emitted when a {@link TextDocument text document} is saved to disk.
14303
*/
14304
export const onDidSaveTextDocument: Event<TextDocument>;
14305
14306
/**
14307
* All notebook documents currently known to the editor.
14308
*/
14309
export const notebookDocuments: readonly NotebookDocument[];
14310
14311
/**
14312
* Open a notebook. Will return early if this notebook is already {@link notebookDocuments loaded}. Otherwise
14313
* the notebook is loaded and the {@linkcode onDidOpenNotebookDocument}-event fires.
14314
*
14315
* *Note* that the lifecycle of the returned notebook is owned by the editor and not by the extension. That means an
14316
* {@linkcode onDidCloseNotebookDocument}-event can occur at any time after.
14317
*
14318
* *Note* that opening a notebook does not show a notebook editor. This function only returns a notebook document which
14319
* can be shown in a notebook editor but it can also be used for other things.
14320
*
14321
* @param uri The resource to open.
14322
* @returns A promise that resolves to a {@link NotebookDocument notebook}
14323
*/
14324
export function openNotebookDocument(uri: Uri): Thenable<NotebookDocument>;
14325
14326
/**
14327
* Open an untitled notebook. The editor will prompt the user for a file
14328
* path when the document is to be saved.
14329
*
14330
* @see {@link workspace.openNotebookDocument}
14331
* @param notebookType The notebook type that should be used.
14332
* @param content The initial contents of the notebook.
14333
* @returns A promise that resolves to a {@link NotebookDocument notebook}.
14334
*/
14335
export function openNotebookDocument(notebookType: string, content?: NotebookData): Thenable<NotebookDocument>;
14336
14337
/**
14338
* An event that is emitted when a {@link NotebookDocument notebook} has changed.
14339
*/
14340
export const onDidChangeNotebookDocument: Event<NotebookDocumentChangeEvent>;
14341
14342
/**
14343
* An event that is emitted when a {@link NotebookDocument notebook document} will be saved to disk.
14344
*
14345
* *Note 1:* Subscribers can delay saving by registering asynchronous work. For the sake of data integrity the editor
14346
* might save without firing this event. For instance when shutting down with dirty files.
14347
*
14348
* *Note 2:* Subscribers are called sequentially and they can {@link NotebookDocumentWillSaveEvent.waitUntil delay} saving
14349
* by registering asynchronous work. Protection against misbehaving listeners is implemented as such:
14350
* * there is an overall time budget that all listeners share and if that is exhausted no further listener is called
14351
* * listeners that take a long time or produce errors frequently will not be called anymore
14352
*
14353
* The current thresholds are 1.5 seconds as overall time budget and a listener can misbehave 3 times before being ignored.
14354
*/
14355
export const onWillSaveNotebookDocument: Event<NotebookDocumentWillSaveEvent>;
14356
14357
/**
14358
* An event that is emitted when a {@link NotebookDocument notebook} is saved.
14359
*/
14360
export const onDidSaveNotebookDocument: Event<NotebookDocument>;
14361
14362
/**
14363
* Register a {@link NotebookSerializer notebook serializer}.
14364
*
14365
* A notebook serializer must be contributed through the `notebooks` extension point. When opening a notebook file, the editor will send
14366
* the `onNotebook:<notebookType>` activation event, and extensions must register their serializer in return.
14367
*
14368
* @param notebookType A notebook.
14369
* @param serializer A notebook serializer.
14370
* @param options Optional context options that define what parts of a notebook should be persisted
14371
* @returns A {@link Disposable} that unregisters this serializer when being disposed.
14372
*/
14373
export function registerNotebookSerializer(notebookType: string, serializer: NotebookSerializer, options?: NotebookDocumentContentOptions): Disposable;
14374
14375
/**
14376
* An event that is emitted when a {@link NotebookDocument notebook} is opened.
14377
*/
14378
export const onDidOpenNotebookDocument: Event<NotebookDocument>;
14379
14380
/**
14381
* An event that is emitted when a {@link NotebookDocument notebook} is disposed.
14382
*
14383
* *Note 1:* There is no guarantee that this event fires when an editor tab is closed.
14384
*
14385
* *Note 2:* A notebook can be open but not shown in an editor which means this event can fire
14386
* for a notebook that has not been shown in an editor.
14387
*/
14388
export const onDidCloseNotebookDocument: Event<NotebookDocument>;
14389
14390
/**
14391
* An event that is emitted when files are being created.
14392
*
14393
* *Note 1:* This event is triggered by user gestures, like creating a file from the
14394
* explorer, or from the {@linkcode workspace.applyEdit}-api. This event is *not* fired when
14395
* files change on disk, e.g triggered by another application, or when using the
14396
* {@linkcode FileSystem workspace.fs}-api.
14397
*
14398
* *Note 2:* When this event is fired, edits to files that are are being created cannot be applied.
14399
*/
14400
export const onWillCreateFiles: Event<FileWillCreateEvent>;
14401
14402
/**
14403
* An event that is emitted when files have been created.
14404
*
14405
* *Note:* This event is triggered by user gestures, like creating a file from the
14406
* explorer, or from the {@linkcode workspace.applyEdit}-api, but this event is *not* fired when
14407
* files change on disk, e.g triggered by another application, or when using the
14408
* {@linkcode FileSystem workspace.fs}-api.
14409
*/
14410
export const onDidCreateFiles: Event<FileCreateEvent>;
14411
14412
/**
14413
* An event that is emitted when files are being deleted.
14414
*
14415
* *Note 1:* This event is triggered by user gestures, like deleting a file from the
14416
* explorer, or from the {@linkcode workspace.applyEdit}-api, but this event is *not* fired when
14417
* files change on disk, e.g triggered by another application, or when using the
14418
* {@linkcode FileSystem workspace.fs}-api.
14419
*
14420
* *Note 2:* When deleting a folder with children only one event is fired.
14421
*/
14422
export const onWillDeleteFiles: Event<FileWillDeleteEvent>;
14423
14424
/**
14425
* An event that is emitted when files have been deleted.
14426
*
14427
* *Note 1:* This event is triggered by user gestures, like deleting a file from the
14428
* explorer, or from the {@linkcode workspace.applyEdit}-api, but this event is *not* fired when
14429
* files change on disk, e.g triggered by another application, or when using the
14430
* {@linkcode FileSystem workspace.fs}-api.
14431
*
14432
* *Note 2:* When deleting a folder with children only one event is fired.
14433
*/
14434
export const onDidDeleteFiles: Event<FileDeleteEvent>;
14435
14436
/**
14437
* An event that is emitted when files are being renamed.
14438
*
14439
* *Note 1:* This event is triggered by user gestures, like renaming a file from the
14440
* explorer, and from the {@linkcode workspace.applyEdit}-api, but this event is *not* fired when
14441
* files change on disk, e.g triggered by another application, or when using the
14442
* {@linkcode FileSystem workspace.fs}-api.
14443
*
14444
* *Note 2:* When renaming a folder with children only one event is fired.
14445
*/
14446
export const onWillRenameFiles: Event<FileWillRenameEvent>;
14447
14448
/**
14449
* An event that is emitted when files have been renamed.
14450
*
14451
* *Note 1:* This event is triggered by user gestures, like renaming a file from the
14452
* explorer, and from the {@linkcode workspace.applyEdit}-api, but this event is *not* fired when
14453
* files change on disk, e.g triggered by another application, or when using the
14454
* {@linkcode FileSystem workspace.fs}-api.
14455
*
14456
* *Note 2:* When renaming a folder with children only one event is fired.
14457
*/
14458
export const onDidRenameFiles: Event<FileRenameEvent>;
14459
14460
/**
14461
* Get a workspace configuration object.
14462
*
14463
* When a section-identifier is provided only that part of the configuration
14464
* is returned. Dots in the section-identifier are interpreted as child-access,
14465
* like `{ myExt: { setting: { doIt: true }}}` and `getConfiguration('myExt.setting').get('doIt') === true`.
14466
*
14467
* When a scope is provided configuration confined to that scope is returned. Scope can be a resource or a language identifier or both.
14468
*
14469
* @param section A dot-separated identifier.
14470
* @param scope A scope for which the configuration is asked for.
14471
* @returns The full configuration or a subset.
14472
*/
14473
export function getConfiguration(section?: string, scope?: ConfigurationScope | null): WorkspaceConfiguration;
14474
14475
/**
14476
* An event that is emitted when the {@link WorkspaceConfiguration configuration} changed.
14477
*/
14478
export const onDidChangeConfiguration: Event<ConfigurationChangeEvent>;
14479
14480
/**
14481
* Register a task provider.
14482
*
14483
* @deprecated Use the corresponding function on the `tasks` namespace instead
14484
*
14485
* @param type The task kind type this provider is registered for.
14486
* @param provider A task provider.
14487
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14488
*/
14489
export function registerTaskProvider(type: string, provider: TaskProvider): Disposable;
14490
14491
/**
14492
* Register a filesystem provider for a given scheme, e.g. `ftp`.
14493
*
14494
* There can only be one provider per scheme and an error is being thrown when a scheme
14495
* has been claimed by another provider or when it is reserved.
14496
*
14497
* @param scheme The uri-{@link Uri.scheme scheme} the provider registers for.
14498
* @param provider The filesystem provider.
14499
* @param options Immutable metadata about the provider.
14500
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14501
*/
14502
export function registerFileSystemProvider(scheme: string, provider: FileSystemProvider, options?: {
14503
/**
14504
* Whether the file system provider use case sensitive compare for {@link Uri.path paths}
14505
*/
14506
readonly isCaseSensitive?: boolean;
14507
/**
14508
* Whether the file system provider is readonly, no modifications like write, delete, create are possible.
14509
* If a {@link MarkdownString} is given, it will be shown as the reason why the file system is readonly.
14510
*/
14511
readonly isReadonly?: boolean | MarkdownString;
14512
}): Disposable;
14513
14514
/**
14515
* When true, the user has explicitly trusted the contents of the workspace.
14516
*/
14517
export const isTrusted: boolean;
14518
14519
/**
14520
* Event that fires when the current workspace has been trusted.
14521
*/
14522
export const onDidGrantWorkspaceTrust: Event<void>;
14523
14524
/**
14525
* Decodes the content from a `Uint8Array` to a `string`. You MUST
14526
* provide the entire content at once to ensure that the encoding
14527
* can properly apply. Do not use this method to decode content
14528
* in chunks, as that may lead to incorrect results.
14529
*
14530
* Will pick an encoding based on settings and the content of the
14531
* buffer (for example byte order marks).
14532
*
14533
* *Note* that if you decode content that is unsupported by the
14534
* encoding, the result may contain substitution characters as
14535
* appropriate.
14536
*
14537
* @throws This method will throw an error when the content is binary.
14538
*
14539
* @param content The text content to decode as a `Uint8Array`.
14540
* @returns A thenable that resolves to the decoded `string`.
14541
*/
14542
export function decode(content: Uint8Array): Thenable<string>;
14543
14544
/**
14545
* Decodes the content from a `Uint8Array` to a `string` using the
14546
* provided encoding. You MUST provide the entire content at once
14547
* to ensure that the encoding can properly apply. Do not use this
14548
* method to decode content in chunks, as that may lead to incorrect
14549
* results.
14550
*
14551
* *Note* that if you decode content that is unsupported by the
14552
* encoding, the result may contain substitution characters as
14553
* appropriate.
14554
*
14555
* @throws This method will throw an error when the content is binary.
14556
*
14557
* @param content The text content to decode as a `Uint8Array`.
14558
* @param options Additional context for picking the encoding.
14559
* @returns A thenable that resolves to the decoded `string`.
14560
*/
14561
export function decode(content: Uint8Array, options: {
14562
/**
14563
* Allows to explicitly pick the encoding to use.
14564
* See {@link TextDocument.encoding} for more information
14565
* about valid values for encoding.
14566
* Using an unsupported encoding will fallback to the
14567
* default configured encoding.
14568
*/
14569
readonly encoding: string;
14570
}): Thenable<string>;
14571
14572
/**
14573
* Decodes the content from a `Uint8Array` to a `string`. You MUST
14574
* provide the entire content at once to ensure that the encoding
14575
* can properly apply. Do not use this method to decode content
14576
* in chunks, as that may lead to incorrect results.
14577
*
14578
* The encoding is picked based on settings and the content
14579
* of the buffer (for example byte order marks).
14580
*
14581
* *Note* that if you decode content that is unsupported by the
14582
* encoding, the result may contain substitution characters as
14583
* appropriate.
14584
*
14585
* @throws This method will throw an error when the content is binary.
14586
*
14587
* @param content The content to decode as a `Uint8Array`.
14588
* @param options Additional context for picking the encoding.
14589
* @returns A thenable that resolves to the decoded `string`.
14590
*/
14591
export function decode(content: Uint8Array, options: {
14592
/**
14593
* The URI that represents the file if known. This information
14594
* is used to figure out the encoding related configuration
14595
* for the file if any.
14596
*/
14597
readonly uri: Uri;
14598
}): Thenable<string>;
14599
14600
/**
14601
* Encodes the content of a `string` to a `Uint8Array`.
14602
*
14603
* Will pick an encoding based on settings.
14604
*
14605
* @param content The content to decode as a `string`.
14606
* @returns A thenable that resolves to the encoded `Uint8Array`.
14607
*/
14608
export function encode(content: string): Thenable<Uint8Array>;
14609
14610
/**
14611
* Encodes the content of a `string` to a `Uint8Array` using the
14612
* provided encoding.
14613
*
14614
* @param content The content to decode as a `string`.
14615
* @param options Additional context for picking the encoding.
14616
* @returns A thenable that resolves to the encoded `Uint8Array`.
14617
*/
14618
export function encode(content: string, options: {
14619
/**
14620
* Allows to explicitly pick the encoding to use.
14621
* See {@link TextDocument.encoding} for more information
14622
* about valid values for encoding.
14623
* Using an unsupported encoding will fallback to the
14624
* default configured encoding.
14625
*/
14626
readonly encoding: string;
14627
}): Thenable<Uint8Array>;
14628
14629
/**
14630
* Encodes the content of a `string` to a `Uint8Array`.
14631
*
14632
* The encoding is picked based on settings.
14633
*
14634
* @param content The content to decode as a `string`.
14635
* @param options Additional context for picking the encoding.
14636
* @returns A thenable that resolves to the encoded `Uint8Array`.
14637
*/
14638
export function encode(content: string, options: {
14639
/**
14640
* The URI that represents the file if known. This information
14641
* is used to figure out the encoding related configuration
14642
* for the file if any.
14643
*/
14644
readonly uri: Uri;
14645
}): Thenable<Uint8Array>;
14646
}
14647
14648
/**
14649
* The configuration scope which can be:
14650
* - a {@link Uri} representing a resource
14651
* - a {@link TextDocument} representing an open text document
14652
* - a {@link WorkspaceFolder} representing a workspace folder
14653
* - an object containing:
14654
* - `uri`: an optional {@link Uri} of a text document
14655
* - `languageId`: the language identifier of a text document
14656
*/
14657
export type ConfigurationScope = Uri | TextDocument | WorkspaceFolder | {
14658
/**
14659
* The uri of a {@link TextDocument text document}
14660
*/
14661
uri?: Uri;
14662
/**
14663
* The language of a text document
14664
*/
14665
languageId: string;
14666
};
14667
14668
/**
14669
* An event describing the change in Configuration
14670
*/
14671
export interface ConfigurationChangeEvent {
14672
14673
/**
14674
* Checks if the given section has changed.
14675
* If scope is provided, checks if the section has changed for resources under the given scope.
14676
*
14677
* @param section Configuration name, supports _dotted_ names.
14678
* @param scope A scope in which to check.
14679
* @returns `true` if the given section has changed.
14680
*/
14681
affectsConfiguration(section: string, scope?: ConfigurationScope): boolean;
14682
}
14683
14684
/**
14685
* Namespace for participating in language-specific editor [features](https://code.visualstudio.com/docs/editor/editingevolved),
14686
* like IntelliSense, code actions, diagnostics etc.
14687
*
14688
* Many programming languages exist and there is huge variety in syntaxes, semantics, and paradigms. Despite that, features
14689
* like automatic word-completion, code navigation, or code checking have become popular across different tools for different
14690
* programming languages.
14691
*
14692
* The editor provides an API that makes it simple to provide such common features by having all UI and actions already in place and
14693
* by allowing you to participate by providing data only. For instance, to contribute a hover all you have to do is provide a function
14694
* that can be called with a {@link TextDocument} and a {@link Position} returning hover info. The rest, like tracking the
14695
* mouse, positioning the hover, keeping the hover stable etc. is taken care of by the editor.
14696
*
14697
* ```javascript
14698
* languages.registerHoverProvider('javascript', {
14699
* provideHover(document, position, token) {
14700
* return new Hover('I am a hover!');
14701
* }
14702
* });
14703
* ```
14704
*
14705
* Registration is done using a {@link DocumentSelector document selector} which is either a language id, like `javascript` or
14706
* a more complex {@link DocumentFilter filter} like `{ language: 'typescript', scheme: 'file' }`. Matching a document against such
14707
* a selector will result in a {@link languages.match score} that is used to determine if and how a provider shall be used. When
14708
* scores are equal the provider that came last wins. For features that allow full arity, like {@link languages.registerHoverProvider hover},
14709
* the score is only checked to be `>0`, for other features, like {@link languages.registerCompletionItemProvider IntelliSense} the
14710
* score is used for determining the order in which providers are asked to participate.
14711
*/
14712
export namespace languages {
14713
14714
/**
14715
* Return the identifiers of all known languages.
14716
* @returns Promise resolving to an array of identifier strings.
14717
*/
14718
export function getLanguages(): Thenable<string[]>;
14719
14720
/**
14721
* Set (and change) the {@link TextDocument.languageId language} that is associated
14722
* with the given document.
14723
*
14724
* *Note* that calling this function will trigger the {@linkcode workspace.onDidCloseTextDocument onDidCloseTextDocument} event
14725
* followed by the {@linkcode workspace.onDidOpenTextDocument onDidOpenTextDocument} event.
14726
*
14727
* @param document The document which language is to be changed
14728
* @param languageId The new language identifier.
14729
* @returns A thenable that resolves with the updated document.
14730
*/
14731
export function setTextDocumentLanguage(document: TextDocument, languageId: string): Thenable<TextDocument>;
14732
14733
/**
14734
* Compute the match between a document {@link DocumentSelector selector} and a document. Values
14735
* greater than zero mean the selector matches the document.
14736
*
14737
* A match is computed according to these rules:
14738
* 1. When {@linkcode DocumentSelector} is an array, compute the match for each contained `DocumentFilter` or language identifier and take the maximum value.
14739
* 2. A string will be desugared to become the `language`-part of a {@linkcode DocumentFilter}, so `"fooLang"` is like `{ language: "fooLang" }`.
14740
* 3. A {@linkcode DocumentFilter} will be matched against the document by comparing its parts with the document. The following rules apply:
14741
* 1. When the `DocumentFilter` is empty (`{}`) the result is `0`
14742
* 2. When `scheme`, `language`, `pattern`, or `notebook` are defined but one doesn't match, the result is `0`
14743
* 3. Matching against `*` gives a score of `5`, matching via equality or via a glob-pattern gives a score of `10`
14744
* 4. The result is the maximum value of each match
14745
*
14746
* Samples:
14747
* ```js
14748
* // default document from disk (file-scheme)
14749
* doc.uri; //'file:///my/file.js'
14750
* doc.languageId; // 'javascript'
14751
* match('javascript', doc); // 10;
14752
* match({ language: 'javascript' }, doc); // 10;
14753
* match({ language: 'javascript', scheme: 'file' }, doc); // 10;
14754
* match('*', doc); // 5
14755
* match('fooLang', doc); // 0
14756
* match(['fooLang', '*'], doc); // 5
14757
*
14758
* // virtual document, e.g. from git-index
14759
* doc.uri; // 'git:/my/file.js'
14760
* doc.languageId; // 'javascript'
14761
* match('javascript', doc); // 10;
14762
* match({ language: 'javascript', scheme: 'git' }, doc); // 10;
14763
* match('*', doc); // 5
14764
*
14765
* // notebook cell document
14766
* doc.uri; // `vscode-notebook-cell:///my/notebook.ipynb#gl65s2pmha`;
14767
* doc.languageId; // 'python'
14768
* match({ notebookType: 'jupyter-notebook' }, doc) // 10
14769
* match({ notebookType: 'fooNotebook', language: 'python' }, doc) // 0
14770
* match({ language: 'python' }, doc) // 10
14771
* match({ notebookType: '*' }, doc) // 5
14772
* ```
14773
*
14774
* @param selector A document selector.
14775
* @param document A text document.
14776
* @returns A number `>0` when the selector matches and `0` when the selector does not match.
14777
*/
14778
export function match(selector: DocumentSelector, document: TextDocument): number;
14779
14780
/**
14781
* An {@link Event} which fires when the global set of diagnostics changes. This is
14782
* newly added and removed diagnostics.
14783
*/
14784
export const onDidChangeDiagnostics: Event<DiagnosticChangeEvent>;
14785
14786
/**
14787
* Get all diagnostics for a given resource.
14788
*
14789
* @param resource A resource
14790
* @returns An array of {@link Diagnostic diagnostics} objects or an empty array.
14791
*/
14792
export function getDiagnostics(resource: Uri): Diagnostic[];
14793
14794
/**
14795
* Get all diagnostics.
14796
*
14797
* @returns An array of uri-diagnostics tuples or an empty array.
14798
*/
14799
export function getDiagnostics(): [Uri, Diagnostic[]][];
14800
14801
/**
14802
* Create a diagnostics collection.
14803
*
14804
* @param name The {@link DiagnosticCollection.name name} of the collection.
14805
* @returns A new diagnostic collection.
14806
*/
14807
export function createDiagnosticCollection(name?: string): DiagnosticCollection;
14808
14809
/**
14810
* Creates a new {@link LanguageStatusItem language status item}.
14811
*
14812
* @param id The identifier of the item.
14813
* @param selector The document selector that defines for what editors the item shows.
14814
* @returns A new language status item.
14815
*/
14816
export function createLanguageStatusItem(id: string, selector: DocumentSelector): LanguageStatusItem;
14817
14818
/**
14819
* Register a completion provider.
14820
*
14821
* Multiple providers can be registered for a language. In that case providers are sorted
14822
* by their {@link languages.match score} and groups of equal score are sequentially asked for
14823
* completion items. The process stops when one or many providers of a group return a
14824
* result. A failing provider (rejected promise or exception) will not fail the whole
14825
* operation.
14826
*
14827
* A completion item provider can be associated with a set of `triggerCharacters`. When trigger
14828
* characters are being typed, completions are requested but only from providers that registered
14829
* the typed character. Because of that trigger characters should be different than {@link LanguageConfiguration.wordPattern word characters},
14830
* a common trigger character is `.` to trigger member completions.
14831
*
14832
* @param selector A selector that defines the documents this provider is applicable to.
14833
* @param provider A completion provider.
14834
* @param triggerCharacters Trigger completion when the user types one of the characters.
14835
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14836
*/
14837
export function registerCompletionItemProvider(selector: DocumentSelector, provider: CompletionItemProvider, ...triggerCharacters: string[]): Disposable;
14838
14839
/**
14840
* Registers an inline completion provider.
14841
*
14842
* Multiple providers can be registered for a language. In that case providers are asked in
14843
* parallel and the results are merged. A failing provider (rejected promise or exception) will
14844
* not cause a failure of the whole operation.
14845
*
14846
* @param selector A selector that defines the documents this provider is applicable to.
14847
* @param provider An inline completion provider.
14848
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14849
*/
14850
export function registerInlineCompletionItemProvider(selector: DocumentSelector, provider: InlineCompletionItemProvider): Disposable;
14851
14852
/**
14853
* Register a code action provider.
14854
*
14855
* Multiple providers can be registered for a language. In that case providers are asked in
14856
* parallel and the results are merged. A failing provider (rejected promise or exception) will
14857
* not cause a failure of the whole operation.
14858
*
14859
* @param selector A selector that defines the documents this provider is applicable to.
14860
* @param provider A code action provider.
14861
* @param metadata Metadata about the kind of code actions the provider provides.
14862
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14863
*/
14864
export function registerCodeActionsProvider(selector: DocumentSelector, provider: CodeActionProvider, metadata?: CodeActionProviderMetadata): Disposable;
14865
14866
/**
14867
* Register a code lens provider.
14868
*
14869
* Multiple providers can be registered for a language. In that case providers are asked in
14870
* parallel and the results are merged. A failing provider (rejected promise or exception) will
14871
* not cause a failure of the whole operation.
14872
*
14873
* @param selector A selector that defines the documents this provider is applicable to.
14874
* @param provider A code lens provider.
14875
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14876
*/
14877
export function registerCodeLensProvider(selector: DocumentSelector, provider: CodeLensProvider): Disposable;
14878
14879
/**
14880
* Register a definition provider.
14881
*
14882
* Multiple providers can be registered for a language. In that case providers are asked in
14883
* parallel and the results are merged. A failing provider (rejected promise or exception) will
14884
* not cause a failure of the whole operation.
14885
*
14886
* @param selector A selector that defines the documents this provider is applicable to.
14887
* @param provider A definition provider.
14888
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14889
*/
14890
export function registerDefinitionProvider(selector: DocumentSelector, provider: DefinitionProvider): Disposable;
14891
14892
/**
14893
* Register an implementation provider.
14894
*
14895
* Multiple providers can be registered for a language. In that case providers are asked in
14896
* parallel and the results are merged. A failing provider (rejected promise or exception) will
14897
* not cause a failure of the whole operation.
14898
*
14899
* @param selector A selector that defines the documents this provider is applicable to.
14900
* @param provider An implementation provider.
14901
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14902
*/
14903
export function registerImplementationProvider(selector: DocumentSelector, provider: ImplementationProvider): Disposable;
14904
14905
/**
14906
* Register a type definition provider.
14907
*
14908
* Multiple providers can be registered for a language. In that case providers are asked in
14909
* parallel and the results are merged. A failing provider (rejected promise or exception) will
14910
* not cause a failure of the whole operation.
14911
*
14912
* @param selector A selector that defines the documents this provider is applicable to.
14913
* @param provider A type definition provider.
14914
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14915
*/
14916
export function registerTypeDefinitionProvider(selector: DocumentSelector, provider: TypeDefinitionProvider): Disposable;
14917
14918
/**
14919
* Register a declaration provider.
14920
*
14921
* Multiple providers can be registered for a language. In that case providers are asked in
14922
* parallel and the results are merged. A failing provider (rejected promise or exception) will
14923
* not cause a failure of the whole operation.
14924
*
14925
* @param selector A selector that defines the documents this provider is applicable to.
14926
* @param provider A declaration provider.
14927
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14928
*/
14929
export function registerDeclarationProvider(selector: DocumentSelector, provider: DeclarationProvider): Disposable;
14930
14931
/**
14932
* Register a hover provider.
14933
*
14934
* Multiple providers can be registered for a language. In that case providers are asked in
14935
* parallel and the results are merged. A failing provider (rejected promise or exception) will
14936
* not cause a failure of the whole operation.
14937
*
14938
* @param selector A selector that defines the documents this provider is applicable to.
14939
* @param provider A hover provider.
14940
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14941
*/
14942
export function registerHoverProvider(selector: DocumentSelector, provider: HoverProvider): Disposable;
14943
14944
/**
14945
* Register a provider that locates evaluatable expressions in text documents.
14946
* The editor will evaluate the expression in the active debug session and will show the result in the debug hover.
14947
*
14948
* If multiple providers are registered for a language an arbitrary provider will be used.
14949
*
14950
* @param selector A selector that defines the documents this provider is applicable to.
14951
* @param provider An evaluatable expression provider.
14952
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14953
*/
14954
export function registerEvaluatableExpressionProvider(selector: DocumentSelector, provider: EvaluatableExpressionProvider): Disposable;
14955
14956
/**
14957
* Register a provider that returns data for the debugger's 'inline value' feature.
14958
* Whenever the generic debugger has stopped in a source file, providers registered for the language of the file
14959
* are called to return textual data that will be shown in the editor at the end of lines.
14960
*
14961
* Multiple providers can be registered for a language. In that case providers are asked in
14962
* parallel and the results are merged. A failing provider (rejected promise or exception) will
14963
* not cause a failure of the whole operation.
14964
*
14965
* @param selector A selector that defines the documents this provider is applicable to.
14966
* @param provider An inline values provider.
14967
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14968
*/
14969
export function registerInlineValuesProvider(selector: DocumentSelector, provider: InlineValuesProvider): Disposable;
14970
14971
/**
14972
* Register a document highlight provider.
14973
*
14974
* Multiple providers can be registered for a language. In that case providers are sorted
14975
* by their {@link languages.match score} and groups sequentially asked for document highlights.
14976
* The process stops when a provider returns a `non-falsy` or `non-failure` result.
14977
*
14978
* @param selector A selector that defines the documents this provider is applicable to.
14979
* @param provider A document highlight provider.
14980
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14981
*/
14982
export function registerDocumentHighlightProvider(selector: DocumentSelector, provider: DocumentHighlightProvider): Disposable;
14983
14984
/**
14985
* Register a document symbol provider.
14986
*
14987
* Multiple providers can be registered for a language. In that case providers are asked in
14988
* parallel and the results are merged. A failing provider (rejected promise or exception) will
14989
* not cause a failure of the whole operation.
14990
*
14991
* @param selector A selector that defines the documents this provider is applicable to.
14992
* @param provider A document symbol provider.
14993
* @param metaData metadata about the provider
14994
* @returns A {@link Disposable} that unregisters this provider when being disposed.
14995
*/
14996
export function registerDocumentSymbolProvider(selector: DocumentSelector, provider: DocumentSymbolProvider, metaData?: DocumentSymbolProviderMetadata): Disposable;
14997
14998
/**
14999
* Register a workspace symbol provider.
15000
*
15001
* Multiple providers can be registered. In that case providers are asked in parallel and
15002
* the results are merged. A failing provider (rejected promise or exception) will not cause
15003
* a failure of the whole operation.
15004
*
15005
* @param provider A workspace symbol provider.
15006
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15007
*/
15008
export function registerWorkspaceSymbolProvider(provider: WorkspaceSymbolProvider): Disposable;
15009
15010
/**
15011
* Register a reference provider.
15012
*
15013
* Multiple providers can be registered for a language. In that case providers are asked in
15014
* parallel and the results are merged. A failing provider (rejected promise or exception) will
15015
* not cause a failure of the whole operation.
15016
*
15017
* @param selector A selector that defines the documents this provider is applicable to.
15018
* @param provider A reference provider.
15019
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15020
*/
15021
export function registerReferenceProvider(selector: DocumentSelector, provider: ReferenceProvider): Disposable;
15022
15023
/**
15024
* Register a rename provider.
15025
*
15026
* Multiple providers can be registered for a language. In that case providers are sorted
15027
* by their {@link languages.match score} and asked in sequence. The first provider producing a result
15028
* defines the result of the whole operation.
15029
*
15030
* @param selector A selector that defines the documents this provider is applicable to.
15031
* @param provider A rename provider.
15032
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15033
*/
15034
export function registerRenameProvider(selector: DocumentSelector, provider: RenameProvider): Disposable;
15035
15036
/**
15037
* Register a semantic tokens provider for a whole document.
15038
*
15039
* Multiple providers can be registered for a language. In that case providers are sorted
15040
* by their {@link languages.match score} and the best-matching provider is used. Failure
15041
* of the selected provider will cause a failure of the whole operation.
15042
*
15043
* @param selector A selector that defines the documents this provider is applicable to.
15044
* @param provider A document semantic tokens provider.
15045
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15046
*/
15047
export function registerDocumentSemanticTokensProvider(selector: DocumentSelector, provider: DocumentSemanticTokensProvider, legend: SemanticTokensLegend): Disposable;
15048
15049
/**
15050
* Register a semantic tokens provider for a document range.
15051
*
15052
* *Note:* If a document has both a `DocumentSemanticTokensProvider` and a `DocumentRangeSemanticTokensProvider`,
15053
* the range provider will be invoked only initially, for the time in which the full document provider takes
15054
* to resolve the first request. Once the full document provider resolves the first request, the semantic tokens
15055
* provided via the range provider will be discarded and from that point forward, only the document provider
15056
* will be used.
15057
*
15058
* Multiple providers can be registered for a language. In that case providers are sorted
15059
* by their {@link languages.match score} and the best-matching provider is used. Failure
15060
* of the selected provider will cause a failure of the whole operation.
15061
*
15062
* @param selector A selector that defines the documents this provider is applicable to.
15063
* @param provider A document range semantic tokens provider.
15064
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15065
*/
15066
export function registerDocumentRangeSemanticTokensProvider(selector: DocumentSelector, provider: DocumentRangeSemanticTokensProvider, legend: SemanticTokensLegend): Disposable;
15067
15068
/**
15069
* Register a formatting provider for a document.
15070
*
15071
* Multiple providers can be registered for a language. In that case providers are sorted
15072
* by their {@link languages.match score} and the best-matching provider is used. Failure
15073
* of the selected provider will cause a failure of the whole operation.
15074
*
15075
* @param selector A selector that defines the documents this provider is applicable to.
15076
* @param provider A document formatting edit provider.
15077
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15078
*/
15079
export function registerDocumentFormattingEditProvider(selector: DocumentSelector, provider: DocumentFormattingEditProvider): Disposable;
15080
15081
/**
15082
* Register a formatting provider for a document range.
15083
*
15084
* *Note:* A document range provider is also a {@link DocumentFormattingEditProvider document formatter}
15085
* which means there is no need to {@link languages.registerDocumentFormattingEditProvider register} a document
15086
* formatter when also registering a range provider.
15087
*
15088
* Multiple providers can be registered for a language. In that case providers are sorted
15089
* by their {@link languages.match score} and the best-matching provider is used. Failure
15090
* of the selected provider will cause a failure of the whole operation.
15091
*
15092
* @param selector A selector that defines the documents this provider is applicable to.
15093
* @param provider A document range formatting edit provider.
15094
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15095
*/
15096
export function registerDocumentRangeFormattingEditProvider(selector: DocumentSelector, provider: DocumentRangeFormattingEditProvider): Disposable;
15097
15098
/**
15099
* Register a formatting provider that works on type. The provider is active when the user enables the setting `editor.formatOnType`.
15100
*
15101
* Multiple providers can be registered for a language. In that case providers are sorted
15102
* by their {@link languages.match score} and the best-matching provider is used. Failure
15103
* of the selected provider will cause a failure of the whole operation.
15104
*
15105
* @param selector A selector that defines the documents this provider is applicable to.
15106
* @param provider An on type formatting edit provider.
15107
* @param firstTriggerCharacter A character on which formatting should be triggered, like `}`.
15108
* @param moreTriggerCharacter More trigger characters.
15109
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15110
*/
15111
export function registerOnTypeFormattingEditProvider(selector: DocumentSelector, provider: OnTypeFormattingEditProvider, firstTriggerCharacter: string, ...moreTriggerCharacter: string[]): Disposable;
15112
15113
/**
15114
* Register a signature help provider.
15115
*
15116
* Multiple providers can be registered for a language. In that case providers are sorted
15117
* by their {@link languages.match score} and called sequentially until a provider returns a
15118
* valid result.
15119
*
15120
* @param selector A selector that defines the documents this provider is applicable to.
15121
* @param provider A signature help provider.
15122
* @param triggerCharacters Trigger signature help when the user types one of the characters, like `,` or `(`.
15123
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15124
*/
15125
export function registerSignatureHelpProvider(selector: DocumentSelector, provider: SignatureHelpProvider, ...triggerCharacters: string[]): Disposable;
15126
15127
/**
15128
* @see {@link languages.registerSignatureHelpProvider}
15129
*
15130
* @param selector A selector that defines the documents this provider is applicable to.
15131
* @param provider A signature help provider.
15132
* @param metadata Information about the provider.
15133
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15134
*/
15135
export function registerSignatureHelpProvider(selector: DocumentSelector, provider: SignatureHelpProvider, metadata: SignatureHelpProviderMetadata): Disposable;
15136
15137
/**
15138
* Register a document link provider.
15139
*
15140
* Multiple providers can be registered for a language. In that case providers are asked in
15141
* parallel and the results are merged. A failing provider (rejected promise or exception) will
15142
* not cause a failure of the whole operation.
15143
*
15144
* @param selector A selector that defines the documents this provider is applicable to.
15145
* @param provider A document link provider.
15146
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15147
*/
15148
export function registerDocumentLinkProvider(selector: DocumentSelector, provider: DocumentLinkProvider): Disposable;
15149
15150
/**
15151
* Register a color provider.
15152
*
15153
* Multiple providers can be registered for a language. In that case providers are asked in
15154
* parallel and the results are merged. A failing provider (rejected promise or exception) will
15155
* not cause a failure of the whole operation.
15156
*
15157
* @param selector A selector that defines the documents this provider is applicable to.
15158
* @param provider A color provider.
15159
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15160
*/
15161
export function registerColorProvider(selector: DocumentSelector, provider: DocumentColorProvider): Disposable;
15162
15163
/**
15164
* Register a inlay hints provider.
15165
*
15166
* Multiple providers can be registered for a language. In that case providers are asked in
15167
* parallel and the results are merged. A failing provider (rejected promise or exception) will
15168
* not cause a failure of the whole operation.
15169
*
15170
* @param selector A selector that defines the documents this provider is applicable to.
15171
* @param provider An inlay hints provider.
15172
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15173
*/
15174
export function registerInlayHintsProvider(selector: DocumentSelector, provider: InlayHintsProvider): Disposable;
15175
15176
/**
15177
* Register a folding range provider.
15178
*
15179
* Multiple providers can be registered for a language. In that case providers are asked in
15180
* parallel and the results are merged.
15181
* If multiple folding ranges start at the same position, only the range of the first registered provider is used.
15182
* If a folding range overlaps with an other range that has a smaller position, it is also ignored.
15183
*
15184
* A failing provider (rejected promise or exception) will
15185
* not cause a failure of the whole operation.
15186
*
15187
* @param selector A selector that defines the documents this provider is applicable to.
15188
* @param provider A folding range provider.
15189
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15190
*/
15191
export function registerFoldingRangeProvider(selector: DocumentSelector, provider: FoldingRangeProvider): Disposable;
15192
15193
/**
15194
* Register a selection range provider.
15195
*
15196
* Multiple providers can be registered for a language. In that case providers are asked in
15197
* parallel and the results are merged. A failing provider (rejected promise or exception) will
15198
* not cause a failure of the whole operation.
15199
*
15200
* @param selector A selector that defines the documents this provider is applicable to.
15201
* @param provider A selection range provider.
15202
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15203
*/
15204
export function registerSelectionRangeProvider(selector: DocumentSelector, provider: SelectionRangeProvider): Disposable;
15205
15206
/**
15207
* Register a call hierarchy provider.
15208
*
15209
* @param selector A selector that defines the documents this provider is applicable to.
15210
* @param provider A call hierarchy provider.
15211
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15212
*/
15213
export function registerCallHierarchyProvider(selector: DocumentSelector, provider: CallHierarchyProvider): Disposable;
15214
15215
/**
15216
* Register a type hierarchy provider.
15217
*
15218
* @param selector A selector that defines the documents this provider is applicable to.
15219
* @param provider A type hierarchy provider.
15220
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15221
*/
15222
export function registerTypeHierarchyProvider(selector: DocumentSelector, provider: TypeHierarchyProvider): Disposable;
15223
15224
/**
15225
* Register a linked editing range provider.
15226
*
15227
* Multiple providers can be registered for a language. In that case providers are sorted
15228
* by their {@link languages.match score} and the best-matching provider that has a result is used. Failure
15229
* of the selected provider will cause a failure of the whole operation.
15230
*
15231
* @param selector A selector that defines the documents this provider is applicable to.
15232
* @param provider A linked editing range provider.
15233
* @returns A {@link Disposable} that unregisters this provider when being disposed.
15234
*/
15235
export function registerLinkedEditingRangeProvider(selector: DocumentSelector, provider: LinkedEditingRangeProvider): Disposable;
15236
15237
/**
15238
* Registers a new {@link DocumentDropEditProvider}.
15239
*
15240
* Multiple drop providers can be registered for a language. When dropping content into an editor, all
15241
* registered providers for the editor's language will be invoked based on the mimetypes they handle
15242
* as specified by their {@linkcode DocumentDropEditProviderMetadata}.
15243
*
15244
* Each provider can return one or more {@linkcode DocumentDropEdit DocumentDropEdits}. The edits are sorted
15245
* using the {@linkcode DocumentDropEdit.yieldTo} property. By default the first edit will be applied. If there
15246
* are any additional edits, these will be shown to the user as selectable drop options in the drop widget.
15247
*
15248
* @param selector A selector that defines the documents this provider applies to.
15249
* @param provider A drop provider.
15250
* @param metadata Additional metadata about the provider.
15251
*
15252
* @returns A {@linkcode Disposable} that unregisters this provider when disposed of.
15253
*/
15254
export function registerDocumentDropEditProvider(selector: DocumentSelector, provider: DocumentDropEditProvider, metadata?: DocumentDropEditProviderMetadata): Disposable;
15255
15256
/**
15257
* Registers a new {@linkcode DocumentPasteEditProvider}.
15258
*
15259
* Multiple providers can be registered for a language. All registered providers for a language will be invoked
15260
* for copy and paste operations based on their handled mimetypes as specified by the {@linkcode DocumentPasteProviderMetadata}.
15261
*
15262
* For {@link DocumentPasteEditProvider.prepareDocumentPaste copy operations}, changes to the {@linkcode DataTransfer}
15263
* made by each provider will be merged into a single {@linkcode DataTransfer} that is used to populate the clipboard.
15264
*
15265
* For {@link DocumentPasteEditProvider.providerDocumentPasteEdits paste operations}, each provider will be invoked
15266
* and can return one or more {@linkcode DocumentPasteEdit DocumentPasteEdits}. The edits are sorted using
15267
* the {@linkcode DocumentPasteEdit.yieldTo} property. By default the first edit will be applied
15268
* and the rest of the edits will be shown to the user as selectable paste options in the paste widget.
15269
*
15270
* @param selector A selector that defines the documents this provider applies to.
15271
* @param provider A paste editor provider.
15272
* @param metadata Additional metadata about the provider.
15273
*
15274
* @returns A {@linkcode Disposable} that unregisters this provider when disposed of.
15275
*/
15276
export function registerDocumentPasteEditProvider(selector: DocumentSelector, provider: DocumentPasteEditProvider, metadata: DocumentPasteProviderMetadata): Disposable;
15277
15278
15279
/**
15280
* Set a {@link LanguageConfiguration language configuration} for a language.
15281
*
15282
* @param language A language identifier like `typescript`.
15283
* @param configuration Language configuration.
15284
* @returns A {@link Disposable} that unsets this configuration.
15285
*/
15286
export function setLanguageConfiguration(language: string, configuration: LanguageConfiguration): Disposable;
15287
}
15288
15289
/**
15290
* Represents a notebook editor that is attached to a {@link NotebookDocument notebook}.
15291
*/
15292
export enum NotebookEditorRevealType {
15293
/**
15294
* The range will be revealed with as little scrolling as possible.
15295
*/
15296
Default = 0,
15297
15298
/**
15299
* The range will always be revealed in the center of the viewport.
15300
*/
15301
InCenter = 1,
15302
15303
/**
15304
* If the range is outside the viewport, it will be revealed in the center of the viewport.
15305
* Otherwise, it will be revealed with as little scrolling as possible.
15306
*/
15307
InCenterIfOutsideViewport = 2,
15308
15309
/**
15310
* The range will always be revealed at the top of the viewport.
15311
*/
15312
AtTop = 3
15313
}
15314
15315
/**
15316
* Represents a notebook editor that is attached to a {@link NotebookDocument notebook}.
15317
* Additional properties of the NotebookEditor are available in the proposed
15318
* API, which will be finalized later.
15319
*/
15320
export interface NotebookEditor {
15321
15322
/**
15323
* The {@link NotebookDocument notebook document} associated with this notebook editor.
15324
*/
15325
readonly notebook: NotebookDocument;
15326
15327
/**
15328
* The primary selection in this notebook editor.
15329
*/
15330
selection: NotebookRange;
15331
15332
/**
15333
* All selections in this notebook editor.
15334
*
15335
* The primary selection (or focused range) is `selections[0]`. When the document has no cells, the primary selection is empty `{ start: 0, end: 0 }`;
15336
*/
15337
selections: readonly NotebookRange[];
15338
15339
/**
15340
* The current visible ranges in the editor (vertically).
15341
*/
15342
readonly visibleRanges: readonly NotebookRange[];
15343
15344
/**
15345
* The column in which this editor shows.
15346
*/
15347
readonly viewColumn?: ViewColumn;
15348
15349
/**
15350
* Scroll as indicated by `revealType` in order to reveal the given range.
15351
*
15352
* @param range A range.
15353
* @param revealType The scrolling strategy for revealing `range`.
15354
*/
15355
revealRange(range: NotebookRange, revealType?: NotebookEditorRevealType): void;
15356
}
15357
15358
/**
15359
* Renderer messaging is used to communicate with a single renderer. It's returned from {@link notebooks.createRendererMessaging}.
15360
*/
15361
export interface NotebookRendererMessaging {
15362
/**
15363
* An event that fires when a message is received from a renderer.
15364
*/
15365
readonly onDidReceiveMessage: Event<{
15366
/**
15367
* The {@link NotebookEditor editor} that sent the message.
15368
*/
15369
readonly editor: NotebookEditor;
15370
/**
15371
* The actual message.
15372
*/
15373
readonly message: any;
15374
}>;
15375
15376
/**
15377
* Send a message to one or all renderer.
15378
*
15379
* @param message Message to send
15380
* @param editor Editor to target with the message. If not provided, the
15381
* message is sent to all renderers.
15382
* @returns a boolean indicating whether the message was successfully
15383
* delivered to any renderer.
15384
*/
15385
postMessage(message: any, editor?: NotebookEditor): Thenable<boolean>;
15386
}
15387
15388
/**
15389
* A notebook cell kind.
15390
*/
15391
export enum NotebookCellKind {
15392
15393
/**
15394
* A markup-cell is formatted source that is used for display.
15395
*/
15396
Markup = 1,
15397
15398
/**
15399
* A code-cell is source that can be {@link NotebookController executed} and that
15400
* produces {@link NotebookCellOutput output}.
15401
*/
15402
Code = 2
15403
}
15404
15405
/**
15406
* Represents a cell of a {@link NotebookDocument notebook}, either a {@link NotebookCellKind.Code code}-cell
15407
* or {@link NotebookCellKind.Markup markup}-cell.
15408
*
15409
* NotebookCell instances are immutable and are kept in sync for as long as they are part of their notebook.
15410
*/
15411
export interface NotebookCell {
15412
15413
/**
15414
* The index of this cell in its {@link NotebookDocument.cellAt containing notebook}. The
15415
* index is updated when a cell is moved within its notebook. The index is `-1`
15416
* when the cell has been removed from its notebook.
15417
*/
15418
readonly index: number;
15419
15420
/**
15421
* The {@link NotebookDocument notebook} that contains this cell.
15422
*/
15423
readonly notebook: NotebookDocument;
15424
15425
/**
15426
* The kind of this cell.
15427
*/
15428
readonly kind: NotebookCellKind;
15429
15430
/**
15431
* The {@link TextDocument text} of this cell, represented as text document.
15432
*/
15433
readonly document: TextDocument;
15434
15435
/**
15436
* The metadata of this cell. Can be anything but must be JSON-stringifyable.
15437
*/
15438
readonly metadata: { readonly [key: string]: any };
15439
15440
/**
15441
* The outputs of this cell.
15442
*/
15443
readonly outputs: readonly NotebookCellOutput[];
15444
15445
/**
15446
* The most recent {@link NotebookCellExecutionSummary execution summary} for this cell.
15447
*/
15448
readonly executionSummary: NotebookCellExecutionSummary | undefined;
15449
}
15450
15451
/**
15452
* Represents a notebook which itself is a sequence of {@link NotebookCell code or markup cells}. Notebook documents are
15453
* created from {@link NotebookData notebook data}.
15454
*/
15455
export interface NotebookDocument {
15456
15457
/**
15458
* The associated uri for this notebook.
15459
*
15460
* *Note* that most notebooks use the `file`-scheme, which means they are files on disk. However, **not** all notebooks are
15461
* saved on disk and therefore the `scheme` must be checked before trying to access the underlying file or siblings on disk.
15462
*
15463
* @see {@link FileSystemProvider}
15464
*/
15465
readonly uri: Uri;
15466
15467
/**
15468
* The type of notebook.
15469
*/
15470
readonly notebookType: string;
15471
15472
/**
15473
* The version number of this notebook (it will strictly increase after each
15474
* change, including undo/redo).
15475
*/
15476
readonly version: number;
15477
15478
/**
15479
* `true` if there are unpersisted changes.
15480
*/
15481
readonly isDirty: boolean;
15482
15483
/**
15484
* Is this notebook representing an untitled file which has not been saved yet.
15485
*/
15486
readonly isUntitled: boolean;
15487
15488
/**
15489
* `true` if the notebook has been closed. A closed notebook isn't synchronized anymore
15490
* and won't be re-used when the same resource is opened again.
15491
*/
15492
readonly isClosed: boolean;
15493
15494
/**
15495
* Arbitrary metadata for this notebook. Can be anything but must be JSON-stringifyable.
15496
*/
15497
readonly metadata: { [key: string]: any };
15498
15499
/**
15500
* The number of cells in the notebook.
15501
*/
15502
readonly cellCount: number;
15503
15504
/**
15505
* Return the cell at the specified index. The index will be adjusted to the notebook.
15506
*
15507
* @param index - The index of the cell to retrieve.
15508
* @returns A {@link NotebookCell cell}.
15509
*/
15510
cellAt(index: number): NotebookCell;
15511
15512
/**
15513
* Get the cells of this notebook. A subset can be retrieved by providing
15514
* a range. The range will be adjusted to the notebook.
15515
*
15516
* @param range A notebook range.
15517
* @returns The cells contained by the range or all cells.
15518
*/
15519
getCells(range?: NotebookRange): NotebookCell[];
15520
15521
/**
15522
* Save the document. The saving will be handled by the corresponding {@link NotebookSerializer serializer}.
15523
*
15524
* @returns A promise that will resolve to true when the document
15525
* has been saved. Will return false if the file was not dirty or when save failed.
15526
*/
15527
save(): Thenable<boolean>;
15528
}
15529
15530
/**
15531
* Describes a change to a notebook cell.
15532
*
15533
* @see {@link NotebookDocumentChangeEvent}
15534
*/
15535
export interface NotebookDocumentCellChange {
15536
15537
/**
15538
* The affected cell.
15539
*/
15540
readonly cell: NotebookCell;
15541
15542
/**
15543
* The document of the cell or `undefined` when it did not change.
15544
*
15545
* *Note* that you should use the {@link workspace.onDidChangeTextDocument onDidChangeTextDocument}-event
15546
* for detailed change information, like what edits have been performed.
15547
*/
15548
readonly document: TextDocument | undefined;
15549
15550
/**
15551
* The new metadata of the cell or `undefined` when it did not change.
15552
*/
15553
readonly metadata: { [key: string]: any } | undefined;
15554
15555
/**
15556
* The new outputs of the cell or `undefined` when they did not change.
15557
*/
15558
readonly outputs: readonly NotebookCellOutput[] | undefined;
15559
15560
/**
15561
* The new execution summary of the cell or `undefined` when it did not change.
15562
*/
15563
readonly executionSummary: NotebookCellExecutionSummary | undefined;
15564
}
15565
15566
/**
15567
* Describes a structural change to a notebook document, e.g newly added and removed cells.
15568
*
15569
* @see {@link NotebookDocumentChangeEvent}
15570
*/
15571
export interface NotebookDocumentContentChange {
15572
15573
/**
15574
* The range at which cells have been either added or removed.
15575
*
15576
* Note that no cells have been {@link NotebookDocumentContentChange.removedCells removed}
15577
* when this range is {@link NotebookRange.isEmpty empty}.
15578
*/
15579
readonly range: NotebookRange;
15580
15581
/**
15582
* Cells that have been added to the document.
15583
*/
15584
readonly addedCells: readonly NotebookCell[];
15585
15586
/**
15587
* Cells that have been removed from the document.
15588
*/
15589
readonly removedCells: readonly NotebookCell[];
15590
}
15591
15592
/**
15593
* An event describing a transactional {@link NotebookDocument notebook} change.
15594
*/
15595
export interface NotebookDocumentChangeEvent {
15596
15597
/**
15598
* The affected notebook.
15599
*/
15600
readonly notebook: NotebookDocument;
15601
15602
/**
15603
* The new metadata of the notebook or `undefined` when it did not change.
15604
*/
15605
readonly metadata: { [key: string]: any } | undefined;
15606
15607
/**
15608
* An array of content changes describing added or removed {@link NotebookCell cells}.
15609
*/
15610
readonly contentChanges: readonly NotebookDocumentContentChange[];
15611
15612
/**
15613
* An array of {@link NotebookDocumentCellChange cell changes}.
15614
*/
15615
readonly cellChanges: readonly NotebookDocumentCellChange[];
15616
}
15617
15618
/**
15619
* An event that is fired when a {@link NotebookDocument notebook document} will be saved.
15620
*
15621
* To make modifications to the document before it is being saved, call the
15622
* {@linkcode NotebookDocumentWillSaveEvent.waitUntil waitUntil}-function with a thenable
15623
* that resolves to a {@link WorkspaceEdit workspace edit}.
15624
*/
15625
export interface NotebookDocumentWillSaveEvent {
15626
/**
15627
* A cancellation token.
15628
*/
15629
readonly token: CancellationToken;
15630
15631
/**
15632
* The {@link NotebookDocument notebook document} that will be saved.
15633
*/
15634
readonly notebook: NotebookDocument;
15635
15636
/**
15637
* The reason why save was triggered.
15638
*/
15639
readonly reason: TextDocumentSaveReason;
15640
15641
/**
15642
* Allows to pause the event loop and to apply {@link WorkspaceEdit workspace edit}.
15643
* Edits of subsequent calls to this function will be applied in order. The
15644
* edits will be *ignored* if concurrent modifications of the notebook document happened.
15645
*
15646
* *Note:* This function can only be called during event dispatch and not
15647
* in an asynchronous manner:
15648
*
15649
* ```ts
15650
* workspace.onWillSaveNotebookDocument(event => {
15651
* // async, will *throw* an error
15652
* setTimeout(() => event.waitUntil(promise));
15653
*
15654
* // sync, OK
15655
* event.waitUntil(promise);
15656
* })
15657
* ```
15658
*
15659
* @param thenable A thenable that resolves to {@link WorkspaceEdit workspace edit}.
15660
*/
15661
waitUntil(thenable: Thenable<WorkspaceEdit>): void;
15662
15663
/**
15664
* Allows to pause the event loop until the provided thenable resolved.
15665
*
15666
* *Note:* This function can only be called during event dispatch.
15667
*
15668
* @param thenable A thenable that delays saving.
15669
*/
15670
waitUntil(thenable: Thenable<any>): void;
15671
}
15672
15673
/**
15674
* The summary of a notebook cell execution.
15675
*/
15676
export interface NotebookCellExecutionSummary {
15677
15678
/**
15679
* The order in which the execution happened.
15680
*/
15681
readonly executionOrder?: number;
15682
15683
/**
15684
* If the execution finished successfully.
15685
*/
15686
readonly success?: boolean;
15687
15688
/**
15689
* The times at which execution started and ended, as unix timestamps
15690
*/
15691
readonly timing?: {
15692
/**
15693
* Execution start time.
15694
*/
15695
readonly startTime: number;
15696
/**
15697
* Execution end time.
15698
*/
15699
readonly endTime: number;
15700
};
15701
}
15702
15703
/**
15704
* A notebook range represents an ordered pair of two cell indices.
15705
* It is guaranteed that start is less than or equal to end.
15706
*/
15707
export class NotebookRange {
15708
15709
/**
15710
* The zero-based start index of this range.
15711
*/
15712
readonly start: number;
15713
15714
/**
15715
* The exclusive end index of this range (zero-based).
15716
*/
15717
readonly end: number;
15718
15719
/**
15720
* `true` if `start` and `end` are equal.
15721
*/
15722
readonly isEmpty: boolean;
15723
15724
/**
15725
* Create a new notebook range. If `start` is not
15726
* before or equal to `end`, the values will be swapped.
15727
*
15728
* @param start start index
15729
* @param end end index.
15730
*/
15731
constructor(start: number, end: number);
15732
15733
/**
15734
* Derive a new range for this range.
15735
*
15736
* @param change An object that describes a change to this range.
15737
* @returns A range that reflects the given change. Will return `this` range if the change
15738
* is not changing anything.
15739
*/
15740
with(change: {
15741
/**
15742
* New start index, defaults to `this.start`.
15743
*/
15744
start?: number;
15745
/**
15746
* New end index, defaults to `this.end`.
15747
*/
15748
end?: number;
15749
}): NotebookRange;
15750
}
15751
15752
/**
15753
* One representation of a {@link NotebookCellOutput notebook output}, defined by MIME type and data.
15754
*/
15755
export class NotebookCellOutputItem {
15756
15757
/**
15758
* Factory function to create a `NotebookCellOutputItem` from a string.
15759
*
15760
* *Note* that an UTF-8 encoder is used to create bytes for the string.
15761
*
15762
* @param value A string.
15763
* @param mime Optional MIME type, defaults to `text/plain`.
15764
* @returns A new output item object.
15765
*/
15766
static text(value: string, mime?: string): NotebookCellOutputItem;
15767
15768
/**
15769
* Factory function to create a `NotebookCellOutputItem` from
15770
* a JSON object.
15771
*
15772
* *Note* that this function is not expecting "stringified JSON" but
15773
* an object that can be stringified. This function will throw an error
15774
* when the passed value cannot be JSON-stringified.
15775
*
15776
* @param value A JSON-stringifyable value.
15777
* @param mime Optional MIME type, defaults to `application/json`
15778
* @returns A new output item object.
15779
*/
15780
static json(value: any, mime?: string): NotebookCellOutputItem;
15781
15782
/**
15783
* Factory function to create a `NotebookCellOutputItem` that uses
15784
* uses the `application/vnd.code.notebook.stdout` mime type.
15785
*
15786
* @param value A string.
15787
* @returns A new output item object.
15788
*/
15789
static stdout(value: string): NotebookCellOutputItem;
15790
15791
/**
15792
* Factory function to create a `NotebookCellOutputItem` that uses
15793
* uses the `application/vnd.code.notebook.stderr` mime type.
15794
*
15795
* @param value A string.
15796
* @returns A new output item object.
15797
*/
15798
static stderr(value: string): NotebookCellOutputItem;
15799
15800
/**
15801
* Factory function to create a `NotebookCellOutputItem` that uses
15802
* uses the `application/vnd.code.notebook.error` mime type.
15803
*
15804
* @param value An error object.
15805
* @returns A new output item object.
15806
*/
15807
static error(value: Error): NotebookCellOutputItem;
15808
15809
/**
15810
* The mime type which determines how the {@linkcode NotebookCellOutputItem.data data}-property
15811
* is interpreted.
15812
*
15813
* Notebooks have built-in support for certain mime-types, extensions can add support for new
15814
* types and override existing types.
15815
*/
15816
mime: string;
15817
15818
/**
15819
* The data of this output item. Must always be an array of unsigned 8-bit integers.
15820
*/
15821
data: Uint8Array;
15822
15823
/**
15824
* Create a new notebook cell output item.
15825
*
15826
* @param data The value of the output item.
15827
* @param mime The mime type of the output item.
15828
*/
15829
constructor(data: Uint8Array, mime: string);
15830
}
15831
15832
/**
15833
* Notebook cell output represents a result of executing a cell. It is a container type for multiple
15834
* {@link NotebookCellOutputItem output items} where contained items represent the same result but
15835
* use different MIME types.
15836
*/
15837
export class NotebookCellOutput {
15838
15839
/**
15840
* The output items of this output. Each item must represent the same result. _Note_ that repeated
15841
* MIME types per output is invalid and that the editor will just pick one of them.
15842
*
15843
* ```ts
15844
* new vscode.NotebookCellOutput([
15845
* vscode.NotebookCellOutputItem.text('Hello', 'text/plain'),
15846
* vscode.NotebookCellOutputItem.text('<i>Hello</i>', 'text/html'),
15847
* vscode.NotebookCellOutputItem.text('_Hello_', 'text/markdown'),
15848
* vscode.NotebookCellOutputItem.text('Hey', 'text/plain'), // INVALID: repeated type, editor will pick just one
15849
* ])
15850
* ```
15851
*/
15852
items: NotebookCellOutputItem[];
15853
15854
/**
15855
* Arbitrary metadata for this cell output. Can be anything but must be JSON-stringifyable.
15856
*/
15857
metadata?: { [key: string]: any };
15858
15859
/**
15860
* Create new notebook output.
15861
*
15862
* @param items Notebook output items.
15863
* @param metadata Optional metadata.
15864
*/
15865
constructor(items: NotebookCellOutputItem[], metadata?: { [key: string]: any });
15866
}
15867
15868
/**
15869
* NotebookCellData is the raw representation of notebook cells. Its is part of {@linkcode NotebookData}.
15870
*/
15871
export class NotebookCellData {
15872
15873
/**
15874
* The {@link NotebookCellKind kind} of this cell data.
15875
*/
15876
kind: NotebookCellKind;
15877
15878
/**
15879
* The source value of this cell data - either source code or formatted text.
15880
*/
15881
value: string;
15882
15883
/**
15884
* The language identifier of the source value of this cell data. Any value from
15885
* {@linkcode languages.getLanguages getLanguages} is possible.
15886
*/
15887
languageId: string;
15888
15889
/**
15890
* The outputs of this cell data.
15891
*/
15892
outputs?: NotebookCellOutput[];
15893
15894
/**
15895
* Arbitrary metadata of this cell data. Can be anything but must be JSON-stringifyable.
15896
*/
15897
metadata?: { [key: string]: any };
15898
15899
/**
15900
* The execution summary of this cell data.
15901
*/
15902
executionSummary?: NotebookCellExecutionSummary;
15903
15904
/**
15905
* Create new cell data. Minimal cell data specifies its kind, its source value, and the
15906
* language identifier of its source.
15907
*
15908
* @param kind The kind.
15909
* @param value The source value.
15910
* @param languageId The language identifier of the source value.
15911
*/
15912
constructor(kind: NotebookCellKind, value: string, languageId: string);
15913
}
15914
15915
/**
15916
* Raw representation of a notebook.
15917
*
15918
* Extensions are responsible for creating {@linkcode NotebookData} so that the editor
15919
* can create a {@linkcode NotebookDocument}.
15920
*
15921
* @see {@link NotebookSerializer}
15922
*/
15923
export class NotebookData {
15924
/**
15925
* The cell data of this notebook data.
15926
*/
15927
cells: NotebookCellData[];
15928
15929
/**
15930
* Arbitrary metadata of notebook data.
15931
*/
15932
metadata?: { [key: string]: any };
15933
15934
/**
15935
* Create new notebook data.
15936
*
15937
* @param cells An array of cell data.
15938
*/
15939
constructor(cells: NotebookCellData[]);
15940
}
15941
15942
/**
15943
* The notebook serializer enables the editor to open notebook files.
15944
*
15945
* At its core the editor only knows a {@link NotebookData notebook data structure} but not
15946
* how that data structure is written to a file, nor how it is read from a file. The
15947
* notebook serializer bridges this gap by deserializing bytes into notebook data and
15948
* vice versa.
15949
*/
15950
export interface NotebookSerializer {
15951
15952
/**
15953
* Deserialize contents of a notebook file into the notebook data structure.
15954
*
15955
* @param content Contents of a notebook file.
15956
* @param token A cancellation token.
15957
* @returns Notebook data or a thenable that resolves to such.
15958
*/
15959
deserializeNotebook(content: Uint8Array, token: CancellationToken): NotebookData | Thenable<NotebookData>;
15960
15961
/**
15962
* Serialize notebook data into file contents.
15963
*
15964
* @param data A notebook data structure.
15965
* @param token A cancellation token.
15966
* @returns An array of bytes or a thenable that resolves to such.
15967
*/
15968
serializeNotebook(data: NotebookData, token: CancellationToken): Uint8Array | Thenable<Uint8Array>;
15969
}
15970
15971
/**
15972
* Notebook content options define what parts of a notebook are persisted. Note
15973
*
15974
* For instance, a notebook serializer can opt-out of saving outputs and in that case the editor doesn't mark a
15975
* notebooks as {@link NotebookDocument.isDirty dirty} when its output has changed.
15976
*/
15977
export interface NotebookDocumentContentOptions {
15978
/**
15979
* Controls if output change events will trigger notebook document content change events and
15980
* if it will be used in the diff editor, defaults to false. If the content provider doesn't
15981
* persist the outputs in the file document, this should be set to true.
15982
*/
15983
transientOutputs?: boolean;
15984
15985
/**
15986
* Controls if a cell metadata property change event will trigger notebook document content
15987
* change events and if it will be used in the diff editor, defaults to false. If the
15988
* content provider doesn't persist a metadata property in the file document, it should be
15989
* set to true.
15990
*/
15991
transientCellMetadata?: { [key: string]: boolean | undefined };
15992
15993
/**
15994
* Controls if a document metadata property change event will trigger notebook document
15995
* content change event and if it will be used in the diff editor, defaults to false. If the
15996
* content provider doesn't persist a metadata property in the file document, it should be
15997
* set to true.
15998
*/
15999
transientDocumentMetadata?: { [key: string]: boolean | undefined };
16000
}
16001
16002
/**
16003
* Notebook controller affinity for notebook documents.
16004
*
16005
* @see {@link NotebookController.updateNotebookAffinity}
16006
*/
16007
export enum NotebookControllerAffinity {
16008
/**
16009
* Default affinity.
16010
*/
16011
Default = 1,
16012
/**
16013
* A controller is preferred for a notebook.
16014
*/
16015
Preferred = 2
16016
}
16017
16018
/**
16019
* A notebook controller represents an entity that can execute notebook cells. This is often referred to as a kernel.
16020
*
16021
* There can be multiple controllers and the editor will let users choose which controller to use for a certain notebook. The
16022
* {@linkcode NotebookController.notebookType notebookType}-property defines for what kind of notebooks a controller is for and
16023
* the {@linkcode NotebookController.updateNotebookAffinity updateNotebookAffinity}-function allows controllers to set a preference
16024
* for specific notebook documents. When a controller has been selected its
16025
* {@link NotebookController.onDidChangeSelectedNotebooks onDidChangeSelectedNotebooks}-event fires.
16026
*
16027
* When a cell is being run the editor will invoke the {@linkcode NotebookController.executeHandler executeHandler} and a controller
16028
* is expected to create and finalize a {@link NotebookCellExecution notebook cell execution}. However, controllers are also free
16029
* to create executions by themselves.
16030
*/
16031
export interface NotebookController {
16032
16033
/**
16034
* The identifier of this notebook controller.
16035
*
16036
* _Note_ that controllers are remembered by their identifier and that extensions should use
16037
* stable identifiers across sessions.
16038
*/
16039
readonly id: string;
16040
16041
/**
16042
* The notebook type this controller is for.
16043
*/
16044
readonly notebookType: string;
16045
16046
/**
16047
* An array of language identifiers that are supported by this
16048
* controller. Any language identifier from {@linkcode languages.getLanguages getLanguages}
16049
* is possible. When falsy all languages are supported.
16050
*
16051
* Samples:
16052
* ```js
16053
* // support JavaScript and TypeScript
16054
* myController.supportedLanguages = ['javascript', 'typescript']
16055
*
16056
* // support all languages
16057
* myController.supportedLanguages = undefined; // falsy
16058
* myController.supportedLanguages = []; // falsy
16059
* ```
16060
*/
16061
supportedLanguages?: string[];
16062
16063
/**
16064
* The human-readable label of this notebook controller.
16065
*/
16066
label: string;
16067
16068
/**
16069
* The human-readable description which is rendered less prominent.
16070
*/
16071
description?: string;
16072
16073
/**
16074
* The human-readable detail which is rendered less prominent.
16075
*/
16076
detail?: string;
16077
16078
/**
16079
* Whether this controller supports execution order so that the
16080
* editor can render placeholders for them.
16081
*/
16082
supportsExecutionOrder?: boolean;
16083
16084
/**
16085
* Create a cell execution task.
16086
*
16087
* _Note_ that there can only be one execution per cell at a time and that an error is thrown if
16088
* a cell execution is created while another is still active.
16089
*
16090
* This should be used in response to the {@link NotebookController.executeHandler execution handler}
16091
* being called or when cell execution has been started else, e.g when a cell was already
16092
* executing or when cell execution was triggered from another source.
16093
*
16094
* @param cell The notebook cell for which to create the execution.
16095
* @returns A notebook cell execution.
16096
*/
16097
createNotebookCellExecution(cell: NotebookCell): NotebookCellExecution;
16098
16099
/**
16100
* The execute handler is invoked when the run gestures in the UI are selected, e.g Run Cell, Run All,
16101
* Run Selection etc. The execute handler is responsible for creating and managing {@link NotebookCellExecution execution}-objects.
16102
*/
16103
executeHandler: (cells: NotebookCell[], notebook: NotebookDocument, controller: NotebookController) => void | Thenable<void>;
16104
16105
/**
16106
* Optional interrupt handler.
16107
*
16108
* By default cell execution is canceled via {@link NotebookCellExecution.token tokens}. Cancellation
16109
* tokens require that a controller can keep track of its execution so that it can cancel a specific execution at a later
16110
* point. Not all scenarios allow for that, eg. REPL-style controllers often work by interrupting whatever is currently
16111
* running. For those cases the interrupt handler exists - it can be thought of as the equivalent of `SIGINT`
16112
* or `Control+C` in terminals.
16113
*
16114
* _Note_ that supporting {@link NotebookCellExecution.token cancellation tokens} is preferred and that interrupt handlers should
16115
* only be used when tokens cannot be supported.
16116
*/
16117
interruptHandler?: (notebook: NotebookDocument) => void | Thenable<void>;
16118
16119
/**
16120
* An event that fires whenever a controller has been selected or un-selected for a notebook document.
16121
*
16122
* There can be multiple controllers for a notebook and in that case a controllers needs to be _selected_. This is a user gesture
16123
* and happens either explicitly or implicitly when interacting with a notebook for which a controller was _suggested_. When possible,
16124
* the editor _suggests_ a controller that is most likely to be _selected_.
16125
*
16126
* _Note_ that controller selection is persisted (by the controllers {@link NotebookController.id id}) and restored as soon as a
16127
* controller is re-created or as a notebook is {@link workspace.onDidOpenNotebookDocument opened}.
16128
*/
16129
readonly onDidChangeSelectedNotebooks: Event<{
16130
/**
16131
* The notebook for which the controller has been selected or un-selected.
16132
*/
16133
readonly notebook: NotebookDocument;
16134
/**
16135
* Whether the controller has been selected or un-selected.
16136
*/
16137
readonly selected: boolean;
16138
}>;
16139
16140
/**
16141
* A controller can set affinities for specific notebook documents. This allows a controller
16142
* to be presented more prominent for some notebooks.
16143
*
16144
* @param notebook The notebook for which a priority is set.
16145
* @param affinity A controller affinity
16146
*/
16147
updateNotebookAffinity(notebook: NotebookDocument, affinity: NotebookControllerAffinity): void;
16148
16149
/**
16150
* Dispose and free associated resources.
16151
*/
16152
dispose(): void;
16153
}
16154
16155
/**
16156
* A NotebookCellExecution is how {@link NotebookController notebook controller} modify a notebook cell as
16157
* it is executing.
16158
*
16159
* When a cell execution object is created, the cell enters the {@linkcode NotebookCellExecutionState.Pending Pending} state.
16160
* When {@linkcode NotebookCellExecution.start start(...)} is called on the execution task, it enters the {@linkcode NotebookCellExecutionState.Executing Executing} state. When
16161
* {@linkcode NotebookCellExecution.end end(...)} is called, it enters the {@linkcode NotebookCellExecutionState.Idle Idle} state.
16162
*/
16163
export interface NotebookCellExecution {
16164
16165
/**
16166
* The {@link NotebookCell cell} for which this execution has been created.
16167
*/
16168
readonly cell: NotebookCell;
16169
16170
/**
16171
* A cancellation token which will be triggered when the cell execution is canceled
16172
* from the UI.
16173
*
16174
* _Note_ that the cancellation token will not be triggered when the {@link NotebookController controller}
16175
* that created this execution uses an {@link NotebookController.interruptHandler interrupt-handler}.
16176
*/
16177
readonly token: CancellationToken;
16178
16179
/**
16180
* Set and unset the order of this cell execution.
16181
*/
16182
executionOrder: number | undefined;
16183
16184
/**
16185
* Signal that the execution has begun.
16186
*
16187
* @param startTime The time that execution began, in milliseconds in the Unix epoch. Used to drive the clock
16188
* that shows for how long a cell has been running. If not given, the clock won't be shown.
16189
*/
16190
start(startTime?: number): void;
16191
16192
/**
16193
* Signal that execution has ended.
16194
*
16195
* @param success If true, a green check is shown on the cell status bar.
16196
* If false, a red X is shown.
16197
* If undefined, no check or X icon is shown.
16198
* @param endTime The time that execution finished, in milliseconds in the Unix epoch.
16199
*/
16200
end(success: boolean | undefined, endTime?: number): void;
16201
16202
/**
16203
* Clears the output of the cell that is executing or of another cell that is affected by this execution.
16204
*
16205
* @param cell Cell for which output is cleared. Defaults to the {@link NotebookCellExecution.cell cell} of
16206
* this execution.
16207
* @returns A thenable that resolves when the operation finished.
16208
*/
16209
clearOutput(cell?: NotebookCell): Thenable<void>;
16210
16211
/**
16212
* Replace the output of the cell that is executing or of another cell that is affected by this execution.
16213
*
16214
* @param out Output that replaces the current output.
16215
* @param cell Cell for which output is cleared. Defaults to the {@link NotebookCellExecution.cell cell} of
16216
* this execution.
16217
* @returns A thenable that resolves when the operation finished.
16218
*/
16219
replaceOutput(out: NotebookCellOutput | readonly NotebookCellOutput[], cell?: NotebookCell): Thenable<void>;
16220
16221
/**
16222
* Append to the output of the cell that is executing or to another cell that is affected by this execution.
16223
*
16224
* @param out Output that is appended to the current output.
16225
* @param cell Cell for which output is cleared. Defaults to the {@link NotebookCellExecution.cell cell} of
16226
* this execution.
16227
* @returns A thenable that resolves when the operation finished.
16228
*/
16229
appendOutput(out: NotebookCellOutput | readonly NotebookCellOutput[], cell?: NotebookCell): Thenable<void>;
16230
16231
/**
16232
* Replace all output items of existing cell output.
16233
*
16234
* @param items Output items that replace the items of existing output.
16235
* @param output Output object that already exists.
16236
* @returns A thenable that resolves when the operation finished.
16237
*/
16238
replaceOutputItems(items: NotebookCellOutputItem | readonly NotebookCellOutputItem[], output: NotebookCellOutput): Thenable<void>;
16239
16240
/**
16241
* Append output items to existing cell output.
16242
*
16243
* @param items Output items that are append to existing output.
16244
* @param output Output object that already exists.
16245
* @returns A thenable that resolves when the operation finished.
16246
*/
16247
appendOutputItems(items: NotebookCellOutputItem | readonly NotebookCellOutputItem[], output: NotebookCellOutput): Thenable<void>;
16248
}
16249
16250
/**
16251
* Represents the alignment of status bar items.
16252
*/
16253
export enum NotebookCellStatusBarAlignment {
16254
16255
/**
16256
* Aligned to the left side.
16257
*/
16258
Left = 1,
16259
16260
/**
16261
* Aligned to the right side.
16262
*/
16263
Right = 2
16264
}
16265
16266
/**
16267
* A contribution to a cell's status bar
16268
*/
16269
export class NotebookCellStatusBarItem {
16270
/**
16271
* The text to show for the item.
16272
*/
16273
text: string;
16274
16275
/**
16276
* Whether the item is aligned to the left or right.
16277
*/
16278
alignment: NotebookCellStatusBarAlignment;
16279
16280
/**
16281
* An optional {@linkcode Command} or identifier of a command to run on click.
16282
*
16283
* The command must be {@link commands.getCommands known}.
16284
*
16285
* Note that if this is a {@linkcode Command} object, only the {@linkcode Command.command command} and {@linkcode Command.arguments arguments}
16286
* are used by the editor.
16287
*/
16288
command?: string | Command;
16289
16290
/**
16291
* A tooltip to show when the item is hovered.
16292
*/
16293
tooltip?: string;
16294
16295
/**
16296
* The priority of the item. A higher value item will be shown more to the left.
16297
*/
16298
priority?: number;
16299
16300
/**
16301
* Accessibility information used when a screen reader interacts with this item.
16302
*/
16303
accessibilityInformation?: AccessibilityInformation;
16304
16305
/**
16306
* Creates a new NotebookCellStatusBarItem.
16307
* @param text The text to show for the item.
16308
* @param alignment Whether the item is aligned to the left or right.
16309
*/
16310
constructor(text: string, alignment: NotebookCellStatusBarAlignment);
16311
}
16312
16313
/**
16314
* A provider that can contribute items to the status bar that appears below a cell's editor.
16315
*/
16316
export interface NotebookCellStatusBarItemProvider {
16317
/**
16318
* An optional event to signal that statusbar items have changed. The provide method will be called again.
16319
*/
16320
onDidChangeCellStatusBarItems?: Event<void>;
16321
16322
/**
16323
* 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.
16324
* @param cell The cell for which to return items.
16325
* @param token A token triggered if this request should be cancelled.
16326
* @returns One or more {@link NotebookCellStatusBarItem cell statusbar items}
16327
*/
16328
provideCellStatusBarItems(cell: NotebookCell, token: CancellationToken): ProviderResult<NotebookCellStatusBarItem | NotebookCellStatusBarItem[]>;
16329
}
16330
16331
/**
16332
* Namespace for notebooks.
16333
*
16334
* The notebooks functionality is composed of three loosely coupled components:
16335
*
16336
* 1. {@link NotebookSerializer} enable the editor to open, show, and save notebooks
16337
* 2. {@link NotebookController} own the execution of notebooks, e.g they create output from code cells.
16338
* 3. NotebookRenderer present notebook output in the editor. They run in a separate context.
16339
*/
16340
export namespace notebooks {
16341
16342
/**
16343
* Creates a new notebook controller.
16344
*
16345
* @param id Identifier of the controller. Must be unique per extension.
16346
* @param notebookType A notebook type for which this controller is for.
16347
* @param label The label of the controller.
16348
* @param handler The execute-handler of the controller.
16349
* @returns A new notebook controller.
16350
*/
16351
export function createNotebookController(id: string, notebookType: string, label: string, handler?: (cells: NotebookCell[], notebook: NotebookDocument, controller: NotebookController) => void | Thenable<void>): NotebookController;
16352
16353
/**
16354
* Register a {@link NotebookCellStatusBarItemProvider cell statusbar item provider} for the given notebook type.
16355
*
16356
* @param notebookType The notebook type to register for.
16357
* @param provider A cell status bar provider.
16358
* @returns A {@link Disposable} that unregisters this provider when being disposed.
16359
*/
16360
export function registerNotebookCellStatusBarItemProvider(notebookType: string, provider: NotebookCellStatusBarItemProvider): Disposable;
16361
16362
/**
16363
* Creates a new messaging instance used to communicate with a specific renderer.
16364
*
16365
* * *Note 1:* Extensions can only create renderer that they have defined in their `package.json`-file
16366
* * *Note 2:* A renderer only has access to messaging if `requiresMessaging` is set to `always` or `optional` in
16367
* its `notebookRenderer` contribution.
16368
*
16369
* @param rendererId The renderer ID to communicate with
16370
* @returns A new notebook renderer messaging object.
16371
*/
16372
export function createRendererMessaging(rendererId: string): NotebookRendererMessaging;
16373
}
16374
16375
/**
16376
* Represents the input box in the Source Control viewlet.
16377
*/
16378
export interface SourceControlInputBox {
16379
16380
/**
16381
* Setter and getter for the contents of the input box.
16382
*/
16383
value: string;
16384
16385
/**
16386
* A string to show as placeholder in the input box to guide the user.
16387
*/
16388
placeholder: string;
16389
16390
/**
16391
* Controls whether the input box is enabled (default is `true`).
16392
*/
16393
enabled: boolean;
16394
16395
/**
16396
* Controls whether the input box is visible (default is `true`).
16397
*/
16398
visible: boolean;
16399
}
16400
16401
/**
16402
* A quick diff provider provides a {@link Uri uri} to the original state of a
16403
* modified resource. The editor will use this information to render ad'hoc diffs
16404
* within the text.
16405
*/
16406
export interface QuickDiffProvider {
16407
16408
/**
16409
* Provide a {@link Uri} to the original resource of any given resource uri.
16410
*
16411
* @param uri The uri of the resource open in a text editor.
16412
* @param token A cancellation token.
16413
* @returns A thenable that resolves to uri of the matching original resource.
16414
*/
16415
provideOriginalResource?(uri: Uri, token: CancellationToken): ProviderResult<Uri>;
16416
}
16417
16418
/**
16419
* The theme-aware decorations for a
16420
* {@link SourceControlResourceState source control resource state}.
16421
*/
16422
export interface SourceControlResourceThemableDecorations {
16423
16424
/**
16425
* The icon path for a specific
16426
* {@link SourceControlResourceState source control resource state}.
16427
*/
16428
readonly iconPath?: string | Uri | ThemeIcon;
16429
}
16430
16431
/**
16432
* The decorations for a {@link SourceControlResourceState source control resource state}.
16433
* Can be independently specified for light and dark themes.
16434
*/
16435
export interface SourceControlResourceDecorations extends SourceControlResourceThemableDecorations {
16436
16437
/**
16438
* Whether the {@link SourceControlResourceState source control resource state} should
16439
* be striked-through in the UI.
16440
*/
16441
readonly strikeThrough?: boolean;
16442
16443
/**
16444
* Whether the {@link SourceControlResourceState source control resource state} should
16445
* be faded in the UI.
16446
*/
16447
readonly faded?: boolean;
16448
16449
/**
16450
* The title for a specific
16451
* {@link SourceControlResourceState source control resource state}.
16452
*/
16453
readonly tooltip?: string;
16454
16455
/**
16456
* The light theme decorations.
16457
*/
16458
readonly light?: SourceControlResourceThemableDecorations;
16459
16460
/**
16461
* The dark theme decorations.
16462
*/
16463
readonly dark?: SourceControlResourceThemableDecorations;
16464
}
16465
16466
/**
16467
* An source control resource state represents the state of an underlying workspace
16468
* resource within a certain {@link SourceControlResourceGroup source control group}.
16469
*/
16470
export interface SourceControlResourceState {
16471
16472
/**
16473
* The {@link Uri} of the underlying resource inside the workspace.
16474
*/
16475
readonly resourceUri: Uri;
16476
16477
/**
16478
* The {@link Command} which should be run when the resource
16479
* state is open in the Source Control viewlet.
16480
*/
16481
readonly command?: Command;
16482
16483
/**
16484
* The {@link SourceControlResourceDecorations decorations} for this source control
16485
* resource state.
16486
*/
16487
readonly decorations?: SourceControlResourceDecorations;
16488
16489
/**
16490
* Context value of the resource state. This can be used to contribute resource specific actions.
16491
* For example, if a resource is given a context value as `diffable`. When contributing actions to `scm/resourceState/context`
16492
* using `menus` extension point, you can specify context value for key `scmResourceState` in `when` expressions, like `scmResourceState == diffable`.
16493
* ```json
16494
* "contributes": {
16495
* "menus": {
16496
* "scm/resourceState/context": [
16497
* {
16498
* "command": "extension.diff",
16499
* "when": "scmResourceState == diffable"
16500
* }
16501
* ]
16502
* }
16503
* }
16504
* ```
16505
* This will show action `extension.diff` only for resources with `contextValue` is `diffable`.
16506
*/
16507
readonly contextValue?: string;
16508
}
16509
16510
/**
16511
* A source control resource group is a collection of
16512
* {@link SourceControlResourceState source control resource states}.
16513
*/
16514
export interface SourceControlResourceGroup {
16515
16516
/**
16517
* The id of this source control resource group.
16518
*/
16519
readonly id: string;
16520
16521
/**
16522
* The label of this source control resource group.
16523
*/
16524
label: string;
16525
16526
/**
16527
* Whether this source control resource group is hidden when it contains
16528
* no {@link SourceControlResourceState source control resource states}.
16529
*/
16530
hideWhenEmpty?: boolean;
16531
16532
/**
16533
* Context value of the resource group. This can be used to contribute resource group specific actions.
16534
* For example, if a resource group is given a context value of `exportable`, when contributing actions to `scm/resourceGroup/context`
16535
* using `menus` extension point, you can specify context value for key `scmResourceGroupState` in `when` expressions, like `scmResourceGroupState == exportable`.
16536
* ```json
16537
* "contributes": {
16538
* "menus": {
16539
* "scm/resourceGroup/context": [
16540
* {
16541
* "command": "extension.export",
16542
* "when": "scmResourceGroupState == exportable"
16543
* }
16544
* ]
16545
* }
16546
* }
16547
* ```
16548
* This will show action `extension.export` only for resource groups with `contextValue` equal to `exportable`.
16549
*/
16550
contextValue?: string;
16551
16552
/**
16553
* This group's collection of
16554
* {@link SourceControlResourceState source control resource states}.
16555
*/
16556
resourceStates: SourceControlResourceState[];
16557
16558
/**
16559
* Dispose this source control resource group.
16560
*/
16561
dispose(): void;
16562
}
16563
16564
/**
16565
* An source control is able to provide {@link SourceControlResourceState resource states}
16566
* to the editor and interact with the editor in several source control related ways.
16567
*/
16568
export interface SourceControl {
16569
16570
/**
16571
* The id of this source control.
16572
*/
16573
readonly id: string;
16574
16575
/**
16576
* The human-readable label of this source control.
16577
*/
16578
readonly label: string;
16579
16580
/**
16581
* The (optional) Uri of the root of this source control.
16582
*/
16583
readonly rootUri: Uri | undefined;
16584
16585
/**
16586
* The {@link SourceControlInputBox input box} for this source control.
16587
*/
16588
readonly inputBox: SourceControlInputBox;
16589
16590
/**
16591
* The UI-visible count of {@link SourceControlResourceState resource states} of
16592
* this source control.
16593
*
16594
* If undefined, this source control will
16595
* - display its UI-visible count as zero, and
16596
* - contribute the count of its {@link SourceControlResourceState resource states} to the UI-visible aggregated count for all source controls
16597
*/
16598
count?: number;
16599
16600
/**
16601
* An optional {@link QuickDiffProvider quick diff provider}.
16602
*/
16603
quickDiffProvider?: QuickDiffProvider;
16604
16605
/**
16606
* Optional commit template string.
16607
*
16608
* The Source Control viewlet will populate the Source Control
16609
* input with this value when appropriate.
16610
*/
16611
commitTemplate?: string;
16612
16613
/**
16614
* Optional accept input command.
16615
*
16616
* This command will be invoked when the user accepts the value
16617
* in the Source Control input.
16618
*/
16619
acceptInputCommand?: Command;
16620
16621
/**
16622
* Optional status bar commands.
16623
*
16624
* These commands will be displayed in the editor's status bar.
16625
*/
16626
statusBarCommands?: Command[];
16627
16628
/**
16629
* Create a new {@link SourceControlResourceGroup resource group}.
16630
*/
16631
createResourceGroup(id: string, label: string): SourceControlResourceGroup;
16632
16633
/**
16634
* Dispose this source control.
16635
*/
16636
dispose(): void;
16637
}
16638
16639
/**
16640
* Namespace for source control management.
16641
*/
16642
export namespace scm {
16643
16644
/**
16645
* The {@link SourceControlInputBox input box} for the last source control
16646
* created by the extension.
16647
*
16648
* @deprecated Use SourceControl.inputBox instead
16649
*/
16650
export const inputBox: SourceControlInputBox;
16651
16652
/**
16653
* Creates a new {@link SourceControl source control} instance.
16654
*
16655
* @param id An `id` for the source control. Something short, e.g.: `git`.
16656
* @param label A human-readable string for the source control. E.g.: `Git`.
16657
* @param rootUri An optional Uri of the root of the source control. E.g.: `Uri.parse(workspaceRoot)`.
16658
* @returns An instance of {@link SourceControl source control}.
16659
*/
16660
export function createSourceControl(id: string, label: string, rootUri?: Uri): SourceControl;
16661
}
16662
16663
/**
16664
* A DebugProtocolMessage is an opaque stand-in type for the [ProtocolMessage](https://microsoft.github.io/debug-adapter-protocol/specification#Base_Protocol_ProtocolMessage) type defined in the Debug Adapter Protocol.
16665
*/
16666
export interface DebugProtocolMessage {
16667
// Properties: see [ProtocolMessage details](https://microsoft.github.io/debug-adapter-protocol/specification#Base_Protocol_ProtocolMessage).
16668
}
16669
16670
/**
16671
* A DebugProtocolSource is an opaque stand-in type for the [Source](https://microsoft.github.io/debug-adapter-protocol/specification#Types_Source) type defined in the Debug Adapter Protocol.
16672
*/
16673
export interface DebugProtocolSource {
16674
// Properties: see [Source details](https://microsoft.github.io/debug-adapter-protocol/specification#Types_Source).
16675
}
16676
16677
/**
16678
* A DebugProtocolBreakpoint is an opaque stand-in type for the [Breakpoint](https://microsoft.github.io/debug-adapter-protocol/specification#Types_Breakpoint) type defined in the Debug Adapter Protocol.
16679
*/
16680
export interface DebugProtocolBreakpoint {
16681
// Properties: see [Breakpoint details](https://microsoft.github.io/debug-adapter-protocol/specification#Types_Breakpoint).
16682
}
16683
16684
/**
16685
* Configuration for a debug session.
16686
*/
16687
export interface DebugConfiguration {
16688
/**
16689
* The type of the debug session.
16690
*/
16691
type: string;
16692
16693
/**
16694
* The name of the debug session.
16695
*/
16696
name: string;
16697
16698
/**
16699
* The request type of the debug session.
16700
*/
16701
request: string;
16702
16703
/**
16704
* Additional debug type specific properties.
16705
*/
16706
[key: string]: any;
16707
}
16708
16709
/**
16710
* A debug session.
16711
*/
16712
export interface DebugSession {
16713
16714
/**
16715
* The unique ID of this debug session.
16716
*/
16717
readonly id: string;
16718
16719
/**
16720
* The debug session's type from the {@link DebugConfiguration debug configuration}.
16721
*/
16722
readonly type: string;
16723
16724
/**
16725
* The parent session of this debug session, if it was created as a child.
16726
* @see DebugSessionOptions.parentSession
16727
*/
16728
readonly parentSession?: DebugSession;
16729
16730
/**
16731
* The debug session's name is initially taken from the {@link DebugConfiguration debug configuration}.
16732
* Any changes will be properly reflected in the UI.
16733
*/
16734
name: string;
16735
16736
/**
16737
* The workspace folder of this session or `undefined` for a folderless setup.
16738
*/
16739
readonly workspaceFolder: WorkspaceFolder | undefined;
16740
16741
/**
16742
* The "resolved" {@link DebugConfiguration debug configuration} of this session.
16743
* "Resolved" means that
16744
* - all variables have been substituted and
16745
* - platform specific attribute sections have been "flattened" for the matching platform and removed for non-matching platforms.
16746
*/
16747
readonly configuration: DebugConfiguration;
16748
16749
/**
16750
* Send a custom request to the debug adapter.
16751
*/
16752
customRequest(command: string, args?: any): Thenable<any>;
16753
16754
/**
16755
* Maps a breakpoint in the editor to the corresponding Debug Adapter Protocol (DAP) breakpoint that is managed by the debug adapter of the debug session.
16756
* 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.
16757
*
16758
* @param breakpoint A {@link Breakpoint} in the editor.
16759
* @returns A promise that resolves to the Debug Adapter Protocol breakpoint or `undefined`.
16760
*/
16761
getDebugProtocolBreakpoint(breakpoint: Breakpoint): Thenable<DebugProtocolBreakpoint | undefined>;
16762
}
16763
16764
/**
16765
* A custom Debug Adapter Protocol event received from a {@link DebugSession debug session}.
16766
*/
16767
export interface DebugSessionCustomEvent {
16768
/**
16769
* The {@link DebugSession debug session} for which the custom event was received.
16770
*/
16771
readonly session: DebugSession;
16772
16773
/**
16774
* Type of event.
16775
*/
16776
readonly event: string;
16777
16778
/**
16779
* Event specific information.
16780
*/
16781
readonly body: any;
16782
}
16783
16784
/**
16785
* A debug configuration provider allows to add debug configurations to the debug service
16786
* and to resolve launch configurations before they are used to start a debug session.
16787
* A debug configuration provider is registered via {@link debug.registerDebugConfigurationProvider}.
16788
*/
16789
export interface DebugConfigurationProvider {
16790
/**
16791
* Provides {@link DebugConfiguration debug configuration} to the debug service. If more than one debug configuration provider is
16792
* registered for the same type, debug configurations are concatenated in arbitrary order.
16793
*
16794
* @param folder The workspace folder for which the configurations are used or `undefined` for a folderless setup.
16795
* @param token A cancellation token.
16796
* @returns An array of {@link DebugConfiguration debug configurations}.
16797
*/
16798
provideDebugConfigurations?(folder: WorkspaceFolder | undefined, token?: CancellationToken): ProviderResult<DebugConfiguration[]>;
16799
16800
/**
16801
* Resolves a {@link DebugConfiguration debug configuration} by filling in missing values or by adding/changing/removing attributes.
16802
* If more than one debug configuration provider is registered for the same type, the resolveDebugConfiguration calls are chained
16803
* in arbitrary order and the initial debug configuration is piped through the chain.
16804
* Returning the value 'undefined' prevents the debug session from starting.
16805
* Returning the value 'null' prevents the debug session from starting and opens the underlying debug configuration instead.
16806
*
16807
* @param folder The workspace folder from which the configuration originates from or `undefined` for a folderless setup.
16808
* @param debugConfiguration The {@link DebugConfiguration debug configuration} to resolve.
16809
* @param token A cancellation token.
16810
* @returns The resolved debug configuration or undefined or null.
16811
*/
16812
resolveDebugConfiguration?(folder: WorkspaceFolder | undefined, debugConfiguration: DebugConfiguration, token?: CancellationToken): ProviderResult<DebugConfiguration>;
16813
16814
/**
16815
* This hook is directly called after 'resolveDebugConfiguration' but with all variables substituted.
16816
* It can be used to resolve or verify a {@link DebugConfiguration debug configuration} by filling in missing values or by adding/changing/removing attributes.
16817
* If more than one debug configuration provider is registered for the same type, the 'resolveDebugConfigurationWithSubstitutedVariables' calls are chained
16818
* in arbitrary order and the initial debug configuration is piped through the chain.
16819
* Returning the value 'undefined' prevents the debug session from starting.
16820
* Returning the value 'null' prevents the debug session from starting and opens the underlying debug configuration instead.
16821
*
16822
* @param folder The workspace folder from which the configuration originates from or `undefined` for a folderless setup.
16823
* @param debugConfiguration The {@link DebugConfiguration debug configuration} to resolve.
16824
* @param token A cancellation token.
16825
* @returns The resolved debug configuration or undefined or null.
16826
*/
16827
resolveDebugConfigurationWithSubstitutedVariables?(folder: WorkspaceFolder | undefined, debugConfiguration: DebugConfiguration, token?: CancellationToken): ProviderResult<DebugConfiguration>;
16828
}
16829
16830
/**
16831
* Represents a debug adapter executable and optional arguments and runtime options passed to it.
16832
*/
16833
export class DebugAdapterExecutable {
16834
16835
/**
16836
* Creates a description for a debug adapter based on an executable program.
16837
*
16838
* @param command The command or executable path that implements the debug adapter.
16839
* @param args Optional arguments to be passed to the command or executable.
16840
* @param options Optional options to be used when starting the command or executable.
16841
*/
16842
constructor(command: string, args?: string[], options?: DebugAdapterExecutableOptions);
16843
16844
/**
16845
* The command or path of the debug adapter executable.
16846
* A command must be either an absolute path of an executable or the name of an command to be looked up via the PATH environment variable.
16847
* The special value 'node' will be mapped to the editor's built-in Node.js runtime.
16848
*/
16849
readonly command: string;
16850
16851
/**
16852
* The arguments passed to the debug adapter executable. Defaults to an empty array.
16853
*/
16854
readonly args: string[];
16855
16856
/**
16857
* Optional options to be used when the debug adapter is started.
16858
* Defaults to undefined.
16859
*/
16860
readonly options?: DebugAdapterExecutableOptions;
16861
}
16862
16863
/**
16864
* Options for a debug adapter executable.
16865
*/
16866
export interface DebugAdapterExecutableOptions {
16867
16868
/**
16869
* The additional environment of the executed program or shell. If omitted
16870
* the parent process' environment is used. If provided it is merged with
16871
* the parent process' environment.
16872
*/
16873
env?: { [key: string]: string };
16874
16875
/**
16876
* The current working directory for the executed debug adapter.
16877
*/
16878
cwd?: string;
16879
}
16880
16881
/**
16882
* Represents a debug adapter running as a socket based server.
16883
*/
16884
export class DebugAdapterServer {
16885
16886
/**
16887
* The port.
16888
*/
16889
readonly port: number;
16890
16891
/**
16892
* The host.
16893
*/
16894
readonly host?: string | undefined;
16895
16896
/**
16897
* Create a description for a debug adapter running as a socket based server.
16898
*/
16899
constructor(port: number, host?: string);
16900
}
16901
16902
/**
16903
* Represents a debug adapter running as a Named Pipe (on Windows)/UNIX Domain Socket (on non-Windows) based server.
16904
*/
16905
export class DebugAdapterNamedPipeServer {
16906
/**
16907
* The path to the NamedPipe/UNIX Domain Socket.
16908
*/
16909
readonly path: string;
16910
16911
/**
16912
* Create a description for a debug adapter running as a Named Pipe (on Windows)/UNIX Domain Socket (on non-Windows) based server.
16913
*/
16914
constructor(path: string);
16915
}
16916
16917
/**
16918
* A debug adapter that implements the Debug Adapter Protocol can be registered with the editor if it implements the DebugAdapter interface.
16919
*/
16920
export interface DebugAdapter extends Disposable {
16921
16922
/**
16923
* An event which fires after the debug adapter has sent a Debug Adapter Protocol message to the editor.
16924
* Messages can be requests, responses, or events.
16925
*/
16926
readonly onDidSendMessage: Event<DebugProtocolMessage>;
16927
16928
/**
16929
* Handle a Debug Adapter Protocol message.
16930
* Messages can be requests, responses, or events.
16931
* Results or errors are returned via onSendMessage events.
16932
* @param message A Debug Adapter Protocol message
16933
*/
16934
handleMessage(message: DebugProtocolMessage): void;
16935
}
16936
16937
/**
16938
* A debug adapter descriptor for an inline implementation.
16939
*/
16940
export class DebugAdapterInlineImplementation {
16941
16942
/**
16943
* Create a descriptor for an inline implementation of a debug adapter.
16944
*/
16945
constructor(implementation: DebugAdapter);
16946
}
16947
16948
/**
16949
* Represents the different types of debug adapters
16950
*/
16951
export type DebugAdapterDescriptor = DebugAdapterExecutable | DebugAdapterServer | DebugAdapterNamedPipeServer | DebugAdapterInlineImplementation;
16952
16953
/**
16954
* A debug adapter factory that creates {@link DebugAdapterDescriptor debug adapter descriptors}.
16955
*/
16956
export interface DebugAdapterDescriptorFactory {
16957
/**
16958
* 'createDebugAdapterDescriptor' is called at the start of a debug session to provide details about the debug adapter to use.
16959
* These details must be returned as objects of type {@link DebugAdapterDescriptor}.
16960
* Currently two types of debug adapters are supported:
16961
* - a debug adapter executable is specified as a command path and arguments (see {@link DebugAdapterExecutable}),
16962
* - a debug adapter server reachable via a communication port (see {@link DebugAdapterServer}).
16963
* If the method is not implemented the default behavior is this:
16964
* createDebugAdapter(session: DebugSession, executable: DebugAdapterExecutable) {
16965
* if (typeof session.configuration.debugServer === 'number') {
16966
* return new DebugAdapterServer(session.configuration.debugServer);
16967
* }
16968
* return executable;
16969
* }
16970
* @param session The {@link DebugSession debug session} for which the debug adapter will be used.
16971
* @param executable The debug adapter's executable information as specified in the package.json (or undefined if no such information exists).
16972
* @returns a {@link DebugAdapterDescriptor debug adapter descriptor} or undefined.
16973
*/
16974
createDebugAdapterDescriptor(session: DebugSession, executable: DebugAdapterExecutable | undefined): ProviderResult<DebugAdapterDescriptor>;
16975
}
16976
16977
/**
16978
* A Debug Adapter Tracker is a means to track the communication between the editor and a Debug Adapter.
16979
*/
16980
export interface DebugAdapterTracker {
16981
/**
16982
* A session with the debug adapter is about to be started.
16983
*/
16984
onWillStartSession?(): void;
16985
/**
16986
* The debug adapter is about to receive a Debug Adapter Protocol message from the editor.
16987
*/
16988
onWillReceiveMessage?(message: any): void;
16989
/**
16990
* The debug adapter has sent a Debug Adapter Protocol message to the editor.
16991
*/
16992
onDidSendMessage?(message: any): void;
16993
/**
16994
* The debug adapter session is about to be stopped.
16995
*/
16996
onWillStopSession?(): void;
16997
/**
16998
* An error with the debug adapter has occurred.
16999
*/
17000
onError?(error: Error): void;
17001
/**
17002
* The debug adapter has exited with the given exit code or signal.
17003
*/
17004
onExit?(code: number | undefined, signal: string | undefined): void;
17005
}
17006
17007
/**
17008
* A debug adapter factory that creates {@link DebugAdapterTracker debug adapter trackers}.
17009
*/
17010
export interface DebugAdapterTrackerFactory {
17011
/**
17012
* The method 'createDebugAdapterTracker' is called at the start of a debug session in order
17013
* to return a "tracker" object that provides read-access to the communication between the editor and a debug adapter.
17014
*
17015
* @param session The {@link DebugSession debug session} for which the debug adapter tracker will be used.
17016
* @returns A {@link DebugAdapterTracker debug adapter tracker} or undefined.
17017
*/
17018
createDebugAdapterTracker(session: DebugSession): ProviderResult<DebugAdapterTracker>;
17019
}
17020
17021
/**
17022
* Represents the debug console.
17023
*/
17024
export interface DebugConsole {
17025
/**
17026
* Append the given value to the debug console.
17027
*
17028
* @param value A string, falsy values will not be printed.
17029
*/
17030
append(value: string): void;
17031
17032
/**
17033
* Append the given value and a line feed character
17034
* to the debug console.
17035
*
17036
* @param value A string, falsy values will be printed.
17037
*/
17038
appendLine(value: string): void;
17039
}
17040
17041
/**
17042
* An event describing the changes to the set of {@link Breakpoint breakpoints}.
17043
*/
17044
export interface BreakpointsChangeEvent {
17045
/**
17046
* Added breakpoints.
17047
*/
17048
readonly added: readonly Breakpoint[];
17049
17050
/**
17051
* Removed breakpoints.
17052
*/
17053
readonly removed: readonly Breakpoint[];
17054
17055
/**
17056
* Changed breakpoints.
17057
*/
17058
readonly changed: readonly Breakpoint[];
17059
}
17060
17061
/**
17062
* The base class of all breakpoint types.
17063
*/
17064
export class Breakpoint {
17065
/**
17066
* The unique ID of the breakpoint.
17067
*/
17068
readonly id: string;
17069
/**
17070
* Is breakpoint enabled.
17071
*/
17072
readonly enabled: boolean;
17073
/**
17074
* An optional expression for conditional breakpoints.
17075
*/
17076
readonly condition?: string | undefined;
17077
/**
17078
* An optional expression that controls how many hits of the breakpoint are ignored.
17079
*/
17080
readonly hitCondition?: string | undefined;
17081
/**
17082
* An optional message that gets logged when this breakpoint is hit. Embedded expressions within {} are interpolated by the debug adapter.
17083
*/
17084
readonly logMessage?: string | undefined;
17085
17086
/**
17087
* Creates a new breakpoint
17088
*
17089
* @param enabled Is breakpoint enabled.
17090
* @param condition Expression for conditional breakpoints
17091
* @param hitCondition Expression that controls how many hits of the breakpoint are ignored
17092
* @param logMessage Log message to display when breakpoint is hit
17093
*/
17094
protected constructor(enabled?: boolean, condition?: string, hitCondition?: string, logMessage?: string);
17095
}
17096
17097
/**
17098
* A breakpoint specified by a source location.
17099
*/
17100
export class SourceBreakpoint extends Breakpoint {
17101
/**
17102
* The source and line position of this breakpoint.
17103
*/
17104
readonly location: Location;
17105
17106
/**
17107
* Create a new breakpoint for a source location.
17108
*/
17109
constructor(location: Location, enabled?: boolean, condition?: string, hitCondition?: string, logMessage?: string);
17110
}
17111
17112
/**
17113
* A breakpoint specified by a function name.
17114
*/
17115
export class FunctionBreakpoint extends Breakpoint {
17116
/**
17117
* The name of the function to which this breakpoint is attached.
17118
*/
17119
readonly functionName: string;
17120
17121
/**
17122
* Create a new function breakpoint.
17123
*/
17124
constructor(functionName: string, enabled?: boolean, condition?: string, hitCondition?: string, logMessage?: string);
17125
}
17126
17127
/**
17128
* Debug console mode used by debug session, see {@link DebugSessionOptions options}.
17129
*/
17130
export enum DebugConsoleMode {
17131
/**
17132
* Debug session should have a separate debug console.
17133
*/
17134
Separate = 0,
17135
17136
/**
17137
* Debug session should share debug console with its parent session.
17138
* This value has no effect for sessions which do not have a parent session.
17139
*/
17140
MergeWithParent = 1
17141
}
17142
17143
/**
17144
* Options for {@link debug.startDebugging starting a debug session}.
17145
*/
17146
export interface DebugSessionOptions {
17147
17148
/**
17149
* When specified the newly created debug session is registered as a "child" session of this
17150
* "parent" debug session.
17151
*/
17152
parentSession?: DebugSession;
17153
17154
/**
17155
* Controls whether lifecycle requests like 'restart' are sent to the newly created session or its parent session.
17156
* By default (if the property is false or missing), lifecycle requests are sent to the new session.
17157
* This property is ignored if the session has no parent session.
17158
*/
17159
lifecycleManagedByParent?: boolean;
17160
17161
/**
17162
* Controls whether this session should have a separate debug console or share it
17163
* with the parent session. Has no effect for sessions which do not have a parent session.
17164
* Defaults to Separate.
17165
*/
17166
consoleMode?: DebugConsoleMode;
17167
17168
/**
17169
* Controls whether this session should run without debugging, thus ignoring breakpoints.
17170
* When this property is not specified, the value from the parent session (if there is one) is used.
17171
*/
17172
noDebug?: boolean;
17173
17174
/**
17175
* Controls if the debug session's parent session is shown in the CALL STACK view even if it has only a single child.
17176
* By default, the debug session will never hide its parent.
17177
* If compact is true, debug sessions with a single child are hidden in the CALL STACK view to make the tree more compact.
17178
*/
17179
compact?: boolean;
17180
17181
/**
17182
* 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.
17183
*/
17184
suppressSaveBeforeStart?: boolean;
17185
17186
/**
17187
* When true, the debug toolbar will not be shown for this session.
17188
*/
17189
suppressDebugToolbar?: boolean;
17190
17191
/**
17192
* When true, the window statusbar color will not be changed for this session.
17193
*/
17194
suppressDebugStatusbar?: boolean;
17195
17196
/**
17197
* When true, the debug viewlet will not be automatically revealed for this session.
17198
*/
17199
suppressDebugView?: boolean;
17200
17201
/**
17202
* Signals to the editor that the debug session was started from a test run
17203
* request. This is used to link the lifecycle of the debug session and
17204
* test run in UI actions.
17205
*/
17206
testRun?: TestRun;
17207
}
17208
17209
/**
17210
* A DebugConfigurationProviderTriggerKind specifies when the `provideDebugConfigurations` method of a `DebugConfigurationProvider` is triggered.
17211
* Currently there are two situations: to provide the initial debug configurations for a newly created launch.json or
17212
* to provide dynamically generated debug configurations when the user asks for them through the UI (e.g. via the "Select and Start Debugging" command).
17213
* A trigger kind is used when registering a `DebugConfigurationProvider` with {@link debug.registerDebugConfigurationProvider}.
17214
*/
17215
export enum DebugConfigurationProviderTriggerKind {
17216
/**
17217
* `DebugConfigurationProvider.provideDebugConfigurations` is called to provide the initial debug configurations for a newly created launch.json.
17218
*/
17219
Initial = 1,
17220
/**
17221
* `DebugConfigurationProvider.provideDebugConfigurations` is called to provide dynamically generated debug configurations when the user asks for them through the UI (e.g. via the "Select and Start Debugging" command).
17222
*/
17223
Dynamic = 2
17224
}
17225
17226
/**
17227
* Represents a thread in a debug session.
17228
*/
17229
export class DebugThread {
17230
/**
17231
* Debug session for thread.
17232
*/
17233
readonly session: DebugSession;
17234
17235
/**
17236
* ID of the associated thread in the debug protocol.
17237
*/
17238
readonly threadId: number;
17239
17240
/**
17241
* @hidden
17242
*/
17243
private constructor(session: DebugSession, threadId: number);
17244
}
17245
17246
/**
17247
* Represents a stack frame in a debug session.
17248
*/
17249
export class DebugStackFrame {
17250
/**
17251
* Debug session for thread.
17252
*/
17253
readonly session: DebugSession;
17254
17255
/**
17256
* ID of the associated thread in the debug protocol.
17257
*/
17258
readonly threadId: number;
17259
/**
17260
* ID of the stack frame in the debug protocol.
17261
*/
17262
readonly frameId: number;
17263
17264
/**
17265
* @hidden
17266
*/
17267
private constructor(session: DebugSession, threadId: number, frameId: number);
17268
}
17269
17270
/**
17271
* Namespace for debug functionality.
17272
*/
17273
export namespace debug {
17274
17275
/**
17276
* The currently active {@link DebugSession debug session} or `undefined`. The active debug session is the one
17277
* represented by the debug action floating window or the one currently shown in the drop down menu of the debug action floating window.
17278
* If no debug session is active, the value is `undefined`.
17279
*/
17280
export let activeDebugSession: DebugSession | undefined;
17281
17282
/**
17283
* The currently active {@link DebugConsole debug console}.
17284
* If no debug session is active, output sent to the debug console is not shown.
17285
*/
17286
export let activeDebugConsole: DebugConsole;
17287
17288
/**
17289
* List of breakpoints.
17290
*/
17291
export let breakpoints: readonly Breakpoint[];
17292
17293
/**
17294
* An {@link Event} which fires when the {@link debug.activeDebugSession active debug session}
17295
* has changed. *Note* that the event also fires when the active debug session changes
17296
* to `undefined`.
17297
*/
17298
export const onDidChangeActiveDebugSession: Event<DebugSession | undefined>;
17299
17300
/**
17301
* An {@link Event} which fires when a new {@link DebugSession debug session} has been started.
17302
*/
17303
export const onDidStartDebugSession: Event<DebugSession>;
17304
17305
/**
17306
* An {@link Event} which fires when a custom DAP event is received from the {@link DebugSession debug session}.
17307
*/
17308
export const onDidReceiveDebugSessionCustomEvent: Event<DebugSessionCustomEvent>;
17309
17310
/**
17311
* An {@link Event} which fires when a {@link DebugSession debug session} has terminated.
17312
*/
17313
export const onDidTerminateDebugSession: Event<DebugSession>;
17314
17315
/**
17316
* An {@link Event} that is emitted when the set of breakpoints is added, removed, or changed.
17317
*/
17318
export const onDidChangeBreakpoints: Event<BreakpointsChangeEvent>;
17319
17320
/**
17321
* The currently focused thread or stack frame, or `undefined` if no
17322
* thread or stack is focused. A thread can be focused any time there is
17323
* an active debug session, while a stack frame can only be focused when
17324
* a session is paused and the call stack has been retrieved.
17325
*/
17326
export const activeStackItem: DebugThread | DebugStackFrame | undefined;
17327
17328
/**
17329
* An event which fires when the {@link debug.activeStackItem} has changed.
17330
*/
17331
export const onDidChangeActiveStackItem: Event<DebugThread | DebugStackFrame | undefined>;
17332
17333
/**
17334
* Register a {@link DebugConfigurationProvider debug configuration provider} for a specific debug type.
17335
* The optional {@link DebugConfigurationProviderTriggerKind triggerKind} can be used to specify when the `provideDebugConfigurations` method of the provider is triggered.
17336
* Currently two trigger kinds are possible: with the value `Initial` (or if no trigger kind argument is given) the `provideDebugConfigurations` method is used to provide the initial debug configurations to be copied into a newly created launch.json.
17337
* With the trigger kind `Dynamic` the `provideDebugConfigurations` method is used to dynamically determine debug configurations to be presented to the user (in addition to the static configurations from the launch.json).
17338
* Please note that the `triggerKind` argument only applies to the `provideDebugConfigurations` method: so the `resolveDebugConfiguration` methods are not affected at all.
17339
* Registering a single provider with resolve methods for different trigger kinds, results in the same resolve methods called multiple times.
17340
* More than one provider can be registered for the same type.
17341
*
17342
* @param debugType The debug type for which the provider is registered.
17343
* @param provider The {@link DebugConfigurationProvider debug configuration provider} to register.
17344
* @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.
17345
* @returns A {@link Disposable} that unregisters this provider when being disposed.
17346
*/
17347
export function registerDebugConfigurationProvider(debugType: string, provider: DebugConfigurationProvider, triggerKind?: DebugConfigurationProviderTriggerKind): Disposable;
17348
17349
/**
17350
* Register a {@link DebugAdapterDescriptorFactory debug adapter descriptor factory} for a specific debug type.
17351
* An extension is only allowed to register a DebugAdapterDescriptorFactory for the debug type(s) defined by the extension. Otherwise an error is thrown.
17352
* Registering more than one DebugAdapterDescriptorFactory for a debug type results in an error.
17353
*
17354
* @param debugType The debug type for which the factory is registered.
17355
* @param factory The {@link DebugAdapterDescriptorFactory debug adapter descriptor factory} to register.
17356
* @returns A {@link Disposable} that unregisters this factory when being disposed.
17357
*/
17358
export function registerDebugAdapterDescriptorFactory(debugType: string, factory: DebugAdapterDescriptorFactory): Disposable;
17359
17360
/**
17361
* Register a debug adapter tracker factory for the given debug type.
17362
*
17363
* @param debugType The debug type for which the factory is registered or '*' for matching all debug types.
17364
* @param factory The {@link DebugAdapterTrackerFactory debug adapter tracker factory} to register.
17365
* @returns A {@link Disposable} that unregisters this factory when being disposed.
17366
*/
17367
export function registerDebugAdapterTrackerFactory(debugType: string, factory: DebugAdapterTrackerFactory): Disposable;
17368
17369
/**
17370
* Start debugging by using either a named launch or named compound configuration,
17371
* or by directly passing a {@link DebugConfiguration}.
17372
* The named configurations are looked up in '.vscode/launch.json' found in the given folder.
17373
* Before debugging starts, all unsaved files are saved and the launch configurations are brought up-to-date.
17374
* Folder specific variables used in the configuration (e.g. '${workspaceFolder}') are resolved against the given folder.
17375
* @param folder The {@link WorkspaceFolder workspace folder} for looking up named configurations and resolving variables or `undefined` for a non-folder setup.
17376
* @param nameOrConfiguration Either the name of a debug or compound configuration or a {@link DebugConfiguration} object.
17377
* @param parentSessionOrOptions Debug session options. When passed a parent {@link DebugSession debug session}, assumes options with just this parent session.
17378
* @returns A thenable that resolves when debugging could be successfully started.
17379
*/
17380
export function startDebugging(folder: WorkspaceFolder | undefined, nameOrConfiguration: string | DebugConfiguration, parentSessionOrOptions?: DebugSession | DebugSessionOptions): Thenable<boolean>;
17381
17382
/**
17383
* Stop the given debug session or stop all debug sessions if session is omitted.
17384
*
17385
* @param session The {@link DebugSession debug session} to stop; if omitted all sessions are stopped.
17386
* @returns A thenable that resolves when the session(s) have been stopped.
17387
*/
17388
export function stopDebugging(session?: DebugSession): Thenable<void>;
17389
17390
/**
17391
* Add breakpoints.
17392
* @param breakpoints The breakpoints to add.
17393
*/
17394
export function addBreakpoints(breakpoints: readonly Breakpoint[]): void;
17395
17396
/**
17397
* Remove breakpoints.
17398
* @param breakpoints The breakpoints to remove.
17399
*/
17400
export function removeBreakpoints(breakpoints: readonly Breakpoint[]): void;
17401
17402
/**
17403
* Converts a "Source" descriptor object received via the Debug Adapter Protocol into a Uri that can be used to load its contents.
17404
* If the source descriptor is based on a path, a file Uri is returned.
17405
* If the source descriptor uses a reference number, a specific debug Uri (scheme 'debug') is constructed that requires a corresponding ContentProvider and a running debug session
17406
*
17407
* If the "Source" descriptor has insufficient information for creating the Uri, an error is thrown.
17408
*
17409
* @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.
17410
* @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.
17411
* @returns A uri that can be used to load the contents of the source.
17412
*/
17413
export function asDebugSourceUri(source: DebugProtocolSource, session?: DebugSession): Uri;
17414
}
17415
17416
/**
17417
* Namespace for dealing with installed extensions. Extensions are represented
17418
* by an {@link Extension}-interface which enables reflection on them.
17419
*
17420
* Extension writers can provide APIs to other extensions by returning their API public
17421
* surface from the `activate`-call.
17422
*
17423
* ```javascript
17424
* export function activate(context: vscode.ExtensionContext) {
17425
* let api = {
17426
* sum(a, b) {
17427
* return a + b;
17428
* },
17429
* mul(a, b) {
17430
* return a * b;
17431
* }
17432
* };
17433
* // 'export' public api-surface
17434
* return api;
17435
* }
17436
* ```
17437
* When depending on the API of another extension add an `extensionDependencies`-entry
17438
* to `package.json`, and use the {@link extensions.getExtension getExtension}-function
17439
* and the {@link Extension.exports exports}-property, like below:
17440
*
17441
* ```javascript
17442
* let mathExt = extensions.getExtension('genius.math');
17443
* let importedApi = mathExt.exports;
17444
*
17445
* console.log(importedApi.mul(42, 1));
17446
* ```
17447
*/
17448
export namespace extensions {
17449
17450
/**
17451
* Get an extension by its full identifier in the form of: `publisher.name`.
17452
*
17453
* @param extensionId An extension identifier.
17454
* @returns An extension or `undefined`.
17455
*/
17456
export function getExtension<T = any>(extensionId: string): Extension<T> | undefined;
17457
17458
/**
17459
* All extensions currently known to the system.
17460
*/
17461
export const all: readonly Extension<any>[];
17462
17463
/**
17464
* An event which fires when `extensions.all` changes. This can happen when extensions are
17465
* installed, uninstalled, enabled or disabled.
17466
*/
17467
export const onDidChange: Event<void>;
17468
}
17469
17470
/**
17471
* Collapsible state of a {@link CommentThread comment thread}
17472
*/
17473
export enum CommentThreadCollapsibleState {
17474
/**
17475
* Determines an item is collapsed
17476
*/
17477
Collapsed = 0,
17478
17479
/**
17480
* Determines an item is expanded
17481
*/
17482
Expanded = 1
17483
}
17484
17485
/**
17486
* Comment mode of a {@link Comment}
17487
*/
17488
export enum CommentMode {
17489
/**
17490
* Displays the comment editor
17491
*/
17492
Editing = 0,
17493
17494
/**
17495
* Displays the preview of the comment
17496
*/
17497
Preview = 1
17498
}
17499
17500
/**
17501
* The state of a comment thread.
17502
*/
17503
export enum CommentThreadState {
17504
/**
17505
* Unresolved thread state
17506
*/
17507
Unresolved = 0,
17508
/**
17509
* Resolved thread state
17510
*/
17511
Resolved = 1
17512
}
17513
17514
/**
17515
* A collection of {@link Comment comments} representing a conversation at a particular range in a document.
17516
*/
17517
export interface CommentThread {
17518
/**
17519
* The uri of the document the thread has been created on.
17520
*/
17521
readonly uri: Uri;
17522
17523
/**
17524
* The range the comment thread is located within the document. The thread icon will be shown
17525
* at the last line of the range. When set to undefined, the comment will be associated with the
17526
* file, and not a specific range.
17527
*/
17528
range: Range | undefined;
17529
17530
/**
17531
* The ordered comments of the thread.
17532
*/
17533
comments: readonly Comment[];
17534
17535
/**
17536
* Whether the thread should be collapsed or expanded when opening the document.
17537
* Defaults to Collapsed.
17538
*/
17539
collapsibleState: CommentThreadCollapsibleState;
17540
17541
/**
17542
* Whether the thread supports reply.
17543
* Defaults to true.
17544
*/
17545
canReply: boolean | CommentAuthorInformation;
17546
17547
/**
17548
* Context value of the comment thread. This can be used to contribute thread specific actions.
17549
* For example, a comment thread is given a context value as `editable`. When contributing actions to `comments/commentThread/title`
17550
* using `menus` extension point, you can specify context value for key `commentThread` in `when` expression like `commentThread == editable`.
17551
* ```json
17552
* "contributes": {
17553
* "menus": {
17554
* "comments/commentThread/title": [
17555
* {
17556
* "command": "extension.deleteCommentThread",
17557
* "when": "commentThread == editable"
17558
* }
17559
* ]
17560
* }
17561
* }
17562
* ```
17563
* This will show action `extension.deleteCommentThread` only for comment threads with `contextValue` is `editable`.
17564
*/
17565
contextValue?: string;
17566
17567
/**
17568
* The optional human-readable label describing the {@link CommentThread Comment Thread}
17569
*/
17570
label?: string;
17571
17572
/**
17573
* The optional state of a comment thread, which may affect how the comment is displayed.
17574
*/
17575
state?: CommentThreadState;
17576
17577
/**
17578
* Dispose this comment thread.
17579
*
17580
* Once disposed, this comment thread will be removed from visible editors and Comment Panel when appropriate.
17581
*/
17582
dispose(): void;
17583
}
17584
17585
/**
17586
* Author information of a {@link Comment}
17587
*/
17588
export interface CommentAuthorInformation {
17589
/**
17590
* The display name of the author of the comment
17591
*/
17592
name: string;
17593
17594
/**
17595
* The optional icon path for the author
17596
*/
17597
iconPath?: Uri;
17598
}
17599
17600
/**
17601
* Reactions of a {@link Comment}
17602
*/
17603
export interface CommentReaction {
17604
/**
17605
* The human-readable label for the reaction
17606
*/
17607
readonly label: string;
17608
17609
/**
17610
* Icon for the reaction shown in UI.
17611
*/
17612
readonly iconPath: string | Uri;
17613
17614
/**
17615
* The number of users who have reacted to this reaction
17616
*/
17617
readonly count: number;
17618
17619
/**
17620
* Whether the {@link CommentAuthorInformation author} of the comment has reacted to this reaction
17621
*/
17622
readonly authorHasReacted: boolean;
17623
}
17624
17625
/**
17626
* A comment is displayed within the editor or the Comments Panel, depending on how it is provided.
17627
*/
17628
export interface Comment {
17629
/**
17630
* The human-readable comment body
17631
*/
17632
body: string | MarkdownString;
17633
17634
/**
17635
* {@link CommentMode Comment mode} of the comment
17636
*/
17637
mode: CommentMode;
17638
17639
/**
17640
* The {@link CommentAuthorInformation author information} of the comment
17641
*/
17642
author: CommentAuthorInformation;
17643
17644
/**
17645
* Context value of the comment. This can be used to contribute comment specific actions.
17646
* For example, a comment is given a context value as `editable`. When contributing actions to `comments/comment/title`
17647
* using `menus` extension point, you can specify context value for key `comment` in `when` expression like `comment == editable`.
17648
* ```json
17649
* "contributes": {
17650
* "menus": {
17651
* "comments/comment/title": [
17652
* {
17653
* "command": "extension.deleteComment",
17654
* "when": "comment == editable"
17655
* }
17656
* ]
17657
* }
17658
* }
17659
* ```
17660
* This will show action `extension.deleteComment` only for comments with `contextValue` is `editable`.
17661
*/
17662
contextValue?: string;
17663
17664
/**
17665
* Optional reactions of the {@link Comment}
17666
*/
17667
reactions?: CommentReaction[];
17668
17669
/**
17670
* Optional label describing the {@link Comment}
17671
* Label will be rendered next to authorName if exists.
17672
*/
17673
label?: string;
17674
17675
/**
17676
* Optional timestamp that will be displayed in comments.
17677
* The date will be formatted according to the user's locale and settings.
17678
*/
17679
timestamp?: Date;
17680
}
17681
17682
/**
17683
* Command argument for actions registered in `comments/commentThread/context`.
17684
*/
17685
export interface CommentReply {
17686
/**
17687
* The active {@link CommentThread comment thread}
17688
*/
17689
thread: CommentThread;
17690
17691
/**
17692
* The value in the comment editor
17693
*/
17694
text: string;
17695
}
17696
17697
/**
17698
* The ranges a CommentingRangeProvider enables commenting on.
17699
*/
17700
export interface CommentingRanges {
17701
/**
17702
* Enables comments to be added to a file without a specific range.
17703
*/
17704
enableFileComments: boolean;
17705
17706
/**
17707
* The ranges which allow new comment threads creation.
17708
*/
17709
ranges?: Range[];
17710
}
17711
17712
/**
17713
* Commenting range provider for a {@link CommentController comment controller}.
17714
*/
17715
export interface CommentingRangeProvider {
17716
/**
17717
* Provide a list of ranges which allow new comment threads creation or null for a given document
17718
*/
17719
provideCommentingRanges(document: TextDocument, token: CancellationToken): ProviderResult<Range[] | CommentingRanges>;
17720
}
17721
17722
/**
17723
* Represents a {@link CommentController comment controller}'s {@link CommentController.options options}.
17724
*/
17725
export interface CommentOptions {
17726
/**
17727
* An optional string to show on the comment input box when it's collapsed.
17728
*/
17729
prompt?: string;
17730
17731
/**
17732
* An optional string to show as placeholder in the comment input box when it's focused.
17733
*/
17734
placeHolder?: string;
17735
}
17736
17737
/**
17738
* A comment controller is able to provide {@link CommentThread comments} support to the editor and
17739
* provide users various ways to interact with comments.
17740
*/
17741
export interface CommentController {
17742
/**
17743
* The id of this comment controller.
17744
*/
17745
readonly id: string;
17746
17747
/**
17748
* The human-readable label of this comment controller.
17749
*/
17750
readonly label: string;
17751
17752
/**
17753
* Comment controller options
17754
*/
17755
options?: CommentOptions;
17756
17757
/**
17758
* Optional commenting range provider. Provide a list {@link Range ranges} which support commenting to any given resource uri.
17759
*
17760
* If not provided, users cannot leave any comments.
17761
*/
17762
commentingRangeProvider?: CommentingRangeProvider;
17763
17764
/**
17765
* Create a {@link CommentThread comment thread}. The comment thread will be displayed in visible text editors (if the resource matches)
17766
* and Comments Panel once created.
17767
*
17768
* @param uri The uri of the document the thread has been created on.
17769
* @param range The range the comment thread is located within the document.
17770
* @param comments The ordered comments of the thread.
17771
*/
17772
createCommentThread(uri: Uri, range: Range, comments: readonly Comment[]): CommentThread;
17773
17774
/**
17775
* Optional reaction handler for creating and deleting reactions on a {@link Comment}.
17776
*/
17777
reactionHandler?: (comment: Comment, reaction: CommentReaction) => Thenable<void>;
17778
17779
/**
17780
* Dispose this comment controller.
17781
*
17782
* Once disposed, all {@link CommentThread comment threads} created by this comment controller will also be removed from the editor
17783
* and Comments Panel.
17784
*/
17785
dispose(): void;
17786
}
17787
17788
namespace comments {
17789
/**
17790
* Creates a new {@link CommentController comment controller} instance.
17791
*
17792
* @param id An `id` for the comment controller.
17793
* @param label A human-readable string for the comment controller.
17794
* @returns An instance of {@link CommentController comment controller}.
17795
*/
17796
export function createCommentController(id: string, label: string): CommentController;
17797
}
17798
17799
/**
17800
* Represents a session of a currently logged in user.
17801
*/
17802
export interface AuthenticationSession {
17803
/**
17804
* The identifier of the authentication session.
17805
*/
17806
readonly id: string;
17807
17808
/**
17809
* The access token. This token should be used to authenticate requests to a service. Popularized by OAuth.
17810
* @reference https://oauth.net/2/access-tokens/
17811
*/
17812
readonly accessToken: string;
17813
17814
/**
17815
* The ID token. This token contains identity information about the user. Popularized by OpenID Connect.
17816
* @reference https://openid.net/specs/openid-connect-core-1_0.html#IDToken
17817
*/
17818
readonly idToken?: string;
17819
17820
/**
17821
* The account associated with the session.
17822
*/
17823
readonly account: AuthenticationSessionAccountInformation;
17824
17825
/**
17826
* The permissions granted by the session's access token. Available scopes
17827
* are defined by the {@link AuthenticationProvider}.
17828
*/
17829
readonly scopes: readonly string[];
17830
}
17831
17832
/**
17833
* The information of an account associated with an {@link AuthenticationSession}.
17834
*/
17835
export interface AuthenticationSessionAccountInformation {
17836
/**
17837
* The unique identifier of the account.
17838
*/
17839
readonly id: string;
17840
17841
/**
17842
* The human-readable name of the account.
17843
*/
17844
readonly label: string;
17845
}
17846
17847
/**
17848
* Optional options to be used when calling {@link authentication.getSession} with interactive options `forceNewSession` & `createIfNone`.
17849
*/
17850
export interface AuthenticationGetSessionPresentationOptions {
17851
/**
17852
* An optional message that will be displayed to the user when we ask to re-authenticate. Providing additional context
17853
* as to why you are asking a user to re-authenticate can help increase the odds that they will accept.
17854
*/
17855
detail?: string;
17856
}
17857
17858
/**
17859
* Optional options to be used when calling {@link authentication.getSession} with the flag `forceNewSession`.
17860
* @deprecated Use {@link AuthenticationGetSessionPresentationOptions} instead.
17861
*/
17862
export type AuthenticationForceNewSessionOptions = AuthenticationGetSessionPresentationOptions;
17863
17864
/**
17865
* Options to be used when getting an {@link AuthenticationSession} from an {@link AuthenticationProvider}.
17866
*/
17867
export interface AuthenticationGetSessionOptions {
17868
/**
17869
* Whether the existing session preference should be cleared.
17870
*
17871
* For authentication providers that support being signed into multiple accounts at once, the user will be
17872
* prompted to select an account to use when {@link authentication.getSession getSession} is called. This preference
17873
* is remembered until {@link authentication.getSession getSession} is called with this flag.
17874
*
17875
* Note:
17876
* The preference is extension specific. So if one extension calls {@link authentication.getSession getSession}, it will not
17877
* affect the session preference for another extension calling {@link authentication.getSession getSession}. Additionally,
17878
* the preference is set for the current workspace and also globally. This means that new workspaces will use the "global"
17879
* value at first and then when this flag is provided, a new value can be set for that workspace. This also means
17880
* that pre-existing workspaces will not lose their preference if a new workspace sets this flag.
17881
*
17882
* Defaults to false.
17883
*/
17884
clearSessionPreference?: boolean;
17885
17886
/**
17887
* Whether login should be performed if there is no matching session.
17888
*
17889
* If true, a modal dialog will be shown asking the user to sign in. If false, a numbered badge will be shown
17890
* on the accounts activity bar icon. An entry for the extension will be added under the menu to sign in. This
17891
* allows quietly prompting the user to sign in.
17892
*
17893
* If you provide options, you will also see the dialog but with the additional context provided.
17894
*
17895
* If there is a matching session but the extension has not been granted access to it, setting this to true
17896
* will also result in an immediate modal dialog, and false will add a numbered badge to the accounts icon.
17897
*
17898
* Defaults to false.
17899
*
17900
* Note: you cannot use this option with {@link AuthenticationGetSessionOptions.silent silent}.
17901
*/
17902
createIfNone?: boolean | AuthenticationGetSessionPresentationOptions;
17903
17904
/**
17905
* Whether we should attempt to reauthenticate even if there is already a session available.
17906
*
17907
* If true, a modal dialog will be shown asking the user to sign in again. This is mostly used for scenarios
17908
* where the token needs to be re minted because it has lost some authorization.
17909
*
17910
* If you provide options, you will also see the dialog but with the additional context provided.
17911
*
17912
* If there are no existing sessions and forceNewSession is true, it will behave identically to
17913
* {@link AuthenticationGetSessionOptions.createIfNone createIfNone}.
17914
*
17915
* This defaults to false.
17916
*/
17917
forceNewSession?: boolean | AuthenticationGetSessionPresentationOptions | AuthenticationForceNewSessionOptions;
17918
17919
/**
17920
* Whether we should show the indication to sign in in the Accounts menu.
17921
*
17922
* If false, the user will be shown a badge on the Accounts menu with an option to sign in for the extension.
17923
* If true, no indication will be shown.
17924
*
17925
* Defaults to false.
17926
*
17927
* Note: you cannot use this option with any other options that prompt the user like {@link AuthenticationGetSessionOptions.createIfNone createIfNone}.
17928
*/
17929
silent?: boolean;
17930
17931
/**
17932
* The account that you would like to get a session for. This is passed down to the Authentication Provider to be used for creating the correct session.
17933
*/
17934
account?: AuthenticationSessionAccountInformation;
17935
}
17936
17937
/**
17938
* Represents parameters for creating a session based on a WWW-Authenticate header value.
17939
* This is used when an API returns a 401 with a WWW-Authenticate header indicating
17940
* that additional authentication is required. The details of which will be passed down
17941
* to the authentication provider to create a session.
17942
*
17943
* @note The authorization provider must support handling challenges and specifically
17944
* the challenges in this WWW-Authenticate value.
17945
* @note For more information on WWW-Authenticate please see https://developer.mozilla.org/docs/Web/HTTP/Reference/Headers/WWW-Authenticate
17946
*/
17947
export interface AuthenticationWwwAuthenticateRequest {
17948
/**
17949
* The raw WWW-Authenticate header value that triggered this challenge.
17950
* This will be parsed by the authentication provider to extract the necessary
17951
* challenge information.
17952
*/
17953
readonly wwwAuthenticate: string;
17954
17955
/**
17956
* The fallback scopes to use if no scopes are found in the WWW-Authenticate header.
17957
*/
17958
readonly fallbackScopes?: readonly string[];
17959
}
17960
17961
/**
17962
* Basic information about an {@link AuthenticationProvider}
17963
*/
17964
export interface AuthenticationProviderInformation {
17965
/**
17966
* The unique identifier of the authentication provider.
17967
*/
17968
readonly id: string;
17969
17970
/**
17971
* The human-readable name of the authentication provider.
17972
*/
17973
readonly label: string;
17974
}
17975
17976
/**
17977
* An {@link Event} which fires when an {@link AuthenticationSession} is added, removed, or changed.
17978
*/
17979
export interface AuthenticationSessionsChangeEvent {
17980
/**
17981
* The {@link AuthenticationProvider} that has had its sessions change.
17982
*/
17983
readonly provider: AuthenticationProviderInformation;
17984
}
17985
17986
/**
17987
* Options for creating an {@link AuthenticationProvider}.
17988
*/
17989
export interface AuthenticationProviderOptions {
17990
/**
17991
* Whether it is possible to be signed into multiple accounts at once with this provider.
17992
* If not specified, will default to false.
17993
*/
17994
readonly supportsMultipleAccounts?: boolean;
17995
}
17996
17997
/**
17998
* An {@link Event} which fires when an {@link AuthenticationSession} is added, removed, or changed.
17999
*/
18000
export interface AuthenticationProviderAuthenticationSessionsChangeEvent {
18001
/**
18002
* The {@link AuthenticationSession AuthenticationSessions} of the {@link AuthenticationProvider} that have been added.
18003
*/
18004
readonly added: readonly AuthenticationSession[] | undefined;
18005
18006
/**
18007
* The {@link AuthenticationSession AuthenticationSessions} of the {@link AuthenticationProvider} that have been removed.
18008
*/
18009
readonly removed: readonly AuthenticationSession[] | undefined;
18010
18011
/**
18012
* The {@link AuthenticationSession AuthenticationSessions} of the {@link AuthenticationProvider} that have been changed.
18013
* A session changes when its data excluding the id are updated. An example of this is a session refresh that results in a new
18014
* access token being set for the session.
18015
*/
18016
readonly changed: readonly AuthenticationSession[] | undefined;
18017
}
18018
18019
/**
18020
* The options passed in to the {@link AuthenticationProvider.getSessions} and
18021
* {@link AuthenticationProvider.createSession} call.
18022
*/
18023
export interface AuthenticationProviderSessionOptions {
18024
/**
18025
* The account that is being asked about. If this is passed in, the provider should
18026
* attempt to return the sessions that are only related to this account.
18027
*/
18028
account?: AuthenticationSessionAccountInformation;
18029
}
18030
18031
/**
18032
* A provider for performing authentication to a service.
18033
*/
18034
export interface AuthenticationProvider {
18035
/**
18036
* An {@link Event} which fires when the array of sessions has changed, or data
18037
* within a session has changed.
18038
*/
18039
readonly onDidChangeSessions: Event<AuthenticationProviderAuthenticationSessionsChangeEvent>;
18040
18041
/**
18042
* Get a list of sessions.
18043
* @param scopes An optional list of scopes. If provided, the sessions returned should match
18044
* these permissions, otherwise all sessions should be returned.
18045
* @param options Additional options for getting sessions.
18046
* @returns A promise that resolves to an array of authentication sessions.
18047
*/
18048
getSessions(scopes: readonly string[] | undefined, options: AuthenticationProviderSessionOptions): Thenable<AuthenticationSession[]>;
18049
18050
/**
18051
* Prompts a user to login.
18052
*
18053
* If login is successful, the onDidChangeSessions event should be fired.
18054
*
18055
* If login fails, a rejected promise should be returned.
18056
*
18057
* If the provider has specified that it does not support multiple accounts,
18058
* then this should never be called if there is already an existing session matching these
18059
* scopes.
18060
* @param scopes A list of scopes, permissions, that the new session should be created with.
18061
* @param options Additional options for creating a session.
18062
* @returns A promise that resolves to an authentication session.
18063
*/
18064
createSession(scopes: readonly string[], options: AuthenticationProviderSessionOptions): Thenable<AuthenticationSession>;
18065
18066
/**
18067
* Removes the session corresponding to session id.
18068
*
18069
* If the removal is successful, the onDidChangeSessions event should be fired.
18070
*
18071
* If a session cannot be removed, the provider should reject with an error message.
18072
* @param sessionId The id of the session to remove.
18073
*/
18074
removeSession(sessionId: string): Thenable<void>;
18075
}
18076
18077
18078
/**
18079
* Namespace for authentication.
18080
*/
18081
export namespace authentication {
18082
/**
18083
* Get an authentication session matching the desired scopes or satisfying the WWW-Authenticate request. Rejects if
18084
* a provider with providerId is not registered, or if the user does not consent to sharing authentication information
18085
* with the extension. If there are multiple sessions with the same scopes, the user will be shown a quickpick to
18086
* select which account they would like to use.
18087
*
18088
* Built-in auth providers include:
18089
* * 'github' - For GitHub.com
18090
* * 'microsoft' For both personal & organizational Microsoft accounts
18091
* * (less common) 'github-enterprise' - for alternative GitHub hostings, GHE.com, GitHub Enterprise Server
18092
* * (less common) 'microsoft-sovereign-cloud' - for alternative Microsoft clouds
18093
*
18094
* @param providerId The id of the provider to use
18095
* @param scopeListOrRequest A scope list of permissions requested or a WWW-Authenticate request. These are dependent on the authentication provider.
18096
* @param options The {@link AuthenticationGetSessionOptions} to use
18097
* @returns A thenable that resolves to an authentication session
18098
*/
18099
export function getSession(providerId: string, scopeListOrRequest: ReadonlyArray<string> | AuthenticationWwwAuthenticateRequest, options: AuthenticationGetSessionOptions & { /** */createIfNone: true | AuthenticationGetSessionPresentationOptions }): Thenable<AuthenticationSession>;
18100
18101
/**
18102
* Get an authentication session matching the desired scopes or request. Rejects if a provider with providerId is not
18103
* registered, or if the user does not consent to sharing authentication information with the extension. If there
18104
* are multiple sessions with the same scopes, the user will be shown a quickpick to select which account they would like to use.
18105
*
18106
* Built-in auth providers include:
18107
* * 'github' - For GitHub.com
18108
* * 'microsoft' For both personal & organizational Microsoft accounts
18109
* * (less common) 'github-enterprise' - for alternative GitHub hostings, GHE.com, GitHub Enterprise Server
18110
* * (less common) 'microsoft-sovereign-cloud' - for alternative Microsoft clouds
18111
*
18112
* @param providerId The id of the provider to use
18113
* @param scopeListOrRequest A scope list of permissions requested or a WWW-Authenticate request. These are dependent on the authentication provider.
18114
* @param options The {@link AuthenticationGetSessionOptions} to use
18115
* @returns A thenable that resolves to an authentication session
18116
*/
18117
export function getSession(providerId: string, scopeListOrRequest: ReadonlyArray<string> | AuthenticationWwwAuthenticateRequest, options: AuthenticationGetSessionOptions & { /** literal-type defines return type */forceNewSession: true | AuthenticationGetSessionPresentationOptions | AuthenticationForceNewSessionOptions }): Thenable<AuthenticationSession>;
18118
18119
/**
18120
* Get an authentication session matching the desired scopes or request. Rejects if a provider with providerId is not
18121
* registered, or if the user does not consent to sharing authentication information with the extension. If there
18122
* are multiple sessions with the same scopes, the user will be shown a quickpick to select which account they would like to use.
18123
*
18124
* Built-in auth providers include:
18125
* * 'github' - For GitHub.com
18126
* * 'microsoft' For both personal & organizational Microsoft accounts
18127
* * (less common) 'github-enterprise' - for alternative GitHub hostings, GHE.com, GitHub Enterprise Server
18128
* * (less common) 'microsoft-sovereign-cloud' - for alternative Microsoft clouds
18129
*
18130
* @param providerId The id of the provider to use
18131
* @param scopeListOrRequest A scope list of permissions requested or a WWW-Authenticate request. These are dependent on the authentication provider.
18132
* @param options The {@link AuthenticationGetSessionOptions} to use
18133
* @returns A thenable that resolves to an authentication session or undefined if a silent flow was used and no session was found
18134
*/
18135
export function getSession(providerId: string, scopeListOrRequest: ReadonlyArray<string> | AuthenticationWwwAuthenticateRequest, options?: AuthenticationGetSessionOptions): Thenable<AuthenticationSession | undefined>;
18136
18137
/**
18138
* Get all accounts that the user is logged in to for the specified provider.
18139
* Use this paired with {@link getSession} in order to get an authentication session for a specific account.
18140
*
18141
* Currently, there are only two authentication providers that are contributed from built in extensions
18142
* to the editor that implement GitHub and Microsoft authentication: their providerId's are 'github' and 'microsoft'.
18143
*
18144
* Note: Getting accounts does not imply that your extension has access to that account or its authentication sessions. You can verify access to the account by calling {@link getSession}.
18145
*
18146
* @param providerId The id of the provider to use
18147
* @returns A thenable that resolves to a readonly array of authentication accounts.
18148
*/
18149
export function getAccounts(providerId: string): Thenable<readonly AuthenticationSessionAccountInformation[]>;
18150
18151
/**
18152
* An {@link Event} which fires when the authentication sessions of an authentication provider have
18153
* been added, removed, or changed.
18154
*/
18155
export const onDidChangeSessions: Event<AuthenticationSessionsChangeEvent>;
18156
18157
/**
18158
* Register an authentication provider.
18159
*
18160
* There can only be one provider per id and an error is being thrown when an id
18161
* has already been used by another provider. Ids are case-sensitive.
18162
*
18163
* @param id The unique identifier of the provider.
18164
* @param label The human-readable name of the provider.
18165
* @param provider The authentication provider provider.
18166
* @param options Additional options for the provider.
18167
* @returns A {@link Disposable} that unregisters this provider when being disposed.
18168
*/
18169
export function registerAuthenticationProvider(id: string, label: string, provider: AuthenticationProvider, options?: AuthenticationProviderOptions): Disposable;
18170
}
18171
18172
/**
18173
* Namespace for localization-related functionality in the extension API. To use this properly,
18174
* you must have `l10n` defined in your extension manifest and have bundle.l10n.<language>.json files.
18175
* For more information on how to generate bundle.l10n.<language>.json files, check out the
18176
* [vscode-l10n repo](https://github.com/microsoft/vscode-l10n).
18177
*
18178
* Note: Built-in extensions (for example, Git, TypeScript Language Features, GitHub Authentication)
18179
* are excluded from the `l10n` property requirement. In other words, they do not need to specify
18180
* a `l10n` in the extension manifest because their translated strings come from Language Packs.
18181
*/
18182
export namespace l10n {
18183
/**
18184
* Marks a string for localization. If a localized bundle is available for the language specified by
18185
* {@link env.language} and the bundle has a localized value for this message, then that localized
18186
* value will be returned (with injected {@link args} values for any templated values).
18187
*
18188
* @param message - The message to localize. Supports index templating where strings like `{0}` and `{1}` are
18189
* replaced by the item at that index in the {@link args} array.
18190
* @param args - The arguments to be used in the localized string. The index of the argument is used to
18191
* match the template placeholder in the localized string.
18192
* @returns localized string with injected arguments.
18193
*
18194
* @example
18195
* l10n.t('Hello {0}!', 'World');
18196
*/
18197
export function t(message: string, ...args: Array<string | number | boolean>): string;
18198
18199
/**
18200
* Marks a string for localization. If a localized bundle is available for the language specified by
18201
* {@link env.language} and the bundle has a localized value for this message, then that localized
18202
* value will be returned (with injected {@link args} values for any templated values).
18203
*
18204
* @param message The message to localize. Supports named templating where strings like `{foo}` and `{bar}` are
18205
* replaced by the value in the Record for that key (foo, bar, etc).
18206
* @param args The arguments to be used in the localized string. The name of the key in the record is used to
18207
* match the template placeholder in the localized string.
18208
* @returns localized string with injected arguments.
18209
*
18210
* @example
18211
* l10n.t('Hello {name}', { name: 'Erich' });
18212
*/
18213
export function t(message: string, args: Record<string, string | number | boolean>): string;
18214
/**
18215
* Marks a string for localization. If a localized bundle is available for the language specified by
18216
* {@link env.language} and the bundle has a localized value for this message, then that localized
18217
* value will be returned (with injected args values for any templated values).
18218
*
18219
* @param options The options to use when localizing the message.
18220
* @returns localized string with injected arguments.
18221
*/
18222
export function t(options: {
18223
/**
18224
* The message to localize. If {@link options.args args} is an array, this message supports index templating where strings like
18225
* `{0}` and `{1}` are replaced by the item at that index in the {@link options.args args} array. If `args` is a `Record`,
18226
* this supports named templating where strings like `{foo}` and `{bar}` are replaced by the value in
18227
* the Record for that key (foo, bar, etc).
18228
*/
18229
message: string;
18230
/**
18231
* The arguments to be used in the localized string. As an array, the index of the argument is used to
18232
* match the template placeholder in the localized string. As a `Record`, the key is used to match the template
18233
* placeholder in the localized string.
18234
*/
18235
args?: Array<string | number | boolean> | Record<string, string | number | boolean>;
18236
/**
18237
* A comment to help translators understand the context of the message.
18238
*/
18239
comment: string | string[];
18240
}): string;
18241
/**
18242
* The bundle of localized strings that have been loaded for the extension.
18243
* It's undefined if no bundle has been loaded. The bundle is typically not loaded if
18244
* there was no bundle found or when we are running with the default language.
18245
*/
18246
export const bundle: { [key: string]: string } | undefined;
18247
/**
18248
* The URI of the localization bundle that has been loaded for the extension.
18249
* It's undefined if no bundle has been loaded. The bundle is typically not loaded if
18250
* there was no bundle found or when we are running with the default language.
18251
*/
18252
export const uri: Uri | undefined;
18253
}
18254
18255
/**
18256
* Namespace for testing functionality. Tests are published by registering
18257
* {@link TestController} instances, then adding {@link TestItem TestItems}.
18258
* Controllers may also describe how to run tests by creating one or more
18259
* {@link TestRunProfile} instances.
18260
*/
18261
export namespace tests {
18262
/**
18263
* Creates a new test controller.
18264
*
18265
* @param id Identifier for the controller, must be globally unique.
18266
* @param label A human-readable label for the controller.
18267
* @returns An instance of the {@link TestController}.
18268
*/
18269
export function createTestController(id: string, label: string): TestController;
18270
}
18271
18272
/**
18273
* The kind of executions that {@link TestRunProfile TestRunProfiles} control.
18274
*/
18275
export enum TestRunProfileKind {
18276
/**
18277
* The `Run` test profile kind.
18278
*/
18279
Run = 1,
18280
/**
18281
* The `Debug` test profile kind.
18282
*/
18283
Debug = 2,
18284
/**
18285
* The `Coverage` test profile kind.
18286
*/
18287
Coverage = 3,
18288
}
18289
18290
/**
18291
* Tags can be associated with {@link TestItem TestItems} and
18292
* {@link TestRunProfile TestRunProfiles}. A profile with a tag can only
18293
* execute tests that include that tag in their {@link TestItem.tags} array.
18294
*/
18295
export class TestTag {
18296
/**
18297
* ID of the test tag. `TestTag` instances with the same ID are considered
18298
* to be identical.
18299
*/
18300
readonly id: string;
18301
18302
/**
18303
* Creates a new TestTag instance.
18304
* @param id ID of the test tag.
18305
*/
18306
constructor(id: string);
18307
}
18308
18309
/**
18310
* A TestRunProfile describes one way to execute tests in a {@link TestController}.
18311
*/
18312
export interface TestRunProfile {
18313
/**
18314
* Label shown to the user in the UI.
18315
*
18316
* Note that the label has some significance if the user requests that
18317
* tests be re-run in a certain way. For example, if tests were run
18318
* normally and the user requests to re-run them in debug mode, the editor
18319
* will attempt use a configuration with the same label of the `Debug`
18320
* kind. If there is no such configuration, the default will be used.
18321
*/
18322
label: string;
18323
18324
/**
18325
* Configures what kind of execution this profile controls. If there
18326
* are no profiles for a kind, it will not be available in the UI.
18327
*/
18328
readonly kind: TestRunProfileKind;
18329
18330
/**
18331
* Controls whether this profile is the default action that will
18332
* be taken when its kind is actioned. For example, if the user clicks
18333
* the generic "run all" button, then the default profile for
18334
* {@link TestRunProfileKind.Run} will be executed, although the
18335
* user can configure this.
18336
*
18337
* Changes the user makes in their default profiles will be reflected
18338
* in this property after a {@link onDidChangeDefault} event.
18339
*/
18340
isDefault: boolean;
18341
18342
/**
18343
* Fired when a user has changed whether this is a default profile. The
18344
* event contains the new value of {@link isDefault}
18345
*/
18346
readonly onDidChangeDefault: Event<boolean>;
18347
18348
/**
18349
* Whether this profile supports continuous running of requests. If so,
18350
* then {@link TestRunRequest.continuous} may be set to `true`. Defaults
18351
* to false.
18352
*/
18353
supportsContinuousRun: boolean;
18354
18355
/**
18356
* Associated tag for the profile. If this is set, only {@link TestItem}
18357
* instances with the same tag will be eligible to execute in this profile.
18358
*/
18359
tag: TestTag | undefined;
18360
18361
/**
18362
* If this method is present, a configuration gear will be present in the
18363
* UI, and this method will be invoked when it's clicked. When called,
18364
* you can take other editor actions, such as showing a quick pick or
18365
* opening a configuration file.
18366
*/
18367
configureHandler: (() => void) | undefined;
18368
18369
/**
18370
* Handler called to start a test run. When invoked, the function should call
18371
* {@link TestController.createTestRun} at least once, and all test runs
18372
* associated with the request should be created before the function returns
18373
* or the returned promise is resolved.
18374
*
18375
* If {@link supportsContinuousRun} is set, then {@link TestRunRequest.continuous}
18376
* may be `true`. In this case, the profile should observe changes to
18377
* source code and create new test runs by calling {@link TestController.createTestRun},
18378
* until the cancellation is requested on the `token`.
18379
*
18380
* @param request Request information for the test run.
18381
* @param cancellationToken Token that signals the used asked to abort the
18382
* test run. If cancellation is requested on this token, all {@link TestRun}
18383
* instances associated with the request will be
18384
* automatically cancelled as well.
18385
*/
18386
runHandler: (request: TestRunRequest, token: CancellationToken) => Thenable<void> | void;
18387
18388
/**
18389
* An extension-provided function that provides detailed statement and
18390
* function-level coverage for a file. The editor will call this when more
18391
* detail is needed for a file, such as when it's opened in an editor or
18392
* expanded in the **Test Coverage** view.
18393
*
18394
* The {@link FileCoverage} object passed to this function is the same instance
18395
* emitted on {@link TestRun.addCoverage} calls associated with this profile.
18396
*/
18397
loadDetailedCoverage?: (testRun: TestRun, fileCoverage: FileCoverage, token: CancellationToken) => Thenable<FileCoverageDetail[]>;
18398
18399
/**
18400
* An extension-provided function that provides detailed statement and
18401
* function-level coverage for a single test in a file. This is the per-test
18402
* sibling of {@link TestRunProfile.loadDetailedCoverage}, called only if
18403
* a test item is provided in {@link FileCoverage.includesTests} and only
18404
* for files where such data is reported.
18405
*
18406
* Often {@link TestRunProfile.loadDetailedCoverage} will be called first
18407
* when a user opens a file, and then this method will be called if they
18408
* drill down into specific per-test coverage information. This method
18409
* should then return coverage data only for statements and declarations
18410
* executed by the specific test during the run.
18411
*
18412
* The {@link FileCoverage} object passed to this function is the same
18413
* instance emitted on {@link TestRun.addCoverage} calls associated with this profile.
18414
*
18415
* @param testRun The test run that generated the coverage data.
18416
* @param fileCoverage The file coverage object to load detailed coverage for.
18417
* @param fromTestItem The test item to request coverage information for.
18418
* @param token A cancellation token that indicates the operation should be cancelled.
18419
*/
18420
loadDetailedCoverageForTest?: (testRun: TestRun, fileCoverage: FileCoverage, fromTestItem: TestItem, token: CancellationToken) => Thenable<FileCoverageDetail[]>;
18421
18422
/**
18423
* Deletes the run profile.
18424
*/
18425
dispose(): void;
18426
}
18427
18428
/**
18429
* Entry point to discover and execute tests. It contains {@link TestController.items} which
18430
* are used to populate the editor UI, and is associated with
18431
* {@link TestController.createRunProfile run profiles} to allow
18432
* for tests to be executed.
18433
*/
18434
export interface TestController {
18435
/**
18436
* The id of the controller passed in {@link tests.createTestController}.
18437
* This must be globally unique.
18438
*/
18439
readonly id: string;
18440
18441
/**
18442
* Human-readable label for the test controller.
18443
*/
18444
label: string;
18445
18446
/**
18447
* A collection of "top-level" {@link TestItem} instances, which can in
18448
* turn have their own {@link TestItem.children children} to form the
18449
* "test tree."
18450
*
18451
* The extension controls when to add tests. For example, extensions should
18452
* add tests for a file when {@link workspace.onDidOpenTextDocument}
18453
* fires in order for decorations for tests within a file to be visible.
18454
*
18455
* However, the editor may sometimes explicitly request children using the
18456
* {@link resolveHandler} See the documentation on that method for more details.
18457
*/
18458
readonly items: TestItemCollection;
18459
18460
/**
18461
* Creates a profile used for running tests. Extensions must create
18462
* at least one profile in order for tests to be run.
18463
* @param label A human-readable label for this profile.
18464
* @param kind Configures what kind of execution this profile manages.
18465
* @param runHandler Function called to start a test run.
18466
* @param isDefault Whether this is the default action for its kind.
18467
* @param tag Profile test tag.
18468
* @param supportsContinuousRun Whether the profile supports continuous running.
18469
* @returns An instance of a {@link TestRunProfile}, which is automatically
18470
* associated with this controller.
18471
*/
18472
createRunProfile(label: string, kind: TestRunProfileKind, runHandler: (request: TestRunRequest, token: CancellationToken) => Thenable<void> | void, isDefault?: boolean, tag?: TestTag, supportsContinuousRun?: boolean): TestRunProfile;
18473
18474
/**
18475
* A function provided by the extension that the editor may call to request
18476
* children of a test item, if the {@link TestItem.canResolveChildren} is
18477
* `true`. When called, the item should discover children and call
18478
* {@link TestController.createTestItem} as children are discovered.
18479
*
18480
* Generally the extension manages the lifecycle of test items, but under
18481
* certain conditions the editor may request the children of a specific
18482
* item to be loaded. For example, if the user requests to re-run tests
18483
* after reloading the editor, the editor may need to call this method
18484
* to resolve the previously-run tests.
18485
*
18486
* The item in the explorer will automatically be marked as "busy" until
18487
* the function returns or the returned thenable resolves.
18488
*
18489
* @param item An unresolved test item for which children are being
18490
* requested, or `undefined` to resolve the controller's initial {@link TestController.items items}.
18491
*/
18492
resolveHandler?: (item: TestItem | undefined) => Thenable<void> | void;
18493
18494
/**
18495
* If this method is present, a refresh button will be present in the
18496
* UI, and this method will be invoked when it's clicked. When called,
18497
* the extension should scan the workspace for any new, changed, or
18498
* removed tests.
18499
*
18500
* It's recommended that extensions try to update tests in realtime, using
18501
* a {@link FileSystemWatcher} for example, and use this method as a fallback.
18502
*
18503
* @returns A thenable that resolves when tests have been refreshed.
18504
*/
18505
refreshHandler: ((token: CancellationToken) => Thenable<void> | void) | undefined;
18506
18507
/**
18508
* Creates a {@link TestRun}. This should be called by the
18509
* {@link TestRunProfile} when a request is made to execute tests, and may
18510
* also be called if a test run is detected externally. Once created, tests
18511
* that are included in the request will be moved into the queued state.
18512
*
18513
* All runs created using the same `request` instance will be grouped
18514
* together. This is useful if, for example, a single suite of tests is
18515
* run on multiple platforms.
18516
*
18517
* @param request Test run request. Only tests inside the `include` may be
18518
* modified, and tests in its `exclude` are ignored.
18519
* @param name The human-readable name of the run. This can be used to
18520
* disambiguate multiple sets of results in a test run. It is useful if
18521
* tests are run across multiple platforms, for example.
18522
* @param persist Whether the results created by the run should be
18523
* persisted in the editor. This may be false if the results are coming from
18524
* a file already saved externally, such as a coverage information file.
18525
* @returns An instance of the {@link TestRun}. It will be considered "running"
18526
* from the moment this method is invoked until {@link TestRun.end} is called.
18527
*/
18528
createTestRun(request: TestRunRequest, name?: string, persist?: boolean): TestRun;
18529
18530
/**
18531
* Creates a new managed {@link TestItem} instance. It can be added into
18532
* the {@link TestItem.children} of an existing item, or into the
18533
* {@link TestController.items}.
18534
*
18535
* @param id Identifier for the TestItem. The test item's ID must be unique
18536
* in the {@link TestItemCollection} it's added to.
18537
* @param label Human-readable label of the test item.
18538
* @param uri URI this TestItem is associated with. May be a file or directory.
18539
*/
18540
createTestItem(id: string, label: string, uri?: Uri): TestItem;
18541
18542
/**
18543
* Marks an item's results as being outdated. This is commonly called when
18544
* code or configuration changes and previous results should no longer
18545
* be considered relevant. The same logic used to mark results as outdated
18546
* may be used to drive {@link TestRunRequest.continuous continuous test runs}.
18547
*
18548
* If an item is passed to this method, test results for the item and all of
18549
* its children will be marked as outdated. If no item is passed, then all
18550
* test owned by the TestController will be marked as outdated.
18551
*
18552
* Any test runs started before the moment this method is called, including
18553
* runs which may still be ongoing, will be marked as outdated and deprioritized
18554
* in the editor's UI.
18555
*
18556
* @param items Item to mark as outdated. If undefined, all the controller's items are marked outdated.
18557
*/
18558
invalidateTestResults(items?: TestItem | readonly TestItem[]): void;
18559
18560
/**
18561
* Unregisters the test controller, disposing of its associated tests
18562
* and unpersisted results.
18563
*/
18564
dispose(): void;
18565
}
18566
18567
/**
18568
* A TestRunRequest is a precursor to a {@link TestRun}, which in turn is
18569
* created by passing a request to {@link TestController.createTestRun}. The
18570
* TestRunRequest contains information about which tests should be run, which
18571
* should not be run, and how they are run (via the {@link TestRunRequest.profile profile}).
18572
*
18573
* In general, TestRunRequests are created by the editor and pass to
18574
* {@link TestRunProfile.runHandler}, however you can also create test
18575
* requests and runs outside of the `runHandler`.
18576
*/
18577
export class TestRunRequest {
18578
/**
18579
* A filter for specific tests to run. If given, the extension should run
18580
* all of the included tests and all their children, excluding any tests
18581
* that appear in {@link TestRunRequest.exclude}. If this property is
18582
* undefined, then the extension should simply run all tests.
18583
*
18584
* The process of running tests should resolve the children of any test
18585
* items who have not yet been resolved.
18586
*/
18587
readonly include: readonly TestItem[] | undefined;
18588
18589
/**
18590
* An array of tests the user has marked as excluded from the test included
18591
* in this run; exclusions should apply after inclusions.
18592
*
18593
* May be omitted if no exclusions were requested. Test controllers should
18594
* not run excluded tests or any children of excluded tests.
18595
*/
18596
readonly exclude: readonly TestItem[] | undefined;
18597
18598
/**
18599
* The profile used for this request. This will always be defined
18600
* for requests issued from the editor UI, though extensions may
18601
* programmatically create requests not associated with any profile.
18602
*/
18603
readonly profile: TestRunProfile | undefined;
18604
18605
/**
18606
* Whether the profile should run continuously as source code changes. Only
18607
* relevant for profiles that set {@link TestRunProfile.supportsContinuousRun}.
18608
*/
18609
readonly continuous?: boolean;
18610
18611
/**
18612
* Controls how test Test Results view is focused. If true, the editor
18613
* will keep the maintain the user's focus. If false, the editor will
18614
* prefer to move focus into the Test Results view, although
18615
* this may be configured by users.
18616
*/
18617
readonly preserveFocus: boolean;
18618
18619
/**
18620
* @param include Array of specific tests to run, or undefined to run all tests
18621
* @param exclude An array of tests to exclude from the run.
18622
* @param profile The run profile used for this request.
18623
* @param continuous Whether to run tests continuously as source changes.
18624
* @param preserveFocus Whether to preserve the user's focus when the run is started
18625
*/
18626
constructor(include?: readonly TestItem[], exclude?: readonly TestItem[], profile?: TestRunProfile, continuous?: boolean, preserveFocus?: boolean);
18627
}
18628
18629
/**
18630
* A TestRun represents an in-progress or completed test run and
18631
* provides methods to report the state of individual tests in the run.
18632
*/
18633
export interface TestRun {
18634
/**
18635
* The human-readable name of the run. This can be used to
18636
* disambiguate multiple sets of results in a test run. It is useful if
18637
* tests are run across multiple platforms, for example.
18638
*/
18639
readonly name: string | undefined;
18640
18641
/**
18642
* A cancellation token which will be triggered when the test run is
18643
* canceled from the UI.
18644
*/
18645
readonly token: CancellationToken;
18646
18647
/**
18648
* Whether the test run will be persisted across reloads by the editor.
18649
*/
18650
readonly isPersisted: boolean;
18651
18652
/**
18653
* Indicates a test is queued for later execution.
18654
* @param test Test item to update.
18655
*/
18656
enqueued(test: TestItem): void;
18657
18658
/**
18659
* Indicates a test has started running.
18660
* @param test Test item to update.
18661
*/
18662
started(test: TestItem): void;
18663
18664
/**
18665
* Indicates a test has been skipped.
18666
* @param test Test item to update.
18667
*/
18668
skipped(test: TestItem): void;
18669
18670
/**
18671
* Indicates a test has failed. You should pass one or more
18672
* {@link TestMessage TestMessages} to describe the failure.
18673
* @param test Test item to update.
18674
* @param message Messages associated with the test failure.
18675
* @param duration How long the test took to execute, in milliseconds.
18676
*/
18677
failed(test: TestItem, message: TestMessage | readonly TestMessage[], duration?: number): void;
18678
18679
/**
18680
* Indicates a test has errored. You should pass one or more
18681
* {@link TestMessage TestMessages} to describe the failure. This differs
18682
* from the "failed" state in that it indicates a test that couldn't be
18683
* executed at all, from a compilation error for example.
18684
* @param test Test item to update.
18685
* @param message Messages associated with the test failure.
18686
* @param duration How long the test took to execute, in milliseconds.
18687
*/
18688
errored(test: TestItem, message: TestMessage | readonly TestMessage[], duration?: number): void;
18689
18690
/**
18691
* Indicates a test has passed.
18692
* @param test Test item to update.
18693
* @param duration How long the test took to execute, in milliseconds.
18694
*/
18695
passed(test: TestItem, duration?: number): void;
18696
18697
/**
18698
* Appends raw output from the test runner. On the user's request, the
18699
* output will be displayed in a terminal. ANSI escape sequences,
18700
* such as colors and text styles, are supported. New lines must be given
18701
* as CRLF (`\r\n`) rather than LF (`\n`).
18702
*
18703
* @param output Output text to append.
18704
* @param location Indicate that the output was logged at the given
18705
* location.
18706
* @param test Test item to associate the output with.
18707
*/
18708
appendOutput(output: string, location?: Location, test?: TestItem): void;
18709
18710
/**
18711
* Adds coverage for a file in the run.
18712
*/
18713
addCoverage(fileCoverage: FileCoverage): void;
18714
18715
/**
18716
* Signals the end of the test run. Any tests included in the run whose
18717
* states have not been updated will have their state reset.
18718
*/
18719
end(): void;
18720
18721
/**
18722
* An event fired when the editor is no longer interested in data
18723
* associated with the test run.
18724
*/
18725
readonly onDidDispose: Event<void>;
18726
}
18727
18728
/**
18729
* Collection of test items, found in {@link TestItem.children} and
18730
* {@link TestController.items}.
18731
*/
18732
export interface TestItemCollection extends Iterable<[id: string, testItem: TestItem]> {
18733
/**
18734
* Gets the number of items in the collection.
18735
*/
18736
readonly size: number;
18737
18738
/**
18739
* Replaces the items stored by the collection.
18740
* @param items Items to store.
18741
*/
18742
replace(items: readonly TestItem[]): void;
18743
18744
/**
18745
* Iterate over each entry in this collection.
18746
*
18747
* @param callback Function to execute for each entry.
18748
* @param thisArg The `this` context used when invoking the handler function.
18749
*/
18750
forEach(callback: (item: TestItem, collection: TestItemCollection) => unknown, thisArg?: any): void;
18751
18752
/**
18753
* Adds the test item to the children. If an item with the same ID already
18754
* exists, it'll be replaced.
18755
* @param item Item to add.
18756
*/
18757
add(item: TestItem): void;
18758
18759
/**
18760
* Removes a single test item from the collection.
18761
* @param itemId Item ID to delete.
18762
*/
18763
delete(itemId: string): void;
18764
18765
/**
18766
* Efficiently gets a test item by ID, if it exists, in the children.
18767
* @param itemId Item ID to get.
18768
* @returns The found item or undefined if it does not exist.
18769
*/
18770
get(itemId: string): TestItem | undefined;
18771
}
18772
18773
/**
18774
* An item shown in the "test explorer" view.
18775
*
18776
* A `TestItem` can represent either a test suite or a test itself, since
18777
* they both have similar capabilities.
18778
*/
18779
export interface TestItem {
18780
/**
18781
* Identifier for the `TestItem`. This is used to correlate
18782
* test results and tests in the document with those in the workspace
18783
* (test explorer). This cannot change for the lifetime of the `TestItem`,
18784
* and must be unique among its parent's direct children.
18785
*/
18786
readonly id: string;
18787
18788
/**
18789
* URI this `TestItem` is associated with. May be a file or directory.
18790
*/
18791
readonly uri: Uri | undefined;
18792
18793
/**
18794
* The children of this test item. For a test suite, this may contain the
18795
* individual test cases or nested suites.
18796
*/
18797
readonly children: TestItemCollection;
18798
18799
/**
18800
* The parent of this item. It's set automatically, and is undefined
18801
* top-level items in the {@link TestController.items} and for items that
18802
* aren't yet included in another item's {@link TestItem.children children}.
18803
*/
18804
readonly parent: TestItem | undefined;
18805
18806
/**
18807
* Tags associated with this test item. May be used in combination with
18808
* {@link TestRunProfile.tag tags}, or simply as an organizational feature.
18809
*/
18810
tags: readonly TestTag[];
18811
18812
/**
18813
* Indicates whether this test item may have children discovered by resolving.
18814
*
18815
* If true, this item is shown as expandable in the Test Explorer view and
18816
* expanding the item will cause {@link TestController.resolveHandler}
18817
* to be invoked with the item.
18818
*
18819
* Default to `false`.
18820
*/
18821
canResolveChildren: boolean;
18822
18823
/**
18824
* Controls whether the item is shown as "busy" in the Test Explorer view.
18825
* This is useful for showing status while discovering children.
18826
*
18827
* Defaults to `false`.
18828
*/
18829
busy: boolean;
18830
18831
/**
18832
* Display name describing the test case.
18833
*/
18834
label: string;
18835
18836
/**
18837
* Optional description that appears next to the label.
18838
*/
18839
description?: string;
18840
18841
/**
18842
* A string that should be used when comparing this item
18843
* with other items. When `falsy` the {@link TestItem.label label}
18844
* is used.
18845
*/
18846
sortText?: string | undefined;
18847
18848
/**
18849
* Location of the test item in its {@link TestItem.uri uri}.
18850
*
18851
* This is only meaningful if the `uri` points to a file.
18852
*/
18853
range: Range | undefined;
18854
18855
/**
18856
* Optional error encountered while loading the test.
18857
*
18858
* Note that this is not a test result and should only be used to represent errors in
18859
* test discovery, such as syntax errors.
18860
*/
18861
error: string | MarkdownString | undefined;
18862
}
18863
18864
/**
18865
* A stack frame found in the {@link TestMessage.stackTrace}.
18866
*/
18867
export class TestMessageStackFrame {
18868
/**
18869
* The location of this stack frame. This should be provided as a URI if the
18870
* location of the call frame can be accessed by the editor.
18871
*/
18872
uri?: Uri;
18873
18874
/**
18875
* Position of the stack frame within the file.
18876
*/
18877
position?: Position;
18878
18879
/**
18880
* The name of the stack frame, typically a method or function name.
18881
*/
18882
label: string;
18883
18884
/**
18885
* @param label The name of the stack frame
18886
* @param file The file URI of the stack frame
18887
* @param position The position of the stack frame within the file
18888
*/
18889
constructor(label: string, uri?: Uri, position?: Position);
18890
}
18891
18892
/**
18893
* Message associated with the test state. Can be linked to a specific
18894
* source range -- useful for assertion failures, for example.
18895
*/
18896
export class TestMessage {
18897
/**
18898
* Human-readable message text to display.
18899
*/
18900
message: string | MarkdownString;
18901
18902
/**
18903
* Expected test output. If given with {@link TestMessage.actualOutput actualOutput }, a diff view will be shown.
18904
*/
18905
expectedOutput?: string;
18906
18907
/**
18908
* Actual test output. If given with {@link TestMessage.expectedOutput expectedOutput }, a diff view will be shown.
18909
*/
18910
actualOutput?: string;
18911
18912
/**
18913
* Associated file location.
18914
*/
18915
location?: Location;
18916
18917
/**
18918
* Context value of the test item. This can be used to contribute message-
18919
* specific actions to the test peek view. The value set here can be found
18920
* in the `testMessage` property of the following `menus` contribution points:
18921
*
18922
* - `testing/message/context` - context menu for the message in the results tree
18923
* - `testing/message/content` - a prominent button overlaying editor content where
18924
* the message is displayed.
18925
*
18926
* For example:
18927
*
18928
* ```json
18929
* "contributes": {
18930
* "menus": {
18931
* "testing/message/content": [
18932
* {
18933
* "command": "extension.deleteCommentThread",
18934
* "when": "testMessage == canApplyRichDiff"
18935
* }
18936
* ]
18937
* }
18938
* }
18939
* ```
18940
*
18941
* The command will be called with an object containing:
18942
* - `test`: the {@link TestItem} the message is associated with, *if* it
18943
* is still present in the {@link TestController.items} collection.
18944
* - `message`: the {@link TestMessage} instance.
18945
*/
18946
contextValue?: string;
18947
18948
/**
18949
* The stack trace associated with the message or failure.
18950
*/
18951
stackTrace?: TestMessageStackFrame[];
18952
18953
/**
18954
* Creates a new TestMessage that will present as a diff in the editor.
18955
* @param message Message to display to the user.
18956
* @param expected Expected output.
18957
* @param actual Actual output.
18958
*/
18959
static diff(message: string | MarkdownString, expected: string, actual: string): TestMessage;
18960
18961
/**
18962
* Creates a new TestMessage instance.
18963
* @param message The message to show to the user.
18964
*/
18965
constructor(message: string | MarkdownString);
18966
}
18967
18968
/**
18969
* A class that contains information about a covered resource. A count can
18970
* be give for lines, branches, and declarations in a file.
18971
*/
18972
export class TestCoverageCount {
18973
/**
18974
* Number of items covered in the file.
18975
*/
18976
covered: number;
18977
/**
18978
* Total number of covered items in the file.
18979
*/
18980
total: number;
18981
18982
/**
18983
* @param covered Value for {@link TestCoverageCount.covered}
18984
* @param total Value for {@link TestCoverageCount.total}
18985
*/
18986
constructor(covered: number, total: number);
18987
}
18988
18989
/**
18990
* Contains coverage metadata for a file.
18991
*/
18992
export class FileCoverage {
18993
/**
18994
* File URI.
18995
*/
18996
readonly uri: Uri;
18997
18998
/**
18999
* Statement coverage information. If the reporter does not provide statement
19000
* coverage information, this can instead be used to represent line coverage.
19001
*/
19002
statementCoverage: TestCoverageCount;
19003
19004
/**
19005
* Branch coverage information.
19006
*/
19007
branchCoverage?: TestCoverageCount;
19008
19009
/**
19010
* Declaration coverage information. Depending on the reporter and
19011
* language, this may be types such as functions, methods, or namespaces.
19012
*/
19013
declarationCoverage?: TestCoverageCount;
19014
19015
/**
19016
* A list of {@link TestItem test cases} that generated coverage in this
19017
* file. If set, then {@link TestRunProfile.loadDetailedCoverageForTest}
19018
* should also be defined in order to retrieve detailed coverage information.
19019
*/
19020
includesTests?: TestItem[];
19021
19022
/**
19023
* Creates a {@link FileCoverage} instance with counts filled in from
19024
* the coverage details.
19025
* @param uri Covered file URI
19026
* @param details Detailed coverage information
19027
*/
19028
static fromDetails(uri: Uri, details: readonly FileCoverageDetail[]): FileCoverage;
19029
19030
/**
19031
* @param uri Covered file URI
19032
* @param statementCoverage Statement coverage information. If the reporter
19033
* does not provide statement coverage information, this can instead be
19034
* used to represent line coverage.
19035
* @param branchCoverage Branch coverage information
19036
* @param declarationCoverage Declaration coverage information
19037
* @param includesTests Test cases included in this coverage report, see {@link FileCoverage.includesTests}
19038
*/
19039
constructor(
19040
uri: Uri,
19041
statementCoverage: TestCoverageCount,
19042
branchCoverage?: TestCoverageCount,
19043
declarationCoverage?: TestCoverageCount,
19044
includesTests?: TestItem[],
19045
);
19046
}
19047
19048
/**
19049
* Contains coverage information for a single statement or line.
19050
*/
19051
export class StatementCoverage {
19052
/**
19053
* The number of times this statement was executed, or a boolean indicating
19054
* whether it was executed if the exact count is unknown. If zero or false,
19055
* the statement will be marked as un-covered.
19056
*/
19057
executed: number | boolean;
19058
19059
/**
19060
* Statement location.
19061
*/
19062
location: Position | Range;
19063
19064
/**
19065
* Coverage from branches of this line or statement. If it's not a
19066
* conditional, this will be empty.
19067
*/
19068
branches: BranchCoverage[];
19069
19070
/**
19071
* @param location The statement position.
19072
* @param executed The number of times this statement was executed, or a
19073
* boolean indicating whether it was executed if the exact count is
19074
* unknown. If zero or false, the statement will be marked as un-covered.
19075
* @param branches Coverage from branches of this line. If it's not a
19076
* conditional, this should be omitted.
19077
*/
19078
constructor(executed: number | boolean, location: Position | Range, branches?: BranchCoverage[]);
19079
}
19080
19081
/**
19082
* Contains coverage information for a branch of a {@link StatementCoverage}.
19083
*/
19084
export class BranchCoverage {
19085
/**
19086
* The number of times this branch was executed, or a boolean indicating
19087
* whether it was executed if the exact count is unknown. If zero or false,
19088
* the branch will be marked as un-covered.
19089
*/
19090
executed: number | boolean;
19091
19092
/**
19093
* Branch location.
19094
*/
19095
location?: Position | Range;
19096
19097
/**
19098
* Label for the branch, used in the context of "the ${label} branch was
19099
* not taken," for example.
19100
*/
19101
label?: string;
19102
19103
/**
19104
* @param executed The number of times this branch was executed, or a
19105
* boolean indicating whether it was executed if the exact count is
19106
* unknown. If zero or false, the branch will be marked as un-covered.
19107
* @param location The branch position.
19108
*/
19109
constructor(executed: number | boolean, location?: Position | Range, label?: string);
19110
}
19111
19112
/**
19113
* Contains coverage information for a declaration. Depending on the reporter
19114
* and language, this may be types such as functions, methods, or namespaces.
19115
*/
19116
export class DeclarationCoverage {
19117
/**
19118
* Name of the declaration.
19119
*/
19120
name: string;
19121
19122
/**
19123
* The number of times this declaration was executed, or a boolean
19124
* indicating whether it was executed if the exact count is unknown. If
19125
* zero or false, the declaration will be marked as un-covered.
19126
*/
19127
executed: number | boolean;
19128
19129
/**
19130
* Declaration location.
19131
*/
19132
location: Position | Range;
19133
19134
/**
19135
* @param executed The number of times this declaration was executed, or a
19136
* boolean indicating whether it was executed if the exact count is
19137
* unknown. If zero or false, the declaration will be marked as un-covered.
19138
* @param location The declaration position.
19139
*/
19140
constructor(name: string, executed: number | boolean, location: Position | Range);
19141
}
19142
19143
/**
19144
* Coverage details returned from {@link TestRunProfile.loadDetailedCoverage}.
19145
*/
19146
export type FileCoverageDetail = StatementCoverage | DeclarationCoverage;
19147
19148
/**
19149
* The tab represents a single text based resource.
19150
*/
19151
export class TabInputText {
19152
/**
19153
* The uri represented by the tab.
19154
*/
19155
readonly uri: Uri;
19156
/**
19157
* Constructs a text tab input with the given URI.
19158
* @param uri The URI of the tab.
19159
*/
19160
constructor(uri: Uri);
19161
}
19162
19163
/**
19164
* The tab represents two text based resources
19165
* being rendered as a diff.
19166
*/
19167
export class TabInputTextDiff {
19168
/**
19169
* The uri of the original text resource.
19170
*/
19171
readonly original: Uri;
19172
/**
19173
* The uri of the modified text resource.
19174
*/
19175
readonly modified: Uri;
19176
/**
19177
* Constructs a new text diff tab input with the given URIs.
19178
* @param original The uri of the original text resource.
19179
* @param modified The uri of the modified text resource.
19180
*/
19181
constructor(original: Uri, modified: Uri);
19182
}
19183
19184
/**
19185
* The tab represents a custom editor.
19186
*/
19187
export class TabInputCustom {
19188
/**
19189
* The uri that the tab is representing.
19190
*/
19191
readonly uri: Uri;
19192
/**
19193
* The type of custom editor.
19194
*/
19195
readonly viewType: string;
19196
/**
19197
* Constructs a custom editor tab input.
19198
* @param uri The uri of the tab.
19199
* @param viewType The viewtype of the custom editor.
19200
*/
19201
constructor(uri: Uri, viewType: string);
19202
}
19203
19204
/**
19205
* The tab represents a webview.
19206
*/
19207
export class TabInputWebview {
19208
/**
19209
* The type of webview. Maps to {@linkcode WebviewPanel.viewType WebviewPanel's viewType}
19210
*/
19211
readonly viewType: string;
19212
/**
19213
* Constructs a webview tab input with the given view type.
19214
* @param viewType The type of webview. Maps to {@linkcode WebviewPanel.viewType WebviewPanel's viewType}
19215
*/
19216
constructor(viewType: string);
19217
}
19218
19219
/**
19220
* The tab represents a notebook.
19221
*/
19222
export class TabInputNotebook {
19223
/**
19224
* The uri that the tab is representing.
19225
*/
19226
readonly uri: Uri;
19227
/**
19228
* The type of notebook. Maps to {@linkcode NotebookDocument.notebookType NotebookDocuments's notebookType}
19229
*/
19230
readonly notebookType: string;
19231
/**
19232
* Constructs a new tab input for a notebook.
19233
* @param uri The uri of the notebook.
19234
* @param notebookType The type of notebook. Maps to {@linkcode NotebookDocument.notebookType NotebookDocuments's notebookType}
19235
*/
19236
constructor(uri: Uri, notebookType: string);
19237
}
19238
19239
/**
19240
* The tabs represents two notebooks in a diff configuration.
19241
*/
19242
export class TabInputNotebookDiff {
19243
/**
19244
* The uri of the original notebook.
19245
*/
19246
readonly original: Uri;
19247
/**
19248
* The uri of the modified notebook.
19249
*/
19250
readonly modified: Uri;
19251
/**
19252
* The type of notebook. Maps to {@linkcode NotebookDocument.notebookType NotebookDocuments's notebookType}
19253
*/
19254
readonly notebookType: string;
19255
/**
19256
* Constructs a notebook diff tab input.
19257
* @param original The uri of the original unmodified notebook.
19258
* @param modified The uri of the modified notebook.
19259
* @param notebookType The type of notebook. Maps to {@linkcode NotebookDocument.notebookType NotebookDocuments's notebookType}
19260
*/
19261
constructor(original: Uri, modified: Uri, notebookType: string);
19262
}
19263
19264
/**
19265
* The tab represents a terminal in the editor area.
19266
*/
19267
export class TabInputTerminal {
19268
/**
19269
* Constructs a terminal tab input.
19270
*/
19271
constructor();
19272
}
19273
19274
/**
19275
* Represents a tab within a {@link TabGroup group of tabs}.
19276
* Tabs are merely the graphical representation within the editor area.
19277
* A backing editor is not a guarantee.
19278
*/
19279
export interface Tab {
19280
19281
/**
19282
* The text displayed on the tab.
19283
*/
19284
readonly label: string;
19285
19286
/**
19287
* The group which the tab belongs to.
19288
*/
19289
readonly group: TabGroup;
19290
19291
/**
19292
* Defines the structure of the tab i.e. text, notebook, custom, etc.
19293
* Resource and other useful properties are defined on the tab kind.
19294
*/
19295
readonly input: TabInputText | TabInputTextDiff | TabInputCustom | TabInputWebview | TabInputNotebook | TabInputNotebookDiff | TabInputTerminal | unknown;
19296
19297
/**
19298
* Whether or not the tab is currently active.
19299
* This is dictated by being the selected tab in the group.
19300
*/
19301
readonly isActive: boolean;
19302
19303
/**
19304
* Whether or not the dirty indicator is present on the tab.
19305
*/
19306
readonly isDirty: boolean;
19307
19308
/**
19309
* Whether or not the tab is pinned (pin icon is present).
19310
*/
19311
readonly isPinned: boolean;
19312
19313
/**
19314
* Whether or not the tab is in preview mode.
19315
*/
19316
readonly isPreview: boolean;
19317
}
19318
19319
/**
19320
* An event describing change to tabs.
19321
*/
19322
export interface TabChangeEvent {
19323
/**
19324
* The tabs that have been opened.
19325
*/
19326
readonly opened: readonly Tab[];
19327
/**
19328
* The tabs that have been closed.
19329
*/
19330
readonly closed: readonly Tab[];
19331
/**
19332
* Tabs that have changed, e.g have changed
19333
* their {@link Tab.isActive active} state.
19334
*/
19335
readonly changed: readonly Tab[];
19336
}
19337
19338
/**
19339
* An event describing changes to tab groups.
19340
*/
19341
export interface TabGroupChangeEvent {
19342
/**
19343
* Tab groups that have been opened.
19344
*/
19345
readonly opened: readonly TabGroup[];
19346
/**
19347
* Tab groups that have been closed.
19348
*/
19349
readonly closed: readonly TabGroup[];
19350
/**
19351
* Tab groups that have changed, e.g have changed
19352
* their {@link TabGroup.isActive active} state.
19353
*/
19354
readonly changed: readonly TabGroup[];
19355
}
19356
19357
/**
19358
* Represents a group of tabs. A tab group itself consists of multiple tabs.
19359
*/
19360
export interface TabGroup {
19361
/**
19362
* Whether or not the group is currently active.
19363
*
19364
* *Note* that only one tab group is active at a time, but that multiple tab
19365
* groups can have an {@link activeTab active tab}.
19366
*
19367
* @see {@link Tab.isActive}
19368
*/
19369
readonly isActive: boolean;
19370
19371
/**
19372
* The view column of the group.
19373
*/
19374
readonly viewColumn: ViewColumn;
19375
19376
/**
19377
* The active {@link Tab tab} in the group. This is the tab whose contents are currently
19378
* being rendered.
19379
*
19380
* *Note* that there can be one active tab per group but there can only be one {@link TabGroups.activeTabGroup active group}.
19381
*/
19382
readonly activeTab: Tab | undefined;
19383
19384
/**
19385
* The list of tabs contained within the group.
19386
* This can be empty if the group has no tabs open.
19387
*/
19388
readonly tabs: readonly Tab[];
19389
}
19390
19391
/**
19392
* Represents the main editor area which consists of multiple groups which contain tabs.
19393
*/
19394
export interface TabGroups {
19395
/**
19396
* All the groups within the group container.
19397
*/
19398
readonly all: readonly TabGroup[];
19399
19400
/**
19401
* The currently active group.
19402
*/
19403
readonly activeTabGroup: TabGroup;
19404
19405
/**
19406
* An {@link Event event} which fires when {@link TabGroup tab groups} have changed.
19407
*/
19408
readonly onDidChangeTabGroups: Event<TabGroupChangeEvent>;
19409
19410
/**
19411
* An {@link Event event} which fires when {@link Tab tabs} have changed.
19412
*/
19413
readonly onDidChangeTabs: Event<TabChangeEvent>;
19414
19415
/**
19416
* Closes the tab. This makes the tab object invalid and the tab
19417
* should no longer be used for further actions.
19418
* Note: In the case of a dirty tab, a confirmation dialog will be shown which may be cancelled. If cancelled the tab is still valid
19419
*
19420
* @param tab The tab to close.
19421
* @param preserveFocus When `true` focus will remain in its current position. If `false` it will jump to the next tab.
19422
* @returns A promise that resolves to `true` when all tabs have been closed.
19423
*/
19424
close(tab: Tab | readonly Tab[], preserveFocus?: boolean): Thenable<boolean>;
19425
19426
/**
19427
* Closes the tab group. This makes the tab group object invalid and the tab group
19428
* should no longer be used for further actions.
19429
* @param tabGroup The tab group to close.
19430
* @param preserveFocus When `true` focus will remain in its current position.
19431
* @returns A promise that resolves to `true` when all tab groups have been closed.
19432
*/
19433
close(tabGroup: TabGroup | readonly TabGroup[], preserveFocus?: boolean): Thenable<boolean>;
19434
}
19435
19436
/**
19437
* A special value wrapper denoting a value that is safe to not clean.
19438
* This is to be used when you can guarantee no identifiable information is contained in the value and the cleaning is improperly redacting it.
19439
*/
19440
export class TelemetryTrustedValue<T = any> {
19441
19442
/**
19443
* The value that is trusted to not contain PII.
19444
*/
19445
readonly value: T;
19446
19447
/**
19448
* Creates a new telemetry trusted value.
19449
*
19450
* @param value A value to trust
19451
*/
19452
constructor(value: T);
19453
}
19454
19455
/**
19456
* A telemetry logger which can be used by extensions to log usage and error telemetry.
19457
*
19458
* A logger wraps around an {@link TelemetrySender sender} but it guarantees that
19459
* - user settings to disable or tweak telemetry are respected, and that
19460
* - potential sensitive data is removed
19461
*
19462
* It also enables an "echo UI" that prints whatever data is send and it allows the editor
19463
* to forward unhandled errors to the respective extensions.
19464
*
19465
* To get an instance of a `TelemetryLogger`, use
19466
* {@link env.createTelemetryLogger `createTelemetryLogger`}.
19467
*/
19468
export interface TelemetryLogger {
19469
19470
/**
19471
* An {@link Event} which fires when the enablement state of usage or error telemetry changes.
19472
*/
19473
readonly onDidChangeEnableStates: Event<TelemetryLogger>;
19474
19475
/**
19476
* Whether or not usage telemetry is enabled for this logger.
19477
*/
19478
readonly isUsageEnabled: boolean;
19479
19480
/**
19481
* Whether or not error telemetry is enabled for this logger.
19482
*/
19483
readonly isErrorsEnabled: boolean;
19484
19485
/**
19486
* Log a usage event.
19487
*
19488
* After completing cleaning, telemetry setting checks, and data mix-in calls `TelemetrySender.sendEventData` to log the event.
19489
* Automatically supports echoing to extension telemetry output channel.
19490
* @param eventName The event name to log
19491
* @param data The data to log
19492
*/
19493
logUsage(eventName: string, data?: Record<string, any | TelemetryTrustedValue>): void;
19494
19495
/**
19496
* Log an error event.
19497
*
19498
* 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+.
19499
* Automatically supports echoing to extension telemetry output channel.
19500
* @param eventName The event name to log
19501
* @param data The data to log
19502
*/
19503
logError(eventName: string, data?: Record<string, any | TelemetryTrustedValue>): void;
19504
19505
/**
19506
* Log an error event.
19507
*
19508
* Calls `TelemetrySender.sendErrorData`. Does cleaning, telemetry checks, and data mix-in.
19509
* Automatically supports echoing to extension telemetry output channel.
19510
* Will also automatically log any exceptions thrown within the extension host process.
19511
* @param error The error object which contains the stack trace cleaned of PII
19512
* @param data Additional data to log alongside the stack trace
19513
*/
19514
logError(error: Error, data?: Record<string, any | TelemetryTrustedValue>): void;
19515
19516
/**
19517
* Dispose this object and free resources.
19518
*/
19519
dispose(): void;
19520
}
19521
19522
/**
19523
* The telemetry sender is the contract between a telemetry logger and some telemetry service. **Note** that extensions must NOT
19524
* call the methods of their sender directly as the logger provides extra guards and cleaning.
19525
*
19526
* ```js
19527
* const sender: vscode.TelemetrySender = {...};
19528
* const logger = vscode.env.createTelemetryLogger(sender);
19529
*
19530
* // GOOD - uses the logger
19531
* logger.logUsage('myEvent', { myData: 'myValue' });
19532
*
19533
* // BAD - uses the sender directly: no data cleansing, ignores user settings, no echoing to the telemetry output channel etc
19534
* sender.logEvent('myEvent', { myData: 'myValue' });
19535
* ```
19536
*/
19537
export interface TelemetrySender {
19538
/**
19539
* Function to send event data without a stacktrace. Used within a {@link TelemetryLogger}
19540
*
19541
* @param eventName The name of the event which you are logging
19542
* @param data A serializable key value pair that is being logged
19543
*/
19544
sendEventData(eventName: string, data?: Record<string, any>): void;
19545
19546
/**
19547
* Function to send an error. Used within a {@link TelemetryLogger}
19548
*
19549
* @param error The error being logged
19550
* @param data Any additional data to be collected with the exception
19551
*/
19552
sendErrorData(error: Error, data?: Record<string, any>): void;
19553
19554
/**
19555
* Optional flush function which will give this sender a chance to send any remaining events
19556
* as its {@link TelemetryLogger} is being disposed
19557
*/
19558
flush?(): void | Thenable<void>;
19559
}
19560
19561
/**
19562
* Options for creating a {@link TelemetryLogger}
19563
*/
19564
export interface TelemetryLoggerOptions {
19565
/**
19566
* Whether or not you want to avoid having the built-in common properties such as os, extension name, etc injected into the data object.
19567
* Defaults to `false` if not defined.
19568
*/
19569
readonly ignoreBuiltInCommonProperties?: boolean;
19570
19571
/**
19572
* Whether or not unhandled errors on the extension host caused by your extension should be logged to your sender.
19573
* Defaults to `false` if not defined.
19574
*/
19575
readonly ignoreUnhandledErrors?: boolean;
19576
19577
/**
19578
* Any additional common properties which should be injected into the data object.
19579
*/
19580
readonly additionalCommonProperties?: Record<string, any>;
19581
}
19582
19583
/**
19584
* Represents a user request in chat history.
19585
*/
19586
export class ChatRequestTurn {
19587
/**
19588
* The prompt as entered by the user.
19589
*
19590
* Information about references used in this request is stored in {@link ChatRequestTurn.references}.
19591
*
19592
* *Note* that the {@link ChatParticipant.name name} of the participant and the {@link ChatCommand.name command}
19593
* are not part of the prompt.
19594
*/
19595
readonly prompt: string;
19596
19597
/**
19598
* The id of the chat participant to which this request was directed.
19599
*/
19600
readonly participant: string;
19601
19602
/**
19603
* The name of the {@link ChatCommand command} that was selected for this request.
19604
*/
19605
readonly command?: string;
19606
19607
/**
19608
* The references that were used in this message.
19609
*/
19610
readonly references: ChatPromptReference[];
19611
19612
/**
19613
* The list of tools were attached to this request.
19614
*/
19615
readonly toolReferences: readonly ChatLanguageModelToolReference[];
19616
19617
/**
19618
* @hidden
19619
*/
19620
private constructor(prompt: string, command: string | undefined, references: ChatPromptReference[], participant: string, toolReferences: ChatLanguageModelToolReference[]);
19621
}
19622
19623
/**
19624
* Represents a chat participant's response in chat history.
19625
*/
19626
export class ChatResponseTurn {
19627
/**
19628
* The content that was received from the chat participant. Only the stream parts that represent actual content (not metadata) are represented.
19629
*/
19630
readonly response: ReadonlyArray<ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart | ChatResponseCommandButtonPart>;
19631
19632
/**
19633
* The result that was received from the chat participant.
19634
*/
19635
readonly result: ChatResult;
19636
19637
/**
19638
* The id of the chat participant that this response came from.
19639
*/
19640
readonly participant: string;
19641
19642
/**
19643
* The name of the command that this response came from.
19644
*/
19645
readonly command?: string;
19646
19647
/**
19648
* @hidden
19649
*/
19650
private constructor(response: ReadonlyArray<ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart | ChatResponseCommandButtonPart>, result: ChatResult, participant: string);
19651
}
19652
19653
/**
19654
* Extra context passed to a participant.
19655
*/
19656
export interface ChatContext {
19657
/**
19658
* All of the chat messages so far in the current chat session. Currently, only chat messages for the current participant are included.
19659
*/
19660
readonly history: ReadonlyArray<ChatRequestTurn | ChatResponseTurn>;
19661
}
19662
19663
/**
19664
* Represents an error result from a chat request.
19665
*/
19666
export interface ChatErrorDetails {
19667
/**
19668
* An error message that is shown to the user.
19669
*/
19670
message: string;
19671
19672
/**
19673
* If set to true, the response will be partly blurred out.
19674
*/
19675
responseIsFiltered?: boolean;
19676
}
19677
19678
/**
19679
* The result of a chat request.
19680
*/
19681
export interface ChatResult {
19682
/**
19683
* If the request resulted in an error, this property defines the error details.
19684
*/
19685
errorDetails?: ChatErrorDetails;
19686
19687
/**
19688
* Arbitrary metadata for this result. Can be anything, but must be JSON-stringifyable.
19689
*/
19690
readonly metadata?: { readonly [key: string]: any };
19691
}
19692
19693
/**
19694
* Represents the type of user feedback received.
19695
*/
19696
export enum ChatResultFeedbackKind {
19697
/**
19698
* The user marked the result as unhelpful.
19699
*/
19700
Unhelpful = 0,
19701
19702
/**
19703
* The user marked the result as helpful.
19704
*/
19705
Helpful = 1,
19706
}
19707
19708
/**
19709
* Represents user feedback for a result.
19710
*/
19711
export interface ChatResultFeedback {
19712
/**
19713
* The ChatResult for which the user is providing feedback.
19714
* This object has the same properties as the result returned from the participant callback, including `metadata`, but is not the same instance.
19715
*/
19716
readonly result: ChatResult;
19717
19718
/**
19719
* The kind of feedback that was received.
19720
*/
19721
readonly kind: ChatResultFeedbackKind;
19722
}
19723
19724
/**
19725
* A followup question suggested by the participant.
19726
*/
19727
export interface ChatFollowup {
19728
/**
19729
* The message to send to the chat.
19730
*/
19731
prompt: string;
19732
19733
/**
19734
* A title to show the user. The prompt will be shown by default, when this is unspecified.
19735
*/
19736
label?: string;
19737
19738
/**
19739
* By default, the followup goes to the same participant/command. But this property can be set to invoke a different participant by ID.
19740
* Followups can only invoke a participant that was contributed by the same extension.
19741
*/
19742
participant?: string;
19743
19744
/**
19745
* By default, the followup goes to the same participant/command. But this property can be set to invoke a different command.
19746
*/
19747
command?: string;
19748
}
19749
19750
/**
19751
* Will be invoked once after each request to get suggested followup questions to show the user. The user can click the followup to send it to the chat.
19752
*/
19753
export interface ChatFollowupProvider {
19754
/**
19755
* Provide followups for the given result.
19756
*
19757
* @param result This object has the same properties as the result returned from the participant callback, including `metadata`, but is not the same instance.
19758
* @param context Extra context passed to a participant.
19759
* @param token A cancellation token.
19760
*/
19761
provideFollowups(result: ChatResult, context: ChatContext, token: CancellationToken): ProviderResult<ChatFollowup[]>;
19762
}
19763
19764
/**
19765
* A chat request handler is a callback that will be invoked when a request is made to a chat participant.
19766
*/
19767
export type ChatRequestHandler = (request: ChatRequest, context: ChatContext, response: ChatResponseStream, token: CancellationToken) => ProviderResult<ChatResult | void>;
19768
19769
/**
19770
* A chat participant can be invoked by the user in a chat session, using the `@` prefix. When it is invoked, it handles the chat request and is solely
19771
* responsible for providing a response to the user. A ChatParticipant is created using {@link chat.createChatParticipant}.
19772
*/
19773
export interface ChatParticipant {
19774
/**
19775
* A unique ID for this participant.
19776
*/
19777
readonly id: string;
19778
19779
/**
19780
* An icon for the participant shown in UI.
19781
*/
19782
iconPath?: IconPath;
19783
19784
/**
19785
* The handler for requests to this participant.
19786
*/
19787
requestHandler: ChatRequestHandler;
19788
19789
/**
19790
* This provider will be called once after each request to retrieve suggested followup questions.
19791
*/
19792
followupProvider?: ChatFollowupProvider;
19793
19794
/**
19795
* An event that fires whenever feedback for a result is received, e.g. when a user up- or down-votes
19796
* a result.
19797
*
19798
* The passed {@link ChatResultFeedback.result result} is guaranteed to have the same properties as the result that was
19799
* previously returned from this chat participant's handler.
19800
*/
19801
readonly onDidReceiveFeedback: Event<ChatResultFeedback>;
19802
19803
/**
19804
* Dispose this participant and free resources.
19805
*/
19806
dispose(): void;
19807
}
19808
19809
/**
19810
* A reference to a value that the user added to their chat request.
19811
*/
19812
export interface ChatPromptReference {
19813
/**
19814
* A unique identifier for this kind of reference.
19815
*/
19816
readonly id: string;
19817
19818
/**
19819
* The start and end index of the reference in the {@link ChatRequest.prompt prompt}. When undefined, the reference was not part of the prompt text.
19820
*
19821
* *Note* that the indices take the leading `#`-character into account which means they can
19822
* used to modify the prompt as-is.
19823
*/
19824
readonly range?: [start: number, end: number];
19825
19826
/**
19827
* A description of this value that could be used in an LLM prompt.
19828
*/
19829
readonly modelDescription?: string;
19830
19831
/**
19832
* The value of this reference. The `string | Uri | Location` types are used today, but this could expand in the future.
19833
*/
19834
readonly value: string | Uri | Location | unknown;
19835
}
19836
19837
/**
19838
* A request to a chat participant.
19839
*/
19840
export interface ChatRequest {
19841
/**
19842
* The prompt as entered by the user.
19843
*
19844
* Information about references used in this request is stored in {@link ChatRequest.references}.
19845
*
19846
* *Note* that the {@link ChatParticipant.name name} of the participant and the {@link ChatCommand.name command}
19847
* are not part of the prompt.
19848
*/
19849
readonly prompt: string;
19850
19851
/**
19852
* The name of the {@link ChatCommand command} that was selected for this request.
19853
*/
19854
readonly command: string | undefined;
19855
19856
/**
19857
* The list of references and their values that are referenced in the prompt.
19858
*
19859
* *Note* that the prompt contains references as authored and that it is up to the participant
19860
* to further modify the prompt, for instance by inlining reference values or creating links to
19861
* headings which contain the resolved values. References are sorted in reverse by their range
19862
* in the prompt. That means the last reference in the prompt is the first in this list. This simplifies
19863
* string-manipulation of the prompt.
19864
*/
19865
readonly references: readonly ChatPromptReference[];
19866
19867
/**
19868
* The list of tools that the user attached to their request.
19869
*
19870
* When a tool reference is present, the chat participant should make a chat request using
19871
* {@link LanguageModelChatToolMode.Required} to force the language model to generate input for the tool. Then, the
19872
* participant can use {@link lm.invokeTool} to use the tool attach the result to its request for the user's prompt. The
19873
* tool may contribute useful extra context for the user's request.
19874
*/
19875
readonly toolReferences: readonly ChatLanguageModelToolReference[];
19876
19877
/**
19878
* A token that can be passed to {@link lm.invokeTool} when invoking a tool inside the context of handling a chat request.
19879
* This associates the tool invocation to a chat session.
19880
*/
19881
readonly toolInvocationToken: ChatParticipantToolToken;
19882
19883
/**
19884
* This is the model that is currently selected in the UI. Extensions can use this or use {@link lm.selectChatModels} to
19885
* pick another model. Don't hold onto this past the lifetime of the request.
19886
*/
19887
readonly model: LanguageModelChat;
19888
}
19889
19890
/**
19891
* The ChatResponseStream is how a participant is able to return content to the chat view. It provides several methods for streaming different types of content
19892
* which will be rendered in an appropriate way in the chat view. A participant can use the helper method for the type of content it wants to return, or it
19893
* can instantiate a {@link ChatResponsePart} and use the generic {@link ChatResponseStream.push} method to return it.
19894
*/
19895
export interface ChatResponseStream {
19896
/**
19897
* Push a markdown part to this stream. Short-hand for
19898
* `push(new ChatResponseMarkdownPart(value))`.
19899
*
19900
* @see {@link ChatResponseStream.push}
19901
* @param value A markdown string or a string that should be interpreted as markdown. The boolean form of {@link MarkdownString.isTrusted} is NOT supported.
19902
*/
19903
markdown(value: string | MarkdownString): void;
19904
19905
/**
19906
* Push an anchor part to this stream. Short-hand for
19907
* `push(new ChatResponseAnchorPart(value, title))`.
19908
* An anchor is an inline reference to some type of resource.
19909
*
19910
* @param value A uri or location.
19911
* @param title An optional title that is rendered with value.
19912
*/
19913
anchor(value: Uri | Location, title?: string): void;
19914
19915
/**
19916
* Push a command button part to this stream. Short-hand for
19917
* `push(new ChatResponseCommandButtonPart(value, title))`.
19918
*
19919
* @param command A Command that will be executed when the button is clicked.
19920
*/
19921
button(command: Command): void;
19922
19923
/**
19924
* Push a filetree part to this stream. Short-hand for
19925
* `push(new ChatResponseFileTreePart(value))`.
19926
*
19927
* @param value File tree data.
19928
* @param baseUri The base uri to which this file tree is relative.
19929
*/
19930
filetree(value: ChatResponseFileTree[], baseUri: Uri): void;
19931
19932
/**
19933
* Push a progress part to this stream. Short-hand for
19934
* `push(new ChatResponseProgressPart(value))`.
19935
*
19936
* @param value A progress message
19937
*/
19938
progress(value: string): void;
19939
19940
/**
19941
* Push a reference to this stream. Short-hand for
19942
* `push(new ChatResponseReferencePart(value))`.
19943
*
19944
* *Note* that the reference is not rendered inline with the response.
19945
*
19946
* @param value A uri or location
19947
* @param iconPath Icon for the reference shown in UI
19948
*/
19949
reference(value: Uri | Location, iconPath?: IconPath): void;
19950
19951
/**
19952
* Pushes a part to this stream.
19953
*
19954
* @param part A response part, rendered or metadata
19955
*/
19956
push(part: ChatResponsePart): void;
19957
}
19958
19959
/**
19960
* Represents a part of a chat response that is formatted as Markdown.
19961
*/
19962
export class ChatResponseMarkdownPart {
19963
/**
19964
* A markdown string or a string that should be interpreted as markdown.
19965
*/
19966
value: MarkdownString;
19967
19968
/**
19969
* Create a new ChatResponseMarkdownPart.
19970
*
19971
* @param value A markdown string or a string that should be interpreted as markdown. The boolean form of {@link MarkdownString.isTrusted} is NOT supported.
19972
*/
19973
constructor(value: string | MarkdownString);
19974
}
19975
19976
/**
19977
* Represents a file tree structure in a chat response.
19978
*/
19979
export interface ChatResponseFileTree {
19980
/**
19981
* The name of the file or directory.
19982
*/
19983
name: string;
19984
19985
/**
19986
* An array of child file trees, if the current file tree is a directory.
19987
*/
19988
children?: ChatResponseFileTree[];
19989
}
19990
19991
/**
19992
* Represents a part of a chat response that is a file tree.
19993
*/
19994
export class ChatResponseFileTreePart {
19995
/**
19996
* File tree data.
19997
*/
19998
value: ChatResponseFileTree[];
19999
20000
/**
20001
* The base uri to which this file tree is relative
20002
*/
20003
baseUri: Uri;
20004
20005
/**
20006
* Create a new ChatResponseFileTreePart.
20007
* @param value File tree data.
20008
* @param baseUri The base uri to which this file tree is relative.
20009
*/
20010
constructor(value: ChatResponseFileTree[], baseUri: Uri);
20011
}
20012
20013
/**
20014
* Represents a part of a chat response that is an anchor, that is rendered as a link to a target.
20015
*/
20016
export class ChatResponseAnchorPart {
20017
/**
20018
* The target of this anchor.
20019
*/
20020
value: Uri | Location;
20021
20022
/**
20023
* An optional title that is rendered with value.
20024
*/
20025
title?: string;
20026
20027
/**
20028
* Create a new ChatResponseAnchorPart.
20029
* @param value A uri or location.
20030
* @param title An optional title that is rendered with value.
20031
*/
20032
constructor(value: Uri | Location, title?: string);
20033
}
20034
20035
/**
20036
* Represents a part of a chat response that is a progress message.
20037
*/
20038
export class ChatResponseProgressPart {
20039
/**
20040
* The progress message
20041
*/
20042
value: string;
20043
20044
/**
20045
* Create a new ChatResponseProgressPart.
20046
* @param value A progress message
20047
*/
20048
constructor(value: string);
20049
}
20050
20051
/**
20052
* Represents a part of a chat response that is a reference, rendered separately from the content.
20053
*/
20054
export class ChatResponseReferencePart {
20055
/**
20056
* The reference target.
20057
*/
20058
value: Uri | Location;
20059
20060
/**
20061
* The icon for the reference.
20062
*/
20063
iconPath?: IconPath;
20064
20065
/**
20066
* Create a new ChatResponseReferencePart.
20067
* @param value A uri or location
20068
* @param iconPath Icon for the reference shown in UI
20069
*/
20070
constructor(value: Uri | Location, iconPath?: IconPath);
20071
}
20072
20073
/**
20074
* Represents a part of a chat response that is a button that executes a command.
20075
*/
20076
export class ChatResponseCommandButtonPart {
20077
/**
20078
* The command that will be executed when the button is clicked.
20079
*/
20080
value: Command;
20081
20082
/**
20083
* Create a new ChatResponseCommandButtonPart.
20084
* @param value A Command that will be executed when the button is clicked.
20085
*/
20086
constructor(value: Command);
20087
}
20088
20089
/**
20090
* Represents the different chat response types.
20091
*/
20092
export type ChatResponsePart = ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart
20093
| ChatResponseProgressPart | ChatResponseReferencePart | ChatResponseCommandButtonPart;
20094
20095
20096
/**
20097
* Namespace for chat functionality. Users interact with chat participants by sending messages
20098
* to them in the chat view. Chat participants can respond with markdown or other types of content
20099
* via the {@link ChatResponseStream}.
20100
*/
20101
export namespace chat {
20102
/**
20103
* Create a new {@link ChatParticipant chat participant} instance.
20104
*
20105
* @param id A unique identifier for the participant.
20106
* @param handler A request handler for the participant.
20107
* @returns A new chat participant
20108
*/
20109
export function createChatParticipant(id: string, handler: ChatRequestHandler): ChatParticipant;
20110
}
20111
20112
/**
20113
* Represents the role of a chat message. This is either the user or the assistant.
20114
*/
20115
export enum LanguageModelChatMessageRole {
20116
/**
20117
* The user role, e.g the human interacting with a language model.
20118
*/
20119
User = 1,
20120
20121
/**
20122
* The assistant role, e.g. the language model generating responses.
20123
*/
20124
Assistant = 2
20125
}
20126
20127
/**
20128
* Represents a message in a chat. Can assume different roles, like user or assistant.
20129
*/
20130
export class LanguageModelChatMessage {
20131
20132
/**
20133
* Utility to create a new user message.
20134
*
20135
* @param content The content of the message.
20136
* @param name The optional name of a user for the message.
20137
*/
20138
static User(content: string | Array<LanguageModelTextPart | LanguageModelToolResultPart | LanguageModelDataPart>, name?: string): LanguageModelChatMessage;
20139
20140
/**
20141
* Utility to create a new assistant message.
20142
*
20143
* @param content The content of the message.
20144
* @param name The optional name of a user for the message.
20145
*/
20146
static Assistant(content: string | Array<LanguageModelTextPart | LanguageModelToolCallPart | LanguageModelDataPart>, name?: string): LanguageModelChatMessage;
20147
20148
/**
20149
* The role of this message.
20150
*/
20151
role: LanguageModelChatMessageRole;
20152
20153
/**
20154
* A string or heterogeneous array of things that a message can contain as content. Some parts may be message-type
20155
* specific for some models.
20156
*/
20157
content: Array<LanguageModelInputPart>;
20158
20159
/**
20160
* The optional name of a user for this message.
20161
*/
20162
name: string | undefined;
20163
20164
/**
20165
* Create a new user message.
20166
*
20167
* @param role The role of the message.
20168
* @param content The content of the message.
20169
* @param name The optional name of a user for the message.
20170
*/
20171
constructor(role: LanguageModelChatMessageRole, content: string | Array<LanguageModelInputPart>, name?: string);
20172
}
20173
20174
/**
20175
* Represents a language model response.
20176
*
20177
* @see {@link ChatRequest}
20178
*/
20179
export interface LanguageModelChatResponse {
20180
20181
/**
20182
* An async iterable that is a stream of text and tool-call parts forming the overall response. A
20183
* {@link LanguageModelTextPart} is part of the assistant's response to be shown to the user. A
20184
* {@link LanguageModelToolCallPart} is a request from the language model to call a tool. The latter will
20185
* only be returned if tools were passed in the request via {@link LanguageModelChatRequestOptions.tools}. The
20186
* `unknown`-type is used as a placeholder for future parts, like image data parts.
20187
*
20188
* *Note* that this stream will error when during data receiving an error occurs. Consumers of the stream should handle
20189
* the errors accordingly.
20190
*
20191
* To cancel the stream, the consumer can {@link CancellationTokenSource.cancel cancel} the token that was used to make
20192
* the request or break from the for-loop.
20193
*
20194
* @example
20195
* ```ts
20196
* try {
20197
* // consume stream
20198
* for await (const chunk of response.stream) {
20199
* if (chunk instanceof LanguageModelTextPart) {
20200
* console.log("TEXT", chunk);
20201
* } else if (chunk instanceof LanguageModelToolCallPart) {
20202
* console.log("TOOL CALL", chunk);
20203
* }
20204
* }
20205
*
20206
* } catch(e) {
20207
* // stream ended with an error
20208
* console.error(e);
20209
* }
20210
* ```
20211
*/
20212
stream: AsyncIterable<LanguageModelTextPart | LanguageModelToolCallPart | LanguageModelDataPart | unknown>;
20213
20214
/**
20215
* This is equivalent to filtering everything except for text parts from a {@link LanguageModelChatResponse.stream}.
20216
*
20217
* @see {@link LanguageModelChatResponse.stream}
20218
*/
20219
text: AsyncIterable<string>;
20220
}
20221
20222
/**
20223
* Represents a language model for making chat requests.
20224
*
20225
* @see {@link lm.selectChatModels}
20226
*/
20227
export interface LanguageModelChat {
20228
20229
/**
20230
* Human-readable name of the language model.
20231
*/
20232
readonly name: string;
20233
20234
/**
20235
* Opaque identifier of the language model.
20236
*/
20237
readonly id: string;
20238
20239
/**
20240
* A well-known identifier of the vendor of the language model. An example is `copilot`, but
20241
* values are defined by extensions contributing chat models and need to be looked up with them.
20242
*/
20243
readonly vendor: string;
20244
20245
/**
20246
* Opaque family-name of the language model. Values might be `gpt-3.5-turbo`, `gpt4`, `phi2`, or `llama`
20247
* but they are defined by extensions contributing languages and subject to change.
20248
*/
20249
readonly family: string;
20250
20251
/**
20252
* Opaque version string of the model. This is defined by the extension contributing the language model
20253
* and subject to change.
20254
*/
20255
readonly version: string;
20256
20257
/**
20258
* The maximum number of tokens that can be sent to the model in a single request.
20259
*/
20260
readonly maxInputTokens: number;
20261
20262
/**
20263
* Make a chat request using a language model.
20264
*
20265
* *Note* that language model use may be subject to access restrictions and user consent. Calling this function
20266
* for the first time (for an extension) will show a consent dialog to the user and because of that this function
20267
* must _only be called in response to a user action!_ Extensions can use {@link LanguageModelAccessInformation.canSendRequest}
20268
* to check if they have the necessary permissions to make a request.
20269
*
20270
* This function will return a rejected promise if making a request to the language model is not
20271
* possible. Reasons for this can be:
20272
*
20273
* - user consent not given, see {@link LanguageModelError.NoPermissions `NoPermissions`}
20274
* - model does not exist anymore, see {@link LanguageModelError.NotFound `NotFound`}
20275
* - quota limits exceeded, see {@link LanguageModelError.Blocked `Blocked`}
20276
* - other issues in which case extension must check {@link LanguageModelError.cause `LanguageModelError.cause`}
20277
*
20278
* An extension can make use of language model tool calling by passing a set of tools to
20279
* {@link LanguageModelChatRequestOptions.tools}. The language model will return a {@link LanguageModelToolCallPart} and
20280
* the extension can invoke the tool and make another request with the result.
20281
*
20282
* @param messages An array of message instances.
20283
* @param options Options that control the request.
20284
* @param token A cancellation token which controls the request. See {@link CancellationTokenSource} for how to create one.
20285
* @returns A thenable that resolves to a {@link LanguageModelChatResponse}. The promise will reject when the request couldn't be made.
20286
*/
20287
sendRequest(messages: LanguageModelChatMessage[], options?: LanguageModelChatRequestOptions, token?: CancellationToken): Thenable<LanguageModelChatResponse>;
20288
20289
/**
20290
* Count the number of tokens in a message using the model specific tokenizer-logic.
20291
20292
* @param text A string or a message instance.
20293
* @param token Optional cancellation token. See {@link CancellationTokenSource} for how to create one.
20294
* @returns A thenable that resolves to the number of tokens.
20295
*/
20296
countTokens(text: string | LanguageModelChatMessage, token?: CancellationToken): Thenable<number>;
20297
}
20298
20299
/**
20300
* Describes how to select language models for chat requests.
20301
*
20302
* @see {@link lm.selectChatModels}
20303
*/
20304
export interface LanguageModelChatSelector {
20305
20306
/**
20307
* A vendor of language models.
20308
* @see {@link LanguageModelChat.vendor}
20309
*/
20310
vendor?: string;
20311
20312
/**
20313
* A family of language models.
20314
* @see {@link LanguageModelChat.family}
20315
*/
20316
family?: string;
20317
20318
/**
20319
* The version of a language model.
20320
* @see {@link LanguageModelChat.version}
20321
*/
20322
version?: string;
20323
20324
/**
20325
* The identifier of a language model.
20326
* @see {@link LanguageModelChat.id}
20327
*/
20328
id?: string;
20329
}
20330
20331
/**
20332
* An error type for language model specific errors.
20333
*
20334
* Consumers of language models should check the code property to determine specific
20335
* failure causes, like `if(someError.code === vscode.LanguageModelError.NotFound.name) {...}`
20336
* for the case of referring to an unknown language model. For unspecified errors the `cause`-property
20337
* will contain the actual error.
20338
*/
20339
export class LanguageModelError extends Error {
20340
20341
/**
20342
* The requestor does not have permissions to use this
20343
* language model
20344
*/
20345
static NoPermissions(message?: string): LanguageModelError;
20346
20347
/**
20348
* The requestor is blocked from using this language model.
20349
*/
20350
static Blocked(message?: string): LanguageModelError;
20351
20352
/**
20353
* The language model does not exist.
20354
*/
20355
static NotFound(message?: string): LanguageModelError;
20356
20357
/**
20358
* A code that identifies this error.
20359
*
20360
* Possible values are names of errors, like {@linkcode LanguageModelError.NotFound NotFound},
20361
* or `Unknown` for unspecified errors from the language model itself. In the latter case the
20362
* `cause`-property will contain the actual error.
20363
*/
20364
readonly code: string;
20365
}
20366
20367
/**
20368
* Options for making a chat request using a language model.
20369
*
20370
* @see {@link LanguageModelChat.sendRequest}
20371
*/
20372
export interface LanguageModelChatRequestOptions {
20373
20374
/**
20375
* A human-readable message that explains why access to a language model is needed and what feature is enabled by it.
20376
*/
20377
justification?: string;
20378
20379
/**
20380
* A set of options that control the behavior of the language model. These options are specific to the language model
20381
* and need to be looked up in the respective documentation.
20382
*/
20383
modelOptions?: { [name: string]: any };
20384
20385
/**
20386
* An optional list of tools that are available to the language model. These could be registered tools available via
20387
* {@link lm.tools}, or private tools that are just implemented within the calling extension.
20388
*
20389
* If the LLM requests to call one of these tools, it will return a {@link LanguageModelToolCallPart} in
20390
* {@link LanguageModelChatResponse.stream}. It's the caller's responsibility to invoke the tool. If it's a tool
20391
* registered in {@link lm.tools}, that means calling {@link lm.invokeTool}.
20392
*
20393
* Then, the tool result can be provided to the LLM by creating an Assistant-type {@link LanguageModelChatMessage} with a
20394
* {@link LanguageModelToolCallPart}, followed by a User-type message with a {@link LanguageModelToolResultPart}.
20395
*/
20396
tools?: LanguageModelChatTool[];
20397
20398
/**
20399
* The tool-selecting mode to use. {@link LanguageModelChatToolMode.Auto} by default.
20400
*/
20401
toolMode?: LanguageModelChatToolMode;
20402
}
20403
20404
/**
20405
* McpStdioServerDefinition represents an MCP server available by running
20406
* a local process and operating on its stdin and stdout streams. The process
20407
* will be spawned as a child process of the extension host and by default
20408
* will not run in a shell environment.
20409
*/
20410
export class McpStdioServerDefinition {
20411
/**
20412
* The human-readable name of the server.
20413
*/
20414
readonly label: string;
20415
20416
/**
20417
* The working directory used to start the server.
20418
*/
20419
cwd?: Uri;
20420
20421
/**
20422
* The command used to start the server. Node.js-based servers may use
20423
* `process.execPath` to use the editor's version of Node.js to run the script.
20424
*/
20425
command: string;
20426
20427
/**
20428
* Additional command-line arguments passed to the server.
20429
*/
20430
args: string[];
20431
20432
/**
20433
* Optional additional environment information for the server. Variables
20434
* in this environment will overwrite or remove (if null) the default
20435
* environment variables of the editor's extension host.
20436
*/
20437
env: Record<string, string | number | null>;
20438
20439
/**
20440
* Optional version identification for the server. If this changes, the
20441
* editor will indicate that tools have changed and prompt to refresh them.
20442
*/
20443
version?: string;
20444
20445
/**
20446
* @param label The human-readable name of the server.
20447
* @param command The command used to start the server.
20448
* @param args Additional command-line arguments passed to the server.
20449
* @param env Optional additional environment information for the server.
20450
* @param version Optional version identification for the server.
20451
*/
20452
constructor(label: string, command: string, args?: string[], env?: Record<string, string | number | null>, version?: string);
20453
}
20454
20455
/**
20456
* McpHttpServerDefinition represents an MCP server available using the
20457
* Streamable HTTP transport.
20458
*/
20459
export class McpHttpServerDefinition {
20460
/**
20461
* The human-readable name of the server.
20462
*/
20463
readonly label: string;
20464
20465
/**
20466
* The URI of the server. The editor will make a POST request to this URI
20467
* to begin each session.
20468
*/
20469
uri: Uri;
20470
20471
/**
20472
* Optional additional heads included with each request to the server.
20473
*/
20474
headers: Record<string, string>;
20475
20476
/**
20477
* Optional version identification for the server. If this changes, the
20478
* editor will indicate that tools have changed and prompt to refresh them.
20479
*/
20480
version?: string;
20481
20482
/**
20483
* @param label The human-readable name of the server.
20484
* @param uri The URI of the server.
20485
* @param headers Optional additional heads included with each request to the server.
20486
*/
20487
constructor(label: string, uri: Uri, headers?: Record<string, string>, version?: string);
20488
}
20489
20490
/**
20491
* Definitions that describe different types of Model Context Protocol servers,
20492
* which can be returned from the {@link McpServerDefinitionProvider}.
20493
*/
20494
export type McpServerDefinition = McpStdioServerDefinition | McpHttpServerDefinition;
20495
20496
/**
20497
* A type that can provide Model Context Protocol server definitions. This
20498
* should be registered using {@link lm.registerMcpServerDefinitionProvider}
20499
* during extension activation.
20500
*/
20501
export interface McpServerDefinitionProvider<T extends McpServerDefinition = McpServerDefinition> {
20502
/**
20503
* Optional event fired to signal that the set of available servers has changed.
20504
*/
20505
readonly onDidChangeMcpServerDefinitions?: Event<void>;
20506
20507
/**
20508
* Provides available MCP servers. The editor will call this method eagerly
20509
* to ensure the availability of servers for the language model, and so
20510
* extensions should not take actions which would require user
20511
* interaction, such as authentication.
20512
*
20513
* @param token A cancellation token.
20514
* @returns An array of MCP available MCP servers
20515
*/
20516
provideMcpServerDefinitions(token: CancellationToken): ProviderResult<T[]>;
20517
20518
/**
20519
* This function will be called when the editor needs to start a MCP server.
20520
* At this point, the extension may take any actions which may require user
20521
* interaction, such as authentication. Any non-`readonly` property of the
20522
* server may be modified, and the extension should return the resolved server.
20523
*
20524
* The extension may return undefined to indicate that the server
20525
* should not be started, or throw an error. If there is a pending tool
20526
* call, the editor will cancel it and return an error message to the
20527
* language model.
20528
*
20529
* @param server The MCP server to resolve
20530
* @param token A cancellation token.
20531
* @returns The resolved server or thenable that resolves to such. This may
20532
* be the given `server` definition with non-readonly properties filled in.
20533
*/
20534
resolveMcpServerDefinition?(server: T, token: CancellationToken): ProviderResult<T>;
20535
}
20536
20537
/**
20538
* The provider version of {@linkcode LanguageModelChatRequestOptions}
20539
*/
20540
export interface ProvideLanguageModelChatResponseOptions {
20541
/**
20542
* A set of options that control the behavior of the language model. These options are specific to the language model.
20543
*/
20544
readonly modelOptions?: { readonly [name: string]: any };
20545
20546
/**
20547
* An optional list of tools that are available to the language model. These could be registered tools available via
20548
* {@link lm.tools}, or private tools that are just implemented within the calling extension.
20549
*
20550
* If the LLM requests to call one of these tools, it will return a {@link LanguageModelToolCallPart} in
20551
* {@link LanguageModelChatResponse.stream}. It's the caller's responsibility to invoke the tool. If it's a tool
20552
* registered in {@link lm.tools}, that means calling {@link lm.invokeTool}.
20553
*
20554
* Then, the tool result can be provided to the LLM by creating an Assistant-type {@link LanguageModelChatMessage} with a
20555
* {@link LanguageModelToolCallPart}, followed by a User-type message with a {@link LanguageModelToolResultPart}.
20556
*/
20557
readonly tools?: readonly LanguageModelChatTool[];
20558
20559
/**
20560
* The tool-selecting mode to use. The provider must implement respecting this.
20561
*/
20562
readonly toolMode: LanguageModelChatToolMode;
20563
}
20564
20565
/**
20566
* Represents a language model provided by a {@linkcode LanguageModelChatProvider}.
20567
*/
20568
export interface LanguageModelChatInformation {
20569
20570
/**
20571
* Unique identifier for the language model. Must be unique per provider, but not required to be globally unique.
20572
*/
20573
readonly id: string;
20574
20575
/**
20576
* Human-readable name of the language model.
20577
*/
20578
readonly name: string;
20579
20580
/**
20581
* Opaque family-name of the language model. Values might be `gpt-3.5-turbo`, `gpt4`, `phi2`, or `llama`
20582
*/
20583
readonly family: string;
20584
20585
/**
20586
* The tooltip to render when hovering the model. Used to provide more information about the model.
20587
*/
20588
readonly tooltip?: string;
20589
20590
/**
20591
* An optional, human-readable string which will be rendered alongside the model.
20592
* Useful for distinguishing models of the same name in the UI.
20593
*/
20594
readonly detail?: string;
20595
20596
/**
20597
* Opaque version string of the model.
20598
* This is used as a lookup value in {@linkcode LanguageModelChatSelector.version}
20599
* An example is how GPT 4o has multiple versions like 2024-11-20 and 2024-08-06
20600
*/
20601
readonly version: string;
20602
20603
/**
20604
* The maximum number of tokens the model can accept as input.
20605
*/
20606
readonly maxInputTokens: number;
20607
20608
/**
20609
* The maximum number of tokens the model is capable of producing.
20610
*/
20611
readonly maxOutputTokens: number;
20612
20613
/**
20614
* Various features that the model supports such as tool calling or image input.
20615
*/
20616
readonly capabilities: LanguageModelChatCapabilities;
20617
}
20618
20619
/**
20620
* Various features that the {@link LanguageModelChatInformation} supports such as tool calling or image input.
20621
*/
20622
export interface LanguageModelChatCapabilities {
20623
/**
20624
* Whether image input is supported by the model.
20625
* Common supported images are jpg and png, but each model will vary in supported mimetypes.
20626
*/
20627
readonly imageInput?: boolean;
20628
20629
/**
20630
* Whether tool calling is supported by the model.
20631
* If a number is provided, that is the maximum number of tools that can be provided in a request to the model.
20632
*/
20633
readonly toolCalling?: boolean | number;
20634
}
20635
20636
/**
20637
* The provider version of {@linkcode LanguageModelChatMessage}.
20638
*/
20639
export interface LanguageModelChatRequestMessage {
20640
/**
20641
* The role of this message.
20642
*/
20643
readonly role: LanguageModelChatMessageRole;
20644
20645
/**
20646
* A heterogeneous array of things that a message can contain as content. Some parts may be message-type
20647
* specific for some models.
20648
*/
20649
readonly content: ReadonlyArray<LanguageModelInputPart | unknown>;
20650
20651
/**
20652
* The optional name of a user for this message.
20653
*/
20654
readonly name: string | undefined;
20655
}
20656
20657
/**
20658
* The various message types which a {@linkcode LanguageModelChatProvider} can emit in the chat response stream
20659
*/
20660
export type LanguageModelResponsePart = LanguageModelTextPart | LanguageModelToolResultPart | LanguageModelToolCallPart | LanguageModelDataPart;
20661
20662
/**
20663
* The various message types which can be sent via {@linkcode LanguageModelChat.sendRequest } and processed by a {@linkcode LanguageModelChatProvider}
20664
*/
20665
export type LanguageModelInputPart = LanguageModelTextPart | LanguageModelToolResultPart | LanguageModelToolCallPart | LanguageModelDataPart;
20666
20667
/**
20668
* A LanguageModelChatProvider implements access to language models, which users can then use through the chat view, or through extension API by acquiring a LanguageModelChat.
20669
* An example of this would be an OpenAI provider that provides models like gpt-5, o3, etc.
20670
*/
20671
export interface LanguageModelChatProvider<T extends LanguageModelChatInformation = LanguageModelChatInformation> {
20672
20673
/**
20674
* An optional event fired when the available set of language models changes.
20675
*/
20676
readonly onDidChangeLanguageModelChatInformation?: Event<void>;
20677
20678
/**
20679
* Get the list of available language models provided by this provider
20680
* @param options Options which specify the calling context of this function
20681
* @param token A cancellation token
20682
* @returns The list of available language models
20683
*/
20684
provideLanguageModelChatInformation(options: PrepareLanguageModelChatModelOptions, token: CancellationToken): ProviderResult<T[]>;
20685
20686
/**
20687
* Returns the response for a chat request, passing the results to the progress callback.
20688
* The {@linkcode LanguageModelChatProvider} must emit the response parts to the progress callback as they are received from the language model.
20689
* @param model The language model to use
20690
* @param messages The messages to include in the request
20691
* @param options Options for the request
20692
* @param progress The progress to emit the streamed response chunks to
20693
* @param token A cancellation token
20694
* @returns A promise that resolves when the response is complete. Results are actually passed to the progress callback.
20695
*/
20696
provideLanguageModelChatResponse(model: T, messages: readonly LanguageModelChatRequestMessage[], options: ProvideLanguageModelChatResponseOptions, progress: Progress<LanguageModelResponsePart>, token: CancellationToken): Thenable<void>;
20697
20698
/**
20699
* Returns the number of tokens for a given text using the model-specific tokenizer logic
20700
* @param model The language model to use
20701
* @param text The text to count tokens for
20702
* @param token A cancellation token
20703
* @returns The number of tokens
20704
*/
20705
provideTokenCount(model: T, text: string | LanguageModelChatRequestMessage, token: CancellationToken): Thenable<number>;
20706
}
20707
20708
/**
20709
* The list of options passed into {@linkcode LanguageModelChatProvider.provideLanguageModelChatInformation}
20710
*/
20711
export interface PrepareLanguageModelChatModelOptions {
20712
/**
20713
* Whether or not the user should be prompted via some UI flow, or if models should be attempted to be resolved silently.
20714
* If silent is true, all models may not be resolved due to lack of info such as API keys.
20715
*/
20716
readonly silent: boolean;
20717
}
20718
20719
/**
20720
* Namespace for language model related functionality.
20721
*/
20722
export namespace lm {
20723
20724
/**
20725
* An event that is fired when the set of available chat models changes.
20726
*/
20727
export const onDidChangeChatModels: Event<void>;
20728
20729
/**
20730
* Select chat models by a {@link LanguageModelChatSelector selector}. This can yield multiple or no chat models and
20731
* extensions must handle these cases, esp. when no chat model exists, gracefully.
20732
*
20733
* ```ts
20734
* const models = await vscode.lm.selectChatModels({ family: 'gpt-3.5-turbo' });
20735
* if (models.length > 0) {
20736
* const [first] = models;
20737
* const response = await first.sendRequest(...)
20738
* // ...
20739
* } else {
20740
* // NO chat models available
20741
* }
20742
* ```
20743
*
20744
* A selector can be written to broadly match all models of a given vendor or family, or it can narrowly select one model by ID.
20745
* Keep in mind that the available set of models will change over time, but also that prompts may perform differently in
20746
* different models.
20747
*
20748
* *Note* that extensions can hold on to the results returned by this function and use them later. However, when the
20749
* {@link onDidChangeChatModels}-event is fired the list of chat models might have changed and extensions should re-query.
20750
*
20751
* @param selector A chat model selector. When omitted all chat models are returned.
20752
* @returns An array of chat models, can be empty!
20753
*/
20754
export function selectChatModels(selector?: LanguageModelChatSelector): Thenable<LanguageModelChat[]>;
20755
20756
/**
20757
* Register a LanguageModelTool. The tool must also be registered in the package.json `languageModelTools` contribution
20758
* point. A registered tool is available in the {@link lm.tools} list for any extension to see. But in order for it to
20759
* be seen by a language model, it must be passed in the list of available tools in {@link LanguageModelChatRequestOptions.tools}.
20760
* @returns A {@link Disposable} that unregisters the tool when disposed.
20761
*/
20762
export function registerTool<T>(name: string, tool: LanguageModelTool<T>): Disposable;
20763
20764
/**
20765
* A list of all available tools that were registered by all extensions using {@link lm.registerTool}. They can be called
20766
* with {@link lm.invokeTool} with input that match their declared `inputSchema`.
20767
*/
20768
export const tools: readonly LanguageModelToolInformation[];
20769
20770
/**
20771
* Invoke a tool listed in {@link lm.tools} by name with the given input. The input will be validated against
20772
* the schema declared by the tool
20773
*
20774
* A tool can be invoked by a chat participant, in the context of handling a chat request, or globally by any extension in
20775
* any custom flow.
20776
*
20777
* In the former case, the caller shall pass the
20778
* {@link LanguageModelToolInvocationOptions.toolInvocationToken toolInvocationToken}, which comes from a
20779
* {@link ChatRequest.toolInvocationToken chat request}. This makes sure the chat UI shows the tool invocation for the
20780
* correct conversation.
20781
*
20782
* A tool {@link LanguageModelToolResult result} is an array of {@link LanguageModelTextPart text-} and
20783
* {@link LanguageModelPromptTsxPart prompt-tsx}-parts. If the tool caller is using `@vscode/prompt-tsx`, it can
20784
* incorporate the response parts into its prompt using a `ToolResult`. If not, the parts can be passed along to the
20785
* {@link LanguageModelChat} via a user message with a {@link LanguageModelToolResultPart}.
20786
*
20787
* If a chat participant wants to preserve tool results for requests across multiple turns, it can store tool results in
20788
* the {@link ChatResult.metadata} returned from the handler and retrieve them on the next turn from
20789
* {@link ChatResponseTurn.result}.
20790
*
20791
* @param name The name of the tool to call.
20792
* @param options The options to use when invoking the tool.
20793
* @param token A cancellation token. See {@link CancellationTokenSource} for how to create one.
20794
* @returns The result of the tool invocation.
20795
*/
20796
export function invokeTool(name: string, options: LanguageModelToolInvocationOptions<object>, token?: CancellationToken): Thenable<LanguageModelToolResult>;
20797
20798
/**
20799
* Registers a provider that publishes Model Context Protocol servers for the editor to
20800
* consume. This allows MCP servers to be dynamically provided to the editor in
20801
* addition to those the user creates in their configuration files.
20802
*
20803
* Before calling this method, extensions must register the `contributes.mcpServerDefinitionProviders`
20804
* extension point with the corresponding {@link id}, for example:
20805
*
20806
* ```js
20807
* "contributes": {
20808
* "mcpServerDefinitionProviders": [
20809
* {
20810
* "id": "cool-cloud-registry.mcp-servers",
20811
* "label": "Cool Cloud Registry",
20812
* }
20813
* ]
20814
* }
20815
* ```
20816
*
20817
* When a new McpServerDefinitionProvider is available, the editor will, by default,
20818
* automatically invoke it to discover new servers and tools when a chat message is
20819
* submitted. To enable this flow, extensions should call
20820
* `registerMcpServerDefinitionProvider` during activation.
20821
*
20822
* @param id The ID of the provider, which is unique to the extension.
20823
* @param provider The provider to register
20824
* @returns A disposable that unregisters the provider when disposed.
20825
*/
20826
export function registerMcpServerDefinitionProvider(id: string, provider: McpServerDefinitionProvider): Disposable;
20827
20828
/**
20829
* Registers a {@linkcode LanguageModelChatProvider}
20830
* Note: You must also define the language model chat provider via the `languageModelChatProviders` contribution point in package.json
20831
* @param vendor The vendor for this provider. Must be globally unique. An example is `copilot` or `openai`.
20832
* @param provider The provider to register
20833
* @returns A disposable that unregisters the provider when disposed
20834
*/
20835
export function registerLanguageModelChatProvider(vendor: string, provider: LanguageModelChatProvider): Disposable;
20836
}
20837
20838
/**
20839
* Represents extension specific information about the access to language models.
20840
*/
20841
export interface LanguageModelAccessInformation {
20842
20843
/**
20844
* An event that fires when access information changes.
20845
*/
20846
readonly onDidChange: Event<void>;
20847
20848
/**
20849
* Checks if a request can be made to a language model.
20850
*
20851
* *Note* that calling this function will not trigger a consent UI but just checks for a persisted state.
20852
*
20853
* @param chat A language model chat object.
20854
* @return `true` if a request can be made, `false` if not, `undefined` if the language
20855
* model does not exist or consent hasn't been asked for.
20856
*/
20857
canSendRequest(chat: LanguageModelChat): boolean | undefined;
20858
}
20859
20860
/**
20861
* A tool that is available to the language model via {@link LanguageModelChatRequestOptions}. A language model uses all the
20862
* properties of this interface to decide which tool to call, and how to call it.
20863
*/
20864
export interface LanguageModelChatTool {
20865
/**
20866
* The name of the tool.
20867
*/
20868
name: string;
20869
20870
/**
20871
* The description of the tool.
20872
*/
20873
description: string;
20874
20875
/**
20876
* A JSON schema for the input this tool accepts.
20877
*/
20878
inputSchema?: object | undefined;
20879
}
20880
20881
/**
20882
* A tool-calling mode for the language model to use.
20883
*/
20884
export enum LanguageModelChatToolMode {
20885
/**
20886
* The language model can choose to call a tool or generate a message. Is the default.
20887
*/
20888
Auto = 1,
20889
20890
/**
20891
* The language model must call one of the provided tools. Note- some models only support a single tool when using this
20892
* mode.
20893
*/
20894
Required = 2
20895
}
20896
20897
/**
20898
* A language model response part indicating a tool call, returned from a {@link LanguageModelChatResponse}, and also can be
20899
* included as a content part on a {@link LanguageModelChatMessage}, to represent a previous tool call in a chat request.
20900
*/
20901
export class LanguageModelToolCallPart {
20902
/**
20903
* The ID of the tool call. This is a unique identifier for the tool call within the chat request.
20904
*/
20905
callId: string;
20906
20907
/**
20908
* The name of the tool to call.
20909
*/
20910
name: string;
20911
20912
/**
20913
* The input with which to call the tool.
20914
*/
20915
input: object;
20916
20917
/**
20918
* Create a new LanguageModelToolCallPart.
20919
*
20920
* @param callId The ID of the tool call.
20921
* @param name The name of the tool to call.
20922
* @param input The input with which to call the tool.
20923
*/
20924
constructor(callId: string, name: string, input: object);
20925
}
20926
20927
/**
20928
* The result of a tool call. This is the counterpart of a {@link LanguageModelToolCallPart tool call} and
20929
* it can only be included in the content of a User message
20930
*/
20931
export class LanguageModelToolResultPart {
20932
/**
20933
* The ID of the tool call.
20934
*
20935
* *Note* that this should match the {@link LanguageModelToolCallPart.callId callId} of a tool call part.
20936
*/
20937
callId: string;
20938
20939
/**
20940
* The value of the tool result.
20941
*/
20942
content: Array<LanguageModelTextPart | LanguageModelPromptTsxPart | LanguageModelDataPart | unknown>;
20943
20944
/**
20945
* @param callId The ID of the tool call.
20946
* @param content The content of the tool result.
20947
*/
20948
constructor(callId: string, content: Array<LanguageModelTextPart | LanguageModelPromptTsxPart | LanguageModelDataPart | unknown>);
20949
}
20950
20951
/**
20952
* A language model response part containing a piece of text, returned from a {@link LanguageModelChatResponse}.
20953
*/
20954
export class LanguageModelTextPart {
20955
/**
20956
* The text content of the part.
20957
*/
20958
value: string;
20959
20960
/**
20961
* Construct a text part with the given content.
20962
* @param value The text content of the part.
20963
*/
20964
constructor(value: string);
20965
}
20966
20967
/**
20968
* A language model response part containing a PromptElementJSON from `@vscode/prompt-tsx`.
20969
* @see {@link LanguageModelToolResult}
20970
*/
20971
export class LanguageModelPromptTsxPart {
20972
/**
20973
* The value of the part.
20974
*/
20975
value: unknown;
20976
20977
/**
20978
* Construct a prompt-tsx part with the given content.
20979
* @param value The value of the part, the result of `renderElementJSON` from `@vscode/prompt-tsx`.
20980
*/
20981
constructor(value: unknown);
20982
}
20983
20984
/**
20985
* A result returned from a tool invocation. If using `@vscode/prompt-tsx`, this result may be rendered using a `ToolResult`.
20986
*/
20987
export class LanguageModelToolResult {
20988
/**
20989
* A list of tool result content parts. Includes `unknown` because this list may be extended with new content types in
20990
* the future.
20991
* @see {@link lm.invokeTool}.
20992
*/
20993
content: Array<LanguageModelTextPart | LanguageModelPromptTsxPart | LanguageModelDataPart | unknown>;
20994
20995
/**
20996
* Create a LanguageModelToolResult
20997
* @param content A list of tool result content parts
20998
*/
20999
constructor(content: Array<LanguageModelTextPart | LanguageModelPromptTsxPart | LanguageModelDataPart | unknown>);
21000
}
21001
21002
/**
21003
* A language model response part containing arbitrary data. Can be used in {@link LanguageModelChatResponse responses},
21004
* {@link LanguageModelChatMessage chat messages}, {@link LanguageModelToolResult tool results}, and other language model interactions.
21005
*/
21006
export class LanguageModelDataPart {
21007
/**
21008
* Create a new {@linkcode LanguageModelDataPart} for an image.
21009
* @param data Binary image data
21010
* @param mime The MIME type of the image. Common values are `image/png` and `image/jpeg`.
21011
*/
21012
static image(data: Uint8Array, mime: string): LanguageModelDataPart;
21013
21014
/**
21015
* Create a new {@linkcode LanguageModelDataPart} for a json.
21016
*
21017
* *Note* that this function is not expecting "stringified JSON" but
21018
* an object that can be stringified. This function will throw an error
21019
* when the passed value cannot be JSON-stringified.
21020
* @param value A JSON-stringifyable value.
21021
* @param mime Optional MIME type, defaults to `application/json`
21022
*/
21023
static json(value: any, mime?: string): LanguageModelDataPart;
21024
21025
/**
21026
* Create a new {@linkcode LanguageModelDataPart} for text.
21027
*
21028
* *Note* that an UTF-8 encoder is used to create bytes for the string.
21029
* @param value Text data
21030
* @param mime The MIME type if any. Common values are `text/plain` and `text/markdown`.
21031
*/
21032
static text(value: string, mime?: string): LanguageModelDataPart;
21033
21034
/**
21035
* The mime type which determines how the data property is interpreted.
21036
*/
21037
mimeType: string;
21038
21039
/**
21040
* The byte data for this part.
21041
*/
21042
data: Uint8Array;
21043
21044
/**
21045
* Construct a generic data part with the given content.
21046
* @param data The byte data for this part.
21047
* @param mimeType The mime type of the data.
21048
*/
21049
constructor(data: Uint8Array, mimeType: string);
21050
}
21051
21052
/**
21053
* A token that can be passed to {@link lm.invokeTool} when invoking a tool inside the context of handling a chat request.
21054
*/
21055
export type ChatParticipantToolToken = never;
21056
21057
/**
21058
* Options provided for tool invocation.
21059
*/
21060
export interface LanguageModelToolInvocationOptions<T> {
21061
/**
21062
* An opaque object that ties a tool invocation to a chat request from a {@link ChatParticipant chat participant}.
21063
*
21064
* The _only_ way to get a valid tool invocation token is using the provided {@link ChatRequest.toolInvocationToken toolInvocationToken}
21065
* from a chat request. In that case, a progress bar will be automatically shown for the tool invocation in the chat response view, and if
21066
* the tool requires user confirmation, it will show up inline in the chat view.
21067
*
21068
* If the tool is being invoked outside of a chat request, `undefined` should be passed instead, and no special UI except for
21069
* confirmations will be shown.
21070
*
21071
* *Note* that a tool that invokes another tool during its invocation, can pass along the `toolInvocationToken` that it received.
21072
*/
21073
toolInvocationToken: ChatParticipantToolToken | undefined;
21074
21075
/**
21076
* The input with which to invoke the tool. The input must match the schema defined in
21077
* {@link LanguageModelToolInformation.inputSchema}
21078
*/
21079
input: T;
21080
21081
/**
21082
* Options to hint at how many tokens the tool should return in its response, and enable the tool to count tokens
21083
* accurately.
21084
*/
21085
tokenizationOptions?: LanguageModelToolTokenizationOptions;
21086
}
21087
21088
/**
21089
* Options related to tokenization for a tool invocation.
21090
*/
21091
export interface LanguageModelToolTokenizationOptions {
21092
/**
21093
* If known, the maximum number of tokens the tool should emit in its result.
21094
*/
21095
tokenBudget: number;
21096
21097
/**
21098
* Count the number of tokens in a message using the model specific tokenizer-logic.
21099
* @param text A string.
21100
* @param token Optional cancellation token. See {@link CancellationTokenSource} for how to create one.
21101
* @returns A thenable that resolves to the number of tokens.
21102
*/
21103
countTokens(text: string, token?: CancellationToken): Thenable<number>;
21104
}
21105
21106
/**
21107
* Information about a registered tool available in {@link lm.tools}.
21108
*/
21109
export interface LanguageModelToolInformation {
21110
/**
21111
* A unique name for the tool.
21112
*/
21113
readonly name: string;
21114
21115
/**
21116
* A description of this tool that may be passed to a language model.
21117
*/
21118
readonly description: string;
21119
21120
/**
21121
* A JSON schema for the input this tool accepts.
21122
*/
21123
readonly inputSchema: object | undefined;
21124
21125
/**
21126
* A set of tags, declared by the tool, that roughly describe the tool's capabilities. A tool user may use these to filter
21127
* the set of tools to just ones that are relevant for the task at hand.
21128
*/
21129
readonly tags: readonly string[];
21130
}
21131
21132
/**
21133
* Options for {@link LanguageModelTool.prepareInvocation}.
21134
*/
21135
export interface LanguageModelToolInvocationPrepareOptions<T> {
21136
/**
21137
* The input that the tool is being invoked with.
21138
*/
21139
input: T;
21140
}
21141
21142
/**
21143
* A tool that can be invoked by a call to a {@link LanguageModelChat}.
21144
*/
21145
export interface LanguageModelTool<T> {
21146
/**
21147
* Invoke the tool with the given input and return a result.
21148
*
21149
* The provided {@link LanguageModelToolInvocationOptions.input} has been validated against the declared schema.
21150
*/
21151
invoke(options: LanguageModelToolInvocationOptions<T>, token: CancellationToken): ProviderResult<LanguageModelToolResult>;
21152
21153
/**
21154
* Called once before a tool is invoked. It's recommended to implement this to customize the progress message that appears
21155
* while the tool is running, and to provide a more useful message with context from the invocation input. Can also
21156
* signal that a tool needs user confirmation before running, if appropriate.
21157
*
21158
* * *Note 1:* Must be free of side-effects.
21159
* * *Note 2:* A call to `prepareInvocation` is not necessarily followed by a call to `invoke`.
21160
*/
21161
prepareInvocation?(options: LanguageModelToolInvocationPrepareOptions<T>, token: CancellationToken): ProviderResult<PreparedToolInvocation>;
21162
}
21163
21164
/**
21165
* When this is returned in {@link PreparedToolInvocation}, the user will be asked to confirm before running the tool. These
21166
* messages will be shown with buttons that say "Continue" and "Cancel".
21167
*/
21168
export interface LanguageModelToolConfirmationMessages {
21169
/**
21170
* The title of the confirmation message.
21171
*/
21172
title: string;
21173
21174
/**
21175
* The body of the confirmation message.
21176
*/
21177
message: string | MarkdownString;
21178
}
21179
21180
/**
21181
* The result of a call to {@link LanguageModelTool.prepareInvocation}.
21182
*/
21183
export interface PreparedToolInvocation {
21184
/**
21185
* A customized progress message to show while the tool runs.
21186
*/
21187
invocationMessage?: string | MarkdownString;
21188
21189
/**
21190
* The presence of this property indicates that the user should be asked to confirm before running the tool. The user
21191
* should be asked for confirmation for any tool that has a side-effect or may potentially be dangerous.
21192
*/
21193
confirmationMessages?: LanguageModelToolConfirmationMessages;
21194
}
21195
21196
/**
21197
* A reference to a tool that the user manually attached to their request, either using the `#`-syntax inline, or as an
21198
* attachment via the paperclip button.
21199
*/
21200
export interface ChatLanguageModelToolReference {
21201
/**
21202
* The tool name. Refers to a tool listed in {@link lm.tools}.
21203
*/
21204
readonly name: string;
21205
21206
/**
21207
* The start and end index of the reference in the {@link ChatRequest.prompt prompt}. When undefined, the reference was
21208
* not part of the prompt text.
21209
*
21210
* *Note* that the indices take the leading `#`-character into account which means they can be used to modify the prompt
21211
* as-is.
21212
*/
21213
readonly range?: [start: number, end: number];
21214
}
21215
}
21216
21217
/**
21218
* Thenable is a common denominator between ES6 promises, Q, jquery.Deferred, WinJS.Promise,
21219
* and others. This API makes no assumption about what promise library is being used which
21220
* enables reusing existing code without migrating to a specific promise implementation. Still,
21221
* we recommend the use of native promises which are available in this editor.
21222
*/
21223
interface Thenable<T> extends PromiseLike<T> { }
21224
21225