-
Notifications
You must be signed in to change notification settings - Fork 328
/
client.ts
3041 lines (2680 loc) · 112 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
import {
workspace as Workspace, window as Window, languages as Languages, commands as Commands,
TextDocumentChangeEvent, TextDocument, Disposable, OutputChannel,
FileSystemWatcher as VFileSystemWatcher, DiagnosticCollection, Diagnostic as VDiagnostic, Uri, ProviderResult,
CancellationToken, Position as VPosition, Location as VLocation, Range as VRange,
CompletionItem as VCompletionItem, CompletionList as VCompletionList, SignatureHelp as VSignatureHelp, Definition as VDefinition, DocumentHighlight as VDocumentHighlight,
SymbolInformation as VSymbolInformation, CodeActionContext as VCodeActionContext, Command as VCommand, CodeLens as VCodeLens,
FormattingOptions as VFormattingOptions, TextEdit as VTextEdit, WorkspaceEdit as VWorkspaceEdit, MessageItem,
Hover as VHover, CodeAction as VCodeAction, DocumentSymbol as VDocumentSymbol,
DocumentLink as VDocumentLink, TextDocumentWillSaveEvent,
WorkspaceFolder as VWorkspaceFolder, CompletionContext as VCompletionContext, ConfigurationChangeEvent
} from 'vscode';
import {
Message, RPCMessageType, Logger, ErrorCodes, ResponseError,
RequestType, RequestType0, RequestHandler, RequestHandler0, GenericRequestHandler,
NotificationType, NotificationType0,
NotificationHandler, NotificationHandler0, GenericNotificationHandler,
MessageReader, MessageWriter, Trace, Tracer, Event, Emitter,
createProtocolConnection,
ClientCapabilities, WorkspaceEdit,
RegistrationRequest, RegistrationParams, UnregistrationRequest, UnregistrationParams, TextDocumentRegistrationOptions,
InitializeRequest, InitializeParams, InitializeResult, InitializeError, ServerCapabilities, TextDocumentSyncKind, TextDocumentSyncOptions,
InitializedNotification, ShutdownRequest, ExitNotification,
LogMessageNotification, LogMessageParams, MessageType,
ShowMessageNotification, ShowMessageParams, ShowMessageRequest,
TelemetryEventNotification,
DidChangeConfigurationNotification, DidChangeConfigurationParams, DidChangeConfigurationRegistrationOptions,
DocumentSelector,
DidOpenTextDocumentNotification, DidOpenTextDocumentParams,
DidChangeTextDocumentNotification, DidChangeTextDocumentParams, TextDocumentChangeRegistrationOptions,
DidCloseTextDocumentNotification, DidCloseTextDocumentParams,
DidSaveTextDocumentNotification, DidSaveTextDocumentParams, TextDocumentSaveRegistrationOptions,
WillSaveTextDocumentNotification, WillSaveTextDocumentWaitUntilRequest, WillSaveTextDocumentParams,
DidChangeWatchedFilesNotification, DidChangeWatchedFilesParams, FileEvent, FileChangeType,
DidChangeWatchedFilesRegistrationOptions, WatchKind,
PublishDiagnosticsNotification, PublishDiagnosticsParams,
CompletionRequest, CompletionResolveRequest, CompletionRegistrationOptions,
HoverRequest,
SignatureHelpRequest, SignatureHelpRegistrationOptions, DefinitionRequest, ReferencesRequest, DocumentHighlightRequest,
DocumentSymbolRequest, WorkspaceSymbolRequest,
CodeActionRequest, CodeActionParams,
CodeLensRequest, CodeLensResolveRequest, CodeLensRegistrationOptions,
DocumentFormattingRequest, DocumentFormattingParams, DocumentRangeFormattingRequest, DocumentRangeFormattingParams,
DocumentOnTypeFormattingRequest, DocumentOnTypeFormattingParams, DocumentOnTypeFormattingRegistrationOptions,
RenameRequest, RenameParams,
DocumentLinkRequest, DocumentLinkResolveRequest, DocumentLinkRegistrationOptions,
ExecuteCommandRequest, ExecuteCommandParams, ExecuteCommandRegistrationOptions,
ApplyWorkspaceEditRequest, ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse,
MarkupKind, SymbolKind, CompletionItemKind, Command, CodeActionKind, DocumentSymbol, SymbolInformation
} from 'vscode-languageserver-protocol';
import { ColorProviderMiddleware } from './colorProvider';
import { ImplementationMiddleware } from './implementation'
import { TypeDefinitionMiddleware } from './typeDefinition';
import { ConfigurationWorkspaceMiddleware } from './configuration';
import { WorkspaceFolderWorkspaceMiddleware } from './workspaceFolders';
import { FoldingRangeProviderMiddleware } from './foldingRange';
import * as c2p from './codeConverter';
import * as p2c from './protocolConverter';
import * as Is from './utils/is';
import { Delayer } from './utils/async'
import * as UUID from './utils/uuid';
export { Converter as Code2ProtocolConverter } from './codeConverter';
export { Converter as Protocol2CodeConverter } from './protocolConverter';
export * from 'vscode-languageserver-protocol';
interface IConnection {
listen(): void;
sendRequest<R, E, RO>(type: RequestType0<R, E, RO>, token?: CancellationToken): Thenable<R>;
sendRequest<P, R, E, RO>(type: RequestType<P, R, E, RO>, params: P, token?: CancellationToken): Thenable<R>;
sendRequest<R>(method: string, token?: CancellationToken): Thenable<R>;
sendRequest<R>(method: string, param: any, token?: CancellationToken): Thenable<R>;
sendRequest<R>(type: string | RPCMessageType, ...params: any[]): Thenable<R>;
onRequest<R, E, RO>(type: RequestType0<R, E, RO>, handler: RequestHandler0<R, E>): void;
onRequest<P, R, E, RO>(type: RequestType<P, R, E, RO>, handler: RequestHandler<P, R, E>): void;
onRequest<R, E>(method: string, handler: GenericRequestHandler<R, E>): void;
onRequest<R, E>(method: string | RPCMessageType, handler: GenericRequestHandler<R, E>): void;
sendNotification<RO>(type: NotificationType0<RO>): void;
sendNotification<P, RO>(type: NotificationType<P, RO>, params?: P): void;
sendNotification(method: string): void;
sendNotification(method: string, params: any): void;
sendNotification(method: string | RPCMessageType, params?: any): void;
onNotification<RO>(type: NotificationType0<RO>, handler: NotificationHandler0): void;
onNotification<P, RO>(type: NotificationType<P, RO>, handler: NotificationHandler<P>): void;
onNotification(method: string, handler: GenericNotificationHandler): void;
onNotification(method: string | RPCMessageType, handler: GenericNotificationHandler): void;
trace(value: Trace, tracer: Tracer, sendNotification?: boolean): void;
initialize(params: InitializeParams): Thenable<InitializeResult>;
shutdown(): Thenable<void>;
exit(): void;
onLogMessage(handle: NotificationHandler<LogMessageParams>): void;
onShowMessage(handler: NotificationHandler<ShowMessageParams>): void;
onTelemetry(handler: NotificationHandler<any>): void;
didChangeConfiguration(params: DidChangeConfigurationParams): void;
didChangeWatchedFiles(params: DidChangeWatchedFilesParams): void;
didOpenTextDocument(params: DidOpenTextDocumentParams): void;
didChangeTextDocument(params: DidChangeTextDocumentParams): void;
didCloseTextDocument(params: DidCloseTextDocumentParams): void;
didSaveTextDocument(params: DidSaveTextDocumentParams): void;
onDiagnostics(handler: NotificationHandler<PublishDiagnosticsParams>): void;
dispose(): void;
}
class ConsoleLogger implements Logger {
public error(message: string): void {
console.error(message);
}
public warn(message: string): void {
console.warn(message);
}
public info(message: string): void {
console.info(message);
}
public log(message: string): void {
console.log(message);
}
}
interface ConnectionErrorHandler {
(error: Error, message: Message | undefined, count: number | undefined): void;
}
interface ConnectionCloseHandler {
(): void;
}
function createConnection(inputStream: NodeJS.ReadableStream, outputStream: NodeJS.WritableStream, errorHandler: ConnectionErrorHandler, closeHandler: ConnectionCloseHandler): IConnection;
function createConnection(reader: MessageReader, writer: MessageWriter, errorHandler: ConnectionErrorHandler, closeHandler: ConnectionCloseHandler): IConnection;
function createConnection(input: any, output: any, errorHandler: ConnectionErrorHandler, closeHandler: ConnectionCloseHandler): IConnection {
let logger = new ConsoleLogger();
let connection = createProtocolConnection(input, output, logger);
connection.onError((data) => { errorHandler(data[0], data[1], data[2]) });
connection.onClose(closeHandler);
let result: IConnection = {
listen: (): void => connection.listen(),
sendRequest: <R>(type: string | RPCMessageType, ...params: any[]): Thenable<R> => connection.sendRequest(Is.string(type) ? type : type.method, ...params),
onRequest: <R, E>(type: string | RPCMessageType, handler: GenericRequestHandler<R, E>): void => connection.onRequest(Is.string(type) ? type : type.method, handler),
sendNotification: (type: string | RPCMessageType, params?: any): void => connection.sendNotification(Is.string(type) ? type : type.method, params),
onNotification: (type: string | RPCMessageType, handler: GenericNotificationHandler): void => connection.onNotification(Is.string(type) ? type : type.method, handler),
trace: (value: Trace, tracer: Tracer, sendNotification: boolean = false): void => connection.trace(value, tracer, sendNotification),
initialize: (params: InitializeParams) => connection.sendRequest(InitializeRequest.type, params),
shutdown: () => connection.sendRequest(ShutdownRequest.type, undefined),
exit: () => connection.sendNotification(ExitNotification.type),
onLogMessage: (handler: NotificationHandler<LogMessageParams>) => connection.onNotification(LogMessageNotification.type, handler),
onShowMessage: (handler: NotificationHandler<ShowMessageParams>) => connection.onNotification(ShowMessageNotification.type, handler),
onTelemetry: (handler: NotificationHandler<any>) => connection.onNotification(TelemetryEventNotification.type, handler),
didChangeConfiguration: (params: DidChangeConfigurationParams) => connection.sendNotification(DidChangeConfigurationNotification.type, params),
didChangeWatchedFiles: (params: DidChangeWatchedFilesParams) => connection.sendNotification(DidChangeWatchedFilesNotification.type, params),
didOpenTextDocument: (params: DidOpenTextDocumentParams) => connection.sendNotification(DidOpenTextDocumentNotification.type, params),
didChangeTextDocument: (params: DidChangeTextDocumentParams) => connection.sendNotification(DidChangeTextDocumentNotification.type, params),
didCloseTextDocument: (params: DidCloseTextDocumentParams) => connection.sendNotification(DidCloseTextDocumentNotification.type, params),
didSaveTextDocument: (params: DidSaveTextDocumentParams) => connection.sendNotification(DidSaveTextDocumentNotification.type, params),
onDiagnostics: (handler: NotificationHandler<PublishDiagnosticsParams>) => connection.onNotification(PublishDiagnosticsNotification.type, handler),
dispose: () => connection.dispose()
}
return result;
}
/**
* An action to be performed when the connection is producing errors.
*/
export enum ErrorAction {
/**
* Continue running the server.
*/
Continue = 1,
/**
* Shutdown the server.
*/
Shutdown = 2
}
/**
* An action to be performed when the connection to a server got closed.
*/
export enum CloseAction {
/**
* Don't restart the server. The connection stays closed.
*/
DoNotRestart = 1,
/**
* Restart the server.
*/
Restart = 2,
}
/**
* A pluggable error handler that is invoked when the connection is either
* producing errors or got closed.
*/
export interface ErrorHandler {
/**
* An error has occurred while writing or reading from the connection.
*
* @param error - the error received
* @param message - the message to be delivered to the server if know.
* @param count - a count indicating how often an error is received. Will
* be reset if a message got successfully send or received.
*/
error(error: Error, message: Message, count: number): ErrorAction;
/**
* The connection to the server got closed.
*/
closed(): CloseAction
}
class DefaultErrorHandler implements ErrorHandler {
private restarts: number[];
constructor(private name: string) {
this.restarts = [];
}
public error(_error: Error, _message: Message, count: number): ErrorAction {
if (count && count <= 3) {
return ErrorAction.Continue;
}
return ErrorAction.Shutdown;
}
public closed(): CloseAction {
this.restarts.push(Date.now());
if (this.restarts.length < 5) {
return CloseAction.Restart;
} else {
let diff = this.restarts[this.restarts.length - 1] - this.restarts[0];
if (diff <= 3 * 60 * 1000) {
Window.showErrorMessage(`The ${this.name} server crashed 5 times in the last 3 minutes. The server will not be restarted.`);
return CloseAction.DoNotRestart;
} else {
this.restarts.shift();
return CloseAction.Restart;
}
}
}
}
export interface InitializationFailedHandler {
(error: ResponseError<InitializeError> | Error | any): boolean;
}
export interface SynchronizeOptions {
configurationSection?: string | string[];
fileEvents?: VFileSystemWatcher | VFileSystemWatcher[];
}
export enum RevealOutputChannelOn {
Info = 1,
Warn = 2,
Error = 3,
Never = 4
}
export interface HandleDiagnosticsSignature {
(uri: Uri, diagnostics: VDiagnostic[]): void;
}
export interface ProvideCompletionItemsSignature {
(document: TextDocument, position: VPosition, context: VCompletionContext, token: CancellationToken): ProviderResult<VCompletionItem[] | VCompletionList>;
}
export interface ResolveCompletionItemSignature {
(item: VCompletionItem, token: CancellationToken): ProviderResult<VCompletionItem>;
}
export interface ProvideHoverSignature {
(document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VHover>;
}
export interface ProvideSignatureHelpSignature {
(document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VSignatureHelp>;
}
export interface ProvideDefinitionSignature {
(document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VDefinition>;
}
export interface ProvideReferencesSignature {
(document: TextDocument, position: VPosition, options: { includeDeclaration: boolean; }, token: CancellationToken): ProviderResult<VLocation[]>;
}
export interface ProvideDocumentHighlightsSignature {
(document: TextDocument, position: VPosition, token: CancellationToken): ProviderResult<VDocumentHighlight[]>;
}
export interface ProvideDocumentSymbolsSignature {
(document: TextDocument, token: CancellationToken): ProviderResult<VSymbolInformation[] | VDocumentSymbol[]>;
}
export interface ProvideWorkspaceSymbolsSignature {
(query: string, token: CancellationToken): ProviderResult<VSymbolInformation[]>;
}
export interface ProvideCodeActionsSignature {
(document: TextDocument, range: VRange, context: VCodeActionContext, token: CancellationToken): ProviderResult<(VCommand | VCodeAction)[]>;
}
export interface ProvideCodeLensesSignature {
(document: TextDocument, token: CancellationToken): ProviderResult<VCodeLens[]>;
}
export interface ResolveCodeLensSignature {
(codeLens: VCodeLens, token: CancellationToken): ProviderResult<VCodeLens>;
}
export interface ProvideDocumentFormattingEditsSignature {
(document: TextDocument, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface ProvideDocumentRangeFormattingEditsSignature {
(document: TextDocument, range: VRange, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface ProvideOnTypeFormattingEditsSignature {
(document: TextDocument, position: VPosition, ch: string, options: VFormattingOptions, token: CancellationToken): ProviderResult<VTextEdit[]>;
}
export interface ProvideRenameEditsSignature {
(document: TextDocument, position: VPosition, newName: string, token: CancellationToken): ProviderResult<VWorkspaceEdit>;
}
export interface ProvideDocumentLinksSignature {
(document: TextDocument, token: CancellationToken): ProviderResult<VDocumentLink[]>;
}
export interface ResolveDocumentLinkSignature {
(link: VDocumentLink, token: CancellationToken): ProviderResult<VDocumentLink>;
}
export interface NextSignature<P, R> {
(this: void, data: P, next: (data: P) => R): R;
}
export interface DidChangeConfigurationSignature {
(sections: string[] | undefined): void;
}
export interface _WorkspaceMiddleware {
didChangeConfiguration?: (this: void, sections: string[] | undefined, next: DidChangeConfigurationSignature) => void;
}
export type WorkspaceMiddleware = _WorkspaceMiddleware & ConfigurationWorkspaceMiddleware & WorkspaceFolderWorkspaceMiddleware;
/**
* The Middleware lets extensions intercept the request and notications send and received
* from the server
*/
export interface _Middleware {
didOpen?: NextSignature<TextDocument, void>;
didChange?: NextSignature<TextDocumentChangeEvent, void>;
willSave?: NextSignature<TextDocumentWillSaveEvent, void>;
willSaveWaitUntil?: NextSignature<TextDocumentWillSaveEvent, Thenable<VTextEdit[]>>;
didSave?: NextSignature<TextDocument, void>;
didClose?: NextSignature<TextDocument, void>;
handleDiagnostics?: (this: void, uri: Uri, diagnostics: VDiagnostic[], next: HandleDiagnosticsSignature) => void;
provideCompletionItem?: (this: void, document: TextDocument, position: VPosition, context: VCompletionContext, token: CancellationToken, next: ProvideCompletionItemsSignature) => ProviderResult<VCompletionItem[] | VCompletionList>;
resolveCompletionItem?: (this: void, item: VCompletionItem, token: CancellationToken, next: ResolveCompletionItemSignature) => ProviderResult<VCompletionItem>;
provideHover?: (this: void, document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideHoverSignature) => ProviderResult<VHover>;
provideSignatureHelp?: (this: void, document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideSignatureHelpSignature) => ProviderResult<VSignatureHelp>;
provideDefinition?: (this: void, document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideDefinitionSignature) => ProviderResult<VDefinition>;
provideReferences?: (this: void, document: TextDocument, position: VPosition, options: { includeDeclaration: boolean; }, token: CancellationToken, next: ProvideReferencesSignature) => ProviderResult<VLocation[]>;
provideDocumentHighlights?: (this: void, document: TextDocument, position: VPosition, token: CancellationToken, next: ProvideDocumentHighlightsSignature) => ProviderResult<VDocumentHighlight[]>;
provideDocumentSymbols?: (this: void, document: TextDocument, token: CancellationToken, next: ProvideDocumentSymbolsSignature) => ProviderResult<VSymbolInformation[] | VDocumentSymbol[]>;
provideWorkspaceSymbols?: (this: void, query: string, token: CancellationToken, next: ProvideWorkspaceSymbolsSignature) => ProviderResult<VSymbolInformation[]>;
provideCodeActions?: (this: void, document: TextDocument, range: VRange, context: VCodeActionContext, token: CancellationToken, next: ProvideCodeActionsSignature) => ProviderResult<(VCommand | VCodeAction)[]>;
provideCodeLenses?: (this: void, document: TextDocument, token: CancellationToken, next: ProvideCodeLensesSignature) => ProviderResult<VCodeLens[]>;
resolveCodeLens?: (this: void, codeLens: VCodeLens, token: CancellationToken, next: ResolveCodeLensSignature) => ProviderResult<VCodeLens>;
provideDocumentFormattingEdits?: (this: void, document: TextDocument, options: VFormattingOptions, token: CancellationToken, next: ProvideDocumentFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
provideDocumentRangeFormattingEdits?: (this: void, document: TextDocument, range: VRange, options: VFormattingOptions, token: CancellationToken, next: ProvideDocumentRangeFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
provideOnTypeFormattingEdits?: (this: void, document: TextDocument, position: VPosition, ch: string, options: VFormattingOptions, token: CancellationToken, next: ProvideOnTypeFormattingEditsSignature) => ProviderResult<VTextEdit[]>;
provideRenameEdits?: (this: void, document: TextDocument, position: VPosition, newName: string, token: CancellationToken, next: ProvideRenameEditsSignature) => ProviderResult<VWorkspaceEdit>;
provideDocumentLinks?: (this: void, document: TextDocument, token: CancellationToken, next: ProvideDocumentLinksSignature) => ProviderResult<VDocumentLink[]>;
resolveDocumentLink?: (this: void, link: VDocumentLink, token: CancellationToken, next: ResolveDocumentLinkSignature) => ProviderResult<VDocumentLink>;
workspace?: WorkspaceMiddleware;
}
export type Middleware = _Middleware & TypeDefinitionMiddleware & ImplementationMiddleware & ColorProviderMiddleware & FoldingRangeProviderMiddleware;
export interface LanguageClientOptions {
documentSelector?: DocumentSelector | string[];
synchronize?: SynchronizeOptions;
diagnosticCollectionName?: string;
outputChannel?: OutputChannel;
outputChannelName?: string;
revealOutputChannelOn?: RevealOutputChannelOn;
/**
* The encoding use to read stdout and stderr. Defaults
* to 'utf8' if ommitted.
*/
stdioEncoding?: string;
initializationOptions?: any | (() => any);
initializationFailedHandler?: InitializationFailedHandler;
errorHandler?: ErrorHandler;
middleware?: Middleware;
uriConverters?: {
code2Protocol: c2p.URIConverter,
protocol2Code: p2c.URIConverter
};
workspaceFolder?: VWorkspaceFolder;
}
interface ResolvedClientOptions {
documentSelector?: DocumentSelector;
synchronize: SynchronizeOptions;
diagnosticCollectionName?: string;
outputChannelName: string;
revealOutputChannelOn: RevealOutputChannelOn;
stdioEncoding: string;
initializationOptions?: any | (() => any);
initializationFailedHandler?: InitializationFailedHandler;
errorHandler: ErrorHandler;
middleware: Middleware;
uriConverters?: {
code2Protocol: c2p.URIConverter,
protocol2Code: p2c.URIConverter
};
workspaceFolder?: VWorkspaceFolder
}
export enum State {
Stopped = 1,
Running = 2
}
export interface StateChangeEvent {
oldState: State;
newState: State;
}
enum ClientState {
Initial,
Starting,
StartFailed,
Running,
Stopping,
Stopped
}
const SupporedSymbolKinds: SymbolKind[] = [
SymbolKind.File,
SymbolKind.Module,
SymbolKind.Namespace,
SymbolKind.Package,
SymbolKind.Class,
SymbolKind.Method,
SymbolKind.Property,
SymbolKind.Field,
SymbolKind.Constructor,
SymbolKind.Enum,
SymbolKind.Interface,
SymbolKind.Function,
SymbolKind.Variable,
SymbolKind.Constant,
SymbolKind.String,
SymbolKind.Number,
SymbolKind.Boolean,
SymbolKind.Array,
SymbolKind.Object,
SymbolKind.Key,
SymbolKind.Null,
SymbolKind.EnumMember,
SymbolKind.Struct,
SymbolKind.Event,
SymbolKind.Operator,
SymbolKind.TypeParameter
];
const SupportedCompletionItemKinds: CompletionItemKind[] = [
CompletionItemKind.Text,
CompletionItemKind.Method,
CompletionItemKind.Function,
CompletionItemKind.Constructor,
CompletionItemKind.Field,
CompletionItemKind.Variable,
CompletionItemKind.Class,
CompletionItemKind.Interface,
CompletionItemKind.Module,
CompletionItemKind.Property,
CompletionItemKind.Unit,
CompletionItemKind.Value,
CompletionItemKind.Enum,
CompletionItemKind.Keyword,
CompletionItemKind.Snippet,
CompletionItemKind.Color,
CompletionItemKind.File,
CompletionItemKind.Reference,
CompletionItemKind.Folder,
CompletionItemKind.EnumMember,
CompletionItemKind.Constant,
CompletionItemKind.Struct,
CompletionItemKind.Event,
CompletionItemKind.Operator,
CompletionItemKind.TypeParameter
];
function ensure<T, K extends keyof T>(target: T, key: K): T[K] {
if (target[key] === void 0) {
target[key] = {} as any;
}
return target[key];
}
interface ResolvedTextDocumentSyncCapabilities {
resolvedTextDocumentSync?: TextDocumentSyncOptions;
}
export interface RegistrationData<T> {
id: string;
registerOptions: T;
}
/**
* A static feature. A static feature can't be dynamically activate via the
* server. It is wired during the initialize sequence.
*/
export interface StaticFeature {
/**
* Called to fill the initialize params.
*
* @params the initialize params.
*/
fillInitializeParams?: (params: InitializeParams) => void;
/**
* Called to fill in the client capabilities this feature implements.
*
* @param capabilities The client capabilities to fill.
*/
fillClientCapabilities(capabilities: ClientCapabilities): void;
/**
* Initialize the feature. This method is called on a feature instance
* when the client has successfully received the initalize request from
* the server and before the client sends the initialized notification
* to the server.
*
* @param capabilities the server capabilities
* @param documentSelector the document selector pass to the client's constuctor.
* May be `undefined` if the client was created without a selector.
*/
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector | undefined): void;
}
export interface DynamicFeature<T> {
/**
* The message for which this features support dynamic activation / registration.
*/
messages: RPCMessageType | RPCMessageType[];
/**
* Called to fill the initialize params.
*
* @params the initialize params.
*/
fillInitializeParams?: (params: InitializeParams) => void;
/**
* Called to fill in the client capabilities this feature implements.
*
* @param capabilities The client capabilities to fill.
*/
fillClientCapabilities(capabilities: ClientCapabilities): void;
/**
* Initialize the feature. This method is called on a feature instance
* when the client has successfully received the initalize request from
* the server and before the client sends the initialized notification
* to the server.
*
* @param capabilities the server capabilities.
* @param documentSelector the document selector pass to the client's constuctor.
* May be `undefined` if the client was created without a selector.
*/
initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector | undefined): void;
/**
* Is called when the server send a register request for the given message.
*
* @param message the message to register for.
* @param data additional registration data as defined in the protocol.
*/
register(message: RPCMessageType, data: RegistrationData<T>): void;
/**
* Is called when the server wants to unregister a feature.
*
* @param id the id used when registering the feature.
*/
unregister(id: string): void;
/**
* Called when the client is stopped to dispose this feature. Usually a feature
* unregisters listeners registerd hooked up with the VS Code extension host.
*/
dispose(): void;
}
namespace DynamicFeature {
export function is<T>(value: any): value is DynamicFeature<T> {
let candidate: DynamicFeature<T> = value;
return candidate && Is.func(candidate.register) && Is.func(candidate.unregister) && Is.func(candidate.dispose) && candidate.messages !== void 0;
}
}
interface CreateParamsSignature<E, P> {
(data: E): P;
}
abstract class DocumentNotifiactions<P, E> implements DynamicFeature<TextDocumentRegistrationOptions> {
private _listener: Disposable | undefined;
protected _selectors: Map<string, DocumentSelector> = new Map<string, DocumentSelector>();
public static textDocumentFilter(selectors: IterableIterator<DocumentSelector>, textDocument: TextDocument): boolean {
for (const selector of selectors) {
if (Languages.match(selector, textDocument)) {
return true;
}
}
return false;
}
constructor(
protected _client: BaseLanguageClient, private _event: Event<E>,
protected _type: NotificationType<P, TextDocumentRegistrationOptions>,
protected _middleware: NextSignature<E, void> | undefined,
protected _createParams: CreateParamsSignature<E, P>,
protected _selectorFilter?: (selectors: IterableIterator<DocumentSelector>, data: E) => boolean) {
}
public abstract messages: RPCMessageType | RPCMessageType[];
public abstract fillClientCapabilities(capabilities: ClientCapabilities): void;
public abstract initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector | undefined): void;
public register(_message: RPCMessageType, data: RegistrationData<TextDocumentRegistrationOptions>): void {
if (!data.registerOptions.documentSelector) {
return;
}
if (!this._listener) {
this._listener = this._event(this.callback, this);
}
this._selectors.set(data.id, data.registerOptions.documentSelector);
}
private callback(data: E): void {
if (!this._selectorFilter || this._selectorFilter(this._selectors.values(), data)) {
if (this._middleware) {
this._middleware(data, (data) => this._client.sendNotification(this._type, this._createParams(data)));
} else {
this._client.sendNotification(this._type, this._createParams(data));
}
this.notificationSent(data);
}
}
protected notificationSent(_data: E): void {
}
public unregister(id: string): void {
this._selectors.delete(id);
if (this._selectors.size === 0 && this._listener) {
this._listener.dispose();
this._listener = undefined;
}
}
public dispose(): void {
this._selectors.clear();
if (this._listener) {
this._listener.dispose();
}
}
}
class DidOpenTextDocumentFeature extends DocumentNotifiactions<DidOpenTextDocumentParams, TextDocument> {
constructor(client: BaseLanguageClient, private _syncedDocuments: Map<string, TextDocument>) {
super(
client, Workspace.onDidOpenTextDocument, DidOpenTextDocumentNotification.type,
client.clientOptions.middleware!.didOpen,
(textDocument) => client.code2ProtocolConverter.asOpenTextDocumentParams(textDocument),
DocumentNotifiactions.textDocumentFilter
);
}
public get messages(): typeof DidOpenTextDocumentNotification.type {
return DidOpenTextDocumentNotification.type;
}
public fillClientCapabilities(capabilities: ClientCapabilities): void {
ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!.dynamicRegistration = true;
}
public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void {
let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync;
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) {
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } });
}
}
public register(message: RPCMessageType, data: RegistrationData<TextDocumentRegistrationOptions>): void {
super.register(message, data);
if (!data.registerOptions.documentSelector) {
return;
}
let documentSelector = data.registerOptions.documentSelector;
Workspace.textDocuments.forEach((textDocument) => {
let uri: string = textDocument.uri.toString();
if (this._syncedDocuments.has(uri)) {
return;
}
if (Languages.match(documentSelector, textDocument)) {
let middleware = this._client.clientOptions.middleware!;
let didOpen = (textDocument: TextDocument) => {
this._client.sendNotification(this._type, this._createParams(textDocument));
};
if (middleware.didOpen) {
middleware.didOpen(textDocument, didOpen);
} else {
didOpen(textDocument);
}
this._syncedDocuments.set(uri, textDocument);
}
});
}
protected notificationSent(textDocument: TextDocument): void {
super.notificationSent(textDocument);
this._syncedDocuments.set(textDocument.uri.toString(), textDocument);
}
}
class DidCloseTextDocumentFeature extends DocumentNotifiactions<DidCloseTextDocumentParams, TextDocument> {
constructor(client: BaseLanguageClient, private _syncedDocuments: Map<string, TextDocument>) {
super(
client, Workspace.onDidCloseTextDocument, DidCloseTextDocumentNotification.type,
client.clientOptions.middleware!.didClose,
(textDocument) => client.code2ProtocolConverter.asCloseTextDocumentParams(textDocument),
DocumentNotifiactions.textDocumentFilter
);
}
public get messages(): typeof DidCloseTextDocumentNotification.type {
return DidCloseTextDocumentNotification.type;
}
public fillClientCapabilities(capabilities: ClientCapabilities): void {
ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!.dynamicRegistration = true;
}
public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void {
let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync;
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) {
this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } });
}
}
protected notificationSent(textDocument: TextDocument): void {
super.notificationSent(textDocument);
this._syncedDocuments.delete(textDocument.uri.toString());
}
public unregister(id: string): void {
let selector = this._selectors.get(id)!;
// The super call removed the selector from the map
// of selectors.
super.unregister(id);
let selectors = this._selectors.values();
this._syncedDocuments.forEach((textDocument) => {
if (Languages.match(selector, textDocument) && !this._selectorFilter!(selectors, textDocument)) {
let middleware = this._client.clientOptions.middleware!;
let didClose = (textDocument: TextDocument) => {
this._client.sendNotification(this._type, this._createParams(textDocument));
};
this._syncedDocuments.delete(textDocument.uri.toString());
if (middleware.didClose) {
middleware.didClose(textDocument, didClose);
} else {
didClose(textDocument);
}
}
});
}
}
interface DidChangeTextDocumentData {
documentSelector: DocumentSelector;
syncKind: 0 | 1 | 2;
}
class DidChangeTextDocumentFeature implements DynamicFeature<TextDocumentChangeRegistrationOptions> {
private _listener: Disposable | undefined;
private _changeData: Map<string, DidChangeTextDocumentData> = new Map<string, DidChangeTextDocumentData>();
private _forcingDelivery: boolean = false;
private _changeDelayer: { uri: string; delayer: Delayer<void> } | undefined;
constructor(private _client: BaseLanguageClient) {
}
public get messages(): typeof DidChangeTextDocumentNotification.type {
return DidChangeTextDocumentNotification.type;
}
public fillClientCapabilities(capabilities: ClientCapabilities): void {
ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!.dynamicRegistration = true;
}
public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void {
let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync;
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.change !== void 0 && textDocumentSyncOptions.change !== TextDocumentSyncKind.None) {
this.register(this.messages,
{
id: UUID.generateUuid(),
registerOptions: Object.assign({}, { documentSelector: documentSelector }, { syncKind: textDocumentSyncOptions.change })
}
);
}
}
public register(_message: RPCMessageType, data: RegistrationData<TextDocumentChangeRegistrationOptions>): void {
if (!data.registerOptions.documentSelector) {
return;
}
if (!this._listener) {
this._listener = Workspace.onDidChangeTextDocument(this.callback, this);
}
this._changeData.set(
data.id,
{
documentSelector: data.registerOptions.documentSelector,
syncKind: data.registerOptions.syncKind
}
);
}
private callback(event: TextDocumentChangeEvent): void {
// Text document changes are send for dirty changes as well. We don't
// have dirty / undirty events in the LSP so we ignore content changes
// with length zero.
if (event.contentChanges.length === 0) {
return;
}
for (const changeData of this._changeData.values()) {
if (Languages.match(changeData.documentSelector, event.document)) {
let middleware = this._client.clientOptions.middleware!;
if (changeData.syncKind === TextDocumentSyncKind.Incremental) {
let params = this._client.code2ProtocolConverter.asChangeTextDocumentParams(event);
if (middleware.didChange) {
middleware.didChange(event, () => this._client.sendNotification(DidChangeTextDocumentNotification.type, params));
} else {
this._client.sendNotification(DidChangeTextDocumentNotification.type, params);
}
} else if (changeData.syncKind === TextDocumentSyncKind.Full) {
let didChange: (event: TextDocumentChangeEvent) => void = (event) => {
if (this._changeDelayer) {
if (this._changeDelayer.uri !== event.document.uri.toString()) {
// Use this force delivery to track boolean state. Otherwise we might call two times.
this.forceDelivery();
this._changeDelayer.uri = event.document.uri.toString();
}
this._changeDelayer.delayer.trigger(() => {
this._client.sendNotification(DidChangeTextDocumentNotification.type, this._client.code2ProtocolConverter.asChangeTextDocumentParams(event.document));
});
} else {
this._changeDelayer = {
uri: event.document.uri.toString(),
delayer: new Delayer<void>(200)
}
this._changeDelayer.delayer.trigger(() => {
this._client.sendNotification(DidChangeTextDocumentNotification.type, this._client.code2ProtocolConverter.asChangeTextDocumentParams(event.document));
}, -1);
}
};
if (middleware.didChange) {
middleware.didChange(event, didChange);
} else {
didChange(event);
}
}
}
}
}
public unregister(id: string): void {
this._changeData.delete(id);
if (this._changeData.size === 0 && this._listener) {
this._listener.dispose();
this._listener = undefined;
}
}
public dispose(): void {
this._changeDelayer = undefined;
this._forcingDelivery = false;
this._changeData.clear();
if (this._listener) {
this._listener.dispose();
this._listener = undefined;
}
}
public forceDelivery() {
if (this._forcingDelivery || !this._changeDelayer) {
return;
}
try {
this._forcingDelivery = true;
this._changeDelayer.delayer.forceDelivery();
} finally {
this._forcingDelivery = false;
}
}
}
class WillSaveFeature extends DocumentNotifiactions<WillSaveTextDocumentParams, TextDocumentWillSaveEvent> {
constructor(client: BaseLanguageClient) {
super(
client, Workspace.onWillSaveTextDocument, WillSaveTextDocumentNotification.type,
client.clientOptions.middleware!.willSave,
(willSaveEvent) => client.code2ProtocolConverter.asWillSaveTextDocumentParams(willSaveEvent),
(selectors, willSaveEvent) => DocumentNotifiactions.textDocumentFilter(selectors, willSaveEvent.document)
)
}
public get messages(): RPCMessageType {
return WillSaveTextDocumentNotification.type;
}
public fillClientCapabilities(capabilities: ClientCapabilities): void {
let value = ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!;
value.willSave = true;
}
public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void {
let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync;
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSave) {
this.register(this.messages, {
id: UUID.generateUuid(),
registerOptions: { documentSelector: documentSelector }
});
}
}
}
class WillSaveWaitUntilFeature implements DynamicFeature<TextDocumentRegistrationOptions> {
private _listener: Disposable | undefined;
private _selectors: Map<string, DocumentSelector> = new Map<string, DocumentSelector>();
constructor(private _client: BaseLanguageClient) {
}
public get messages(): RPCMessageType {
return WillSaveTextDocumentWaitUntilRequest.type;
}
public fillClientCapabilities(capabilities: ClientCapabilities): void {
let value = ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!;