forked from PowerShell/PowerShellEditorServices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLanguageServer.cs
2017 lines (1733 loc) · 82.8 KB
/
LanguageServer.cs
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. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Debugging;
using Microsoft.PowerShell.EditorServices.Extensions;
using Microsoft.PowerShell.EditorServices.Protocol.LanguageServer;
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol.Channel;
using Microsoft.PowerShell.EditorServices.Templates;
using Microsoft.PowerShell.EditorServices.Utility;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using DebugAdapterMessages = Microsoft.PowerShell.EditorServices.Protocol.DebugAdapter;
namespace Microsoft.PowerShell.EditorServices.Protocol.Server
{
public class LanguageServer
{
private static CancellationTokenSource s_existingRequestCancellation;
private static readonly Location[] s_emptyLocationResult = new Location[0];
private static readonly CompletionItem[] s_emptyCompletionResult = new CompletionItem[0];
private static readonly SignatureInformation[] s_emptySignatureResult = new SignatureInformation[0];
private static readonly DocumentHighlight[] s_emptyHighlightResult = new DocumentHighlight[0];
private static readonly SymbolInformation[] s_emptySymbolResult = new SymbolInformation[0];
private ILogger Logger;
private bool profilesLoaded;
private bool consoleReplStarted;
private EditorSession editorSession;
private IMessageSender messageSender;
private IMessageHandlers messageHandlers;
private LanguageServerEditorOperations editorOperations;
private LanguageServerSettings currentSettings = new LanguageServerSettings();
// The outer key is the file's uri, the inner key is a unique id for the diagnostic
private Dictionary<string, Dictionary<string, MarkerCorrection>> codeActionsPerFile =
new Dictionary<string, Dictionary<string, MarkerCorrection>>();
private TaskCompletionSource<bool> serverCompletedTask;
public IEditorOperations EditorOperations
{
get { return this.editorOperations; }
}
/// <summary>
/// Initializes a new language server that is used for handing language server protocol messages
/// </summary>
/// <param name="editorSession">The editor session that handles the PowerShell runspace</param>
/// <param name="messageHandlers">An object that manages all of the message handlers</param>
/// <param name="messageSender">The message sender</param>
/// <param name="serverCompletedTask">A TaskCompletionSource<bool> that will be completed to stop the running process</param>
/// <param name="logger">The logger.</param>
public LanguageServer(
EditorSession editorSession,
IMessageHandlers messageHandlers,
IMessageSender messageSender,
TaskCompletionSource<bool> serverCompletedTask,
ILogger logger)
{
this.Logger = logger;
this.editorSession = editorSession;
this.serverCompletedTask = serverCompletedTask;
// Attach to the underlying PowerShell context to listen for changes in the runspace or execution status
this.editorSession.PowerShellContext.RunspaceChanged += PowerShellContext_RunspaceChangedAsync;
this.editorSession.PowerShellContext.ExecutionStatusChanged += PowerShellContext_ExecutionStatusChangedAsync;
// Attach to ExtensionService events
this.editorSession.ExtensionService.CommandAdded += ExtensionService_ExtensionAddedAsync;
this.editorSession.ExtensionService.CommandUpdated += ExtensionService_ExtensionUpdatedAsync;
this.editorSession.ExtensionService.CommandRemoved += ExtensionService_ExtensionRemovedAsync;
this.messageSender = messageSender;
this.messageHandlers = messageHandlers;
// Create the IEditorOperations implementation
this.editorOperations =
new LanguageServerEditorOperations(
this.editorSession,
this.messageSender);
this.editorSession.StartDebugService(this.editorOperations);
this.editorSession.DebugService.DebuggerStopped += DebugService_DebuggerStoppedAsync;
}
/// <summary>
/// Starts the language server client and sends the Initialize method.
/// </summary>
/// <returns>A Task that can be awaited for initialization to complete.</returns>
public void Start()
{
// Register all supported message types
this.messageHandlers.SetRequestHandler(ShutdownRequest.Type, this.HandleShutdownRequestAsync);
this.messageHandlers.SetEventHandler(ExitNotification.Type, this.HandleExitNotificationAsync);
this.messageHandlers.SetRequestHandler(InitializeRequest.Type, this.HandleInitializeRequestAsync);
this.messageHandlers.SetEventHandler(InitializedNotification.Type, this.HandleInitializedNotificationAsync);
this.messageHandlers.SetEventHandler(DidOpenTextDocumentNotification.Type, this.HandleDidOpenTextDocumentNotificationAsync);
this.messageHandlers.SetEventHandler(DidCloseTextDocumentNotification.Type, this.HandleDidCloseTextDocumentNotificationAsync);
this.messageHandlers.SetEventHandler(DidSaveTextDocumentNotification.Type, this.HandleDidSaveTextDocumentNotificationAsync);
this.messageHandlers.SetEventHandler(DidChangeTextDocumentNotification.Type, this.HandleDidChangeTextDocumentNotificationAsync);
this.messageHandlers.SetEventHandler(DidChangeConfigurationNotification<LanguageServerSettingsWrapper>.Type, this.HandleDidChangeConfigurationNotificationAsync);
this.messageHandlers.SetRequestHandler(DefinitionRequest.Type, this.HandleDefinitionRequestAsync);
this.messageHandlers.SetRequestHandler(ReferencesRequest.Type, this.HandleReferencesRequestAsync);
this.messageHandlers.SetRequestHandler(CompletionRequest.Type, this.HandleCompletionRequestAsync);
this.messageHandlers.SetRequestHandler(CompletionResolveRequest.Type, this.HandleCompletionResolveRequestAsync);
this.messageHandlers.SetRequestHandler(SignatureHelpRequest.Type, this.HandleSignatureHelpRequestAsync);
this.messageHandlers.SetRequestHandler(DocumentHighlightRequest.Type, this.HandleDocumentHighlightRequestAsync);
this.messageHandlers.SetRequestHandler(HoverRequest.Type, this.HandleHoverRequestAsync);
this.messageHandlers.SetRequestHandler(WorkspaceSymbolRequest.Type, this.HandleWorkspaceSymbolRequestAsync);
this.messageHandlers.SetRequestHandler(CodeActionRequest.Type, this.HandleCodeActionRequestAsync);
this.messageHandlers.SetRequestHandler(DocumentFormattingRequest.Type, this.HandleDocumentFormattingRequestAsync);
this.messageHandlers.SetRequestHandler(
DocumentRangeFormattingRequest.Type,
this.HandleDocumentRangeFormattingRequestAsync);
this.messageHandlers.SetRequestHandler(FoldingRangeRequest.Type, this.HandleFoldingRangeRequestAsync);
this.messageHandlers.SetRequestHandler(ShowHelpRequest.Type, this.HandleShowHelpRequestAsync);
this.messageHandlers.SetRequestHandler(ExpandAliasRequest.Type, this.HandleExpandAliasRequestAsync);
this.messageHandlers.SetRequestHandler(GetCommandRequest.Type, this.HandleGetCommandRequestAsync);
this.messageHandlers.SetRequestHandler(FindModuleRequest.Type, this.HandleFindModuleRequestAsync);
this.messageHandlers.SetRequestHandler(InstallModuleRequest.Type, this.HandleInstallModuleRequestAsync);
this.messageHandlers.SetRequestHandler(InvokeExtensionCommandRequest.Type, this.HandleInvokeExtensionCommandRequestAsync);
this.messageHandlers.SetRequestHandler(PowerShellVersionRequest.Type, this.HandlePowerShellVersionRequestAsync);
this.messageHandlers.SetRequestHandler(NewProjectFromTemplateRequest.Type, this.HandleNewProjectFromTemplateRequestAsync);
this.messageHandlers.SetRequestHandler(GetProjectTemplatesRequest.Type, this.HandleGetProjectTemplatesRequestAsync);
this.messageHandlers.SetRequestHandler(DebugAdapterMessages.EvaluateRequest.Type, this.HandleEvaluateRequestAsync);
this.messageHandlers.SetRequestHandler(GetPSSARulesRequest.Type, this.HandleGetPSSARulesRequestAsync);
this.messageHandlers.SetRequestHandler(SetPSSARulesRequest.Type, this.HandleSetPSSARulesRequestAsync);
this.messageHandlers.SetRequestHandler(ScriptRegionRequest.Type, this.HandleGetFormatScriptRegionRequestAsync);
this.messageHandlers.SetRequestHandler(GetPSHostProcessesRequest.Type, this.HandleGetPSHostProcessesRequestAsync);
this.messageHandlers.SetRequestHandler(CommentHelpRequest.Type, this.HandleCommentHelpRequestAsync);
this.messageHandlers.SetRequestHandler(GetRunspaceRequest.Type, this.HandleGetRunspaceRequestAsync);
// Initialize the extension service
// TODO: This should be made awaited once Initialize is async!
this.editorSession.ExtensionService.InitializeAsync(
this.editorOperations,
this.editorSession.Components).Wait();
}
protected Task Stop()
{
Logger.Write(LogLevel.Normal, "Language service is shutting down...");
// complete the task so that the host knows to shut down
this.serverCompletedTask.SetResult(true);
return Task.FromResult(true);
}
#region Built-in Message Handlers
private async Task HandleShutdownRequestAsync(
RequestContext<object> requestContext)
{
// Allow the implementor to shut down gracefully
await requestContext.SendResultAsync(new object());
}
private async Task HandleExitNotificationAsync(
object exitParams,
EventContext eventContext)
{
// Stop the server channel
await this.Stop();
}
private Task HandleInitializedNotificationAsync(InitializedParams initializedParams,
EventContext eventContext)
{
// Can do dynamic registration of capabilities in this notification handler
return Task.FromResult(true);
}
protected async Task HandleInitializeRequestAsync(
InitializeParams initializeParams,
RequestContext<InitializeResult> requestContext)
{
// Grab the workspace path from the parameters
editorSession.Workspace.WorkspacePath = initializeParams.RootPath;
// Set the working directory of the PowerShell session to the workspace path
if (editorSession.Workspace.WorkspacePath != null)
{
await editorSession.PowerShellContext.SetWorkingDirectoryAsync(
editorSession.Workspace.WorkspacePath,
isPathAlreadyEscaped: false);
}
await requestContext.SendResultAsync(
new InitializeResult
{
Capabilities = new ServerCapabilities
{
TextDocumentSync = TextDocumentSyncKind.Incremental,
DefinitionProvider = true,
ReferencesProvider = true,
DocumentHighlightProvider = true,
DocumentSymbolProvider = true,
WorkspaceSymbolProvider = true,
HoverProvider = true,
CodeActionProvider = true,
CodeLensProvider = new CodeLensOptions { ResolveProvider = true },
CompletionProvider = new CompletionOptions
{
ResolveProvider = true,
TriggerCharacters = new string[] { ".", "-", ":", "\\" }
},
SignatureHelpProvider = new SignatureHelpOptions
{
TriggerCharacters = new string[] { " " } // TODO: Other characters here?
},
DocumentFormattingProvider = false,
DocumentRangeFormattingProvider = false,
RenameProvider = false,
FoldingRangeProvider = true
}
});
}
protected async Task HandleShowHelpRequestAsync(
string helpParams,
RequestContext<object> requestContext)
{
const string CheckHelpScript = @"
[CmdletBinding()]
param (
[String]$CommandName
)
try {
$command = Microsoft.PowerShell.Core\Get-Command $CommandName -ErrorAction Stop
} catch [System.Management.Automation.CommandNotFoundException] {
$PSCmdlet.ThrowTerminatingError($PSItem)
}
try {
$helpUri = [Microsoft.PowerShell.Commands.GetHelpCodeMethods]::GetHelpUri($command)
$oldSslVersion = [System.Net.ServicePointManager]::SecurityProtocol
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
# HEAD means we don't need the content itself back, just the response header
$status = (Microsoft.PowerShell.Utility\Invoke-WebRequest -Method Head -Uri $helpUri -TimeoutSec 5 -ErrorAction Stop).StatusCode
if ($status -lt 400) {
$null = Microsoft.PowerShell.Core\Get-Help $CommandName -Online
return
}
} catch {
# Ignore - we want to drop out to Get-Help -Full
} finally {
[System.Net.ServicePointManager]::SecurityProtocol = $oldSslVersion
}
return Microsoft.PowerShell.Core\Get-Help $CommandName -Full
";
if (string.IsNullOrEmpty(helpParams)) { helpParams = "Get-Help"; }
PSCommand checkHelpPSCommand = new PSCommand()
.AddScript(CheckHelpScript, useLocalScope: true)
.AddArgument(helpParams);
// TODO: Rather than print the help in the console, we should send the string back
// to VSCode to display in a help pop-up (or similar)
await editorSession.PowerShellContext.ExecuteCommandAsync<PSObject>(checkHelpPSCommand, sendOutputToHost: true);
await requestContext.SendResultAsync(null);
}
private async Task HandleSetPSSARulesRequestAsync(
object param,
RequestContext<object> requestContext)
{
var dynParams = param as dynamic;
if (editorSession.AnalysisService != null &&
editorSession.AnalysisService.SettingsPath == null)
{
var activeRules = new List<string>();
var ruleInfos = dynParams.ruleInfos;
foreach (dynamic ruleInfo in ruleInfos)
{
if ((Boolean)ruleInfo.isEnabled)
{
activeRules.Add((string)ruleInfo.name);
}
}
editorSession.AnalysisService.ActiveRules = activeRules.ToArray();
}
var sendresult = requestContext.SendResultAsync(null);
var scripFile = editorSession.Workspace.GetFile((string)dynParams.filepath);
await RunScriptDiagnosticsAsync(
new ScriptFile[] { scripFile },
editorSession,
this.messageSender.SendEventAsync);
await sendresult;
}
private async Task HandleGetFormatScriptRegionRequestAsync(
ScriptRegionRequestParams requestParams,
RequestContext<ScriptRegionRequestResult> requestContext)
{
var scriptFile = this.editorSession.Workspace.GetFile(requestParams.FileUri);
var lineNumber = requestParams.Line;
var columnNumber = requestParams.Column;
ScriptRegion scriptRegion = null;
switch (requestParams.Character)
{
case "\n":
// find the smallest statement ast that occupies
// the element before \n or \r\n and return the extent.
--lineNumber; // vscode sends the next line when pressed enter
var line = scriptFile.GetLine(lineNumber);
if (!String.IsNullOrEmpty(line))
{
scriptRegion = this.editorSession.LanguageService.FindSmallestStatementAstRegion(
scriptFile,
lineNumber,
line.Length);
}
break;
case "}":
scriptRegion = this.editorSession.LanguageService.FindSmallestStatementAstRegion(
scriptFile,
lineNumber,
columnNumber);
break;
default:
break;
}
await requestContext.SendResultAsync(new ScriptRegionRequestResult
{
scriptRegion = scriptRegion
});
}
private async Task HandleGetPSSARulesRequestAsync(
object param,
RequestContext<object> requestContext)
{
List<object> rules = null;
if (editorSession.AnalysisService != null
&& editorSession.AnalysisService.SettingsPath == null)
{
rules = new List<object>();
var ruleNames = editorSession.AnalysisService.GetPSScriptAnalyzerRules();
var activeRules = editorSession.AnalysisService.ActiveRules;
foreach (var ruleName in ruleNames)
{
rules.Add(new { name = ruleName, isEnabled = activeRules.Contains(ruleName, StringComparer.OrdinalIgnoreCase) });
}
}
await requestContext.SendResultAsync(rules);
}
private async Task HandleInstallModuleRequestAsync(
string moduleName,
RequestContext<object> requestContext
)
{
var script = string.Format("Install-Module -Name {0} -Scope CurrentUser", moduleName);
var executeTask =
editorSession.PowerShellContext.ExecuteScriptStringAsync(
script,
true,
true).ConfigureAwait(false);
await requestContext.SendResultAsync(null);
}
private Task HandleInvokeExtensionCommandRequestAsync(
InvokeExtensionCommandRequest commandDetails,
RequestContext<string> requestContext)
{
// We don't await the result of the execution here because we want
// to be able to receive further messages while the editor command
// is executing. This important in cases where the pipeline thread
// gets blocked by something in the script like a prompt to the user.
EditorContext editorContext =
this.editorOperations.ConvertClientEditorContext(
commandDetails.Context);
Task commandTask =
this.editorSession.ExtensionService.InvokeCommandAsync(
commandDetails.Name,
editorContext);
commandTask.ContinueWith(t =>
{
return requestContext.SendResultAsync(null);
});
return Task.FromResult(true);
}
private Task HandleNewProjectFromTemplateRequestAsync(
NewProjectFromTemplateRequest newProjectArgs,
RequestContext<NewProjectFromTemplateResponse> requestContext)
{
// Don't await the Task here so that we don't block the session
this.editorSession.TemplateService
.CreateFromTemplateAsync(newProjectArgs.TemplatePath, newProjectArgs.DestinationPath)
.ContinueWith(
async task =>
{
await requestContext.SendResultAsync(
new NewProjectFromTemplateResponse
{
CreationSuccessful = task.Result
});
});
return Task.FromResult(true);
}
private async Task HandleGetProjectTemplatesRequestAsync(
GetProjectTemplatesRequest requestArgs,
RequestContext<GetProjectTemplatesResponse> requestContext)
{
bool plasterInstalled = await this.editorSession.TemplateService.ImportPlasterIfInstalledAsync();
if (plasterInstalled)
{
var availableTemplates =
await this.editorSession.TemplateService.GetAvailableTemplatesAsync(
requestArgs.IncludeInstalledModules);
await requestContext.SendResultAsync(
new GetProjectTemplatesResponse
{
Templates = availableTemplates
});
}
else
{
await requestContext.SendResultAsync(
new GetProjectTemplatesResponse
{
NeedsModuleInstall = true,
Templates = new TemplateDetails[0]
});
}
}
private async Task HandleExpandAliasRequestAsync(
string content,
RequestContext<string> requestContext)
{
var script = @"
function __Expand-Alias {
param($targetScript)
[ref]$errors=$null
$tokens = [System.Management.Automation.PsParser]::Tokenize($targetScript, $errors).Where({$_.type -eq 'command'}) |
Sort-Object Start -Descending
foreach ($token in $tokens) {
$definition=(Get-Command ('`'+$token.Content) -CommandType Alias -ErrorAction SilentlyContinue).Definition
if($definition) {
$lhs=$targetScript.Substring(0, $token.Start)
$rhs=$targetScript.Substring($token.Start + $token.Length)
$targetScript=$lhs + $definition + $rhs
}
}
$targetScript
}";
var psCommand = new PSCommand();
psCommand.AddScript(script);
await this.editorSession.PowerShellContext.ExecuteCommandAsync<PSObject>(psCommand);
psCommand = new PSCommand();
psCommand.AddCommand("__Expand-Alias").AddArgument(content);
var result = await this.editorSession.PowerShellContext.ExecuteCommandAsync<string>(psCommand);
await requestContext.SendResultAsync(result.First().ToString());
}
private async Task HandleGetCommandRequestAsync(
string param,
RequestContext<object> requestContext)
{
PSCommand psCommand = new PSCommand();
if (!string.IsNullOrEmpty(param))
{
psCommand.AddCommand("Microsoft.PowerShell.Core\\Get-Command").AddArgument(param);
}
else
{
// Executes the following:
// Get-Command -CommandType Function,Cmdlet,ExternalScript | Select-Object -Property Name,ModuleName | Sort-Object -Property Name
psCommand
.AddCommand("Microsoft.PowerShell.Core\\Get-Command")
.AddParameter("CommandType", new[]{"Function", "Cmdlet", "ExternalScript"})
.AddCommand("Microsoft.PowerShell.Utility\\Select-Object")
.AddParameter("Property", new[]{"Name", "ModuleName"})
.AddCommand("Microsoft.PowerShell.Utility\\Sort-Object")
.AddParameter("Property", "Name");
}
IEnumerable<PSObject> result = await this.editorSession.PowerShellContext.ExecuteCommandAsync<PSObject>(psCommand);
var commandList = new List<PSCommandMessage>();
if (result != null)
{
foreach (dynamic command in result)
{
commandList.Add(new PSCommandMessage
{
Name = command.Name,
ModuleName = command.ModuleName,
Parameters = command.Parameters,
ParameterSets = command.ParameterSets,
DefaultParameterSet = command.DefaultParameterSet
});
}
}
await requestContext.SendResultAsync(commandList);
}
private async Task HandleFindModuleRequestAsync(
object param,
RequestContext<object> requestContext)
{
var psCommand = new PSCommand();
psCommand.AddScript("Find-Module | Select Name, Description");
var modules = await editorSession.PowerShellContext.ExecuteCommandAsync<PSObject>(psCommand);
var moduleList = new List<PSModuleMessage>();
if (modules != null)
{
foreach (dynamic m in modules)
{
moduleList.Add(new PSModuleMessage { Name = m.Name, Description = m.Description });
}
}
await requestContext.SendResultAsync(moduleList);
}
protected Task HandleDidOpenTextDocumentNotificationAsync(
DidOpenTextDocumentParams openParams,
EventContext eventContext)
{
ScriptFile openedFile =
editorSession.Workspace.GetFileBuffer(
openParams.TextDocument.Uri,
openParams.TextDocument.Text);
// TODO: Get all recently edited files in the workspace
this.RunScriptDiagnosticsAsync(
new ScriptFile[] { openedFile },
editorSession,
eventContext);
Logger.Write(LogLevel.Verbose, "Finished opening document.");
return Task.FromResult(true);
}
protected async Task HandleDidCloseTextDocumentNotificationAsync(
DidCloseTextDocumentParams closeParams,
EventContext eventContext)
{
// Find and close the file in the current session
var fileToClose = editorSession.Workspace.GetFile(closeParams.TextDocument.Uri);
if (fileToClose != null)
{
editorSession.Workspace.CloseFile(fileToClose);
await ClearMarkersAsync(fileToClose, eventContext);
}
Logger.Write(LogLevel.Verbose, "Finished closing document.");
}
protected async Task HandleDidSaveTextDocumentNotificationAsync(
DidSaveTextDocumentParams saveParams,
EventContext eventContext)
{
ScriptFile savedFile =
this.editorSession.Workspace.GetFile(
saveParams.TextDocument.Uri);
if (savedFile != null)
{
if (this.editorSession.RemoteFileManager.IsUnderRemoteTempPath(savedFile.FilePath))
{
await this.editorSession.RemoteFileManager.SaveRemoteFileAsync(
savedFile.FilePath);
}
}
}
protected Task HandleDidChangeTextDocumentNotificationAsync(
DidChangeTextDocumentParams textChangeParams,
EventContext eventContext)
{
List<ScriptFile> changedFiles = new List<ScriptFile>();
// A text change notification can batch multiple change requests
foreach (var textChange in textChangeParams.ContentChanges)
{
ScriptFile changedFile = editorSession.Workspace.GetFile(textChangeParams.TextDocument.Uri);
changedFile.ApplyChange(
GetFileChangeDetails(
textChange.Range,
textChange.Text));
changedFiles.Add(changedFile);
}
// TODO: Get all recently edited files in the workspace
this.RunScriptDiagnosticsAsync(
changedFiles.ToArray(),
editorSession,
eventContext);
return Task.FromResult(true);
}
protected async Task HandleDidChangeConfigurationNotificationAsync(
DidChangeConfigurationParams<LanguageServerSettingsWrapper> configChangeParams,
EventContext eventContext)
{
bool oldLoadProfiles = this.currentSettings.EnableProfileLoading;
bool oldScriptAnalysisEnabled =
this.currentSettings.ScriptAnalysis.Enable.HasValue ? this.currentSettings.ScriptAnalysis.Enable.Value : false;
string oldScriptAnalysisSettingsPath =
this.currentSettings.ScriptAnalysis?.SettingsPath;
this.currentSettings.Update(
configChangeParams.Settings.Powershell,
this.editorSession.Workspace.WorkspacePath,
this.Logger);
if (!this.profilesLoaded &&
this.currentSettings.EnableProfileLoading &&
oldLoadProfiles != this.currentSettings.EnableProfileLoading)
{
await this.editorSession.PowerShellContext.LoadHostProfilesAsync();
this.profilesLoaded = true;
}
// Wait until after profiles are loaded (or not, if that's the
// case) before starting the interactive console.
if (!this.consoleReplStarted)
{
// Start the interactive terminal
this.editorSession.HostInput.StartCommandLoop();
this.consoleReplStarted = true;
}
// If there is a new settings file path, restart the analyzer with the new settigs.
bool settingsPathChanged = false;
string newSettingsPath = this.currentSettings.ScriptAnalysis.SettingsPath;
if (!string.Equals(oldScriptAnalysisSettingsPath, newSettingsPath, StringComparison.OrdinalIgnoreCase))
{
if (this.editorSession.AnalysisService != null)
{
this.editorSession.AnalysisService.SettingsPath = newSettingsPath;
settingsPathChanged = true;
}
}
// If script analysis settings have changed we need to clear & possibly update the current diagnostic records.
if ((oldScriptAnalysisEnabled != this.currentSettings.ScriptAnalysis?.Enable) || settingsPathChanged)
{
// If the user just turned off script analysis or changed the settings path, send a diagnostics
// event to clear the analysis markers that they already have.
if (!this.currentSettings.ScriptAnalysis.Enable.Value || settingsPathChanged)
{
foreach (var scriptFile in editorSession.Workspace.GetOpenedFiles())
{
await ClearMarkersAsync(scriptFile, eventContext);
}
}
await this.RunScriptDiagnosticsAsync(
this.editorSession.Workspace.GetOpenedFiles(),
this.editorSession,
eventContext);
}
}
protected async Task HandleDefinitionRequestAsync(
TextDocumentPositionParams textDocumentPosition,
RequestContext<Location[]> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
textDocumentPosition.TextDocument.Uri);
SymbolReference foundSymbol =
editorSession.LanguageService.FindSymbolAtLocation(
scriptFile,
textDocumentPosition.Position.Line + 1,
textDocumentPosition.Position.Character + 1);
List<Location> definitionLocations = new List<Location>();
GetDefinitionResult definition = null;
if (foundSymbol != null)
{
definition =
await editorSession.LanguageService.GetDefinitionOfSymbolAsync(
scriptFile,
foundSymbol,
editorSession.Workspace);
if (definition != null)
{
definitionLocations.Add(
new Location
{
Uri = GetFileUri(definition.FoundDefinition.FilePath),
Range = GetRangeFromScriptRegion(definition.FoundDefinition.ScriptRegion)
});
}
}
await requestContext.SendResultAsync(definitionLocations.ToArray());
}
protected async Task HandleReferencesRequestAsync(
ReferencesParams referencesParams,
RequestContext<Location[]> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
referencesParams.TextDocument.Uri);
SymbolReference foundSymbol =
editorSession.LanguageService.FindSymbolAtLocation(
scriptFile,
referencesParams.Position.Line + 1,
referencesParams.Position.Character + 1);
FindReferencesResult referencesResult =
await editorSession.LanguageService.FindReferencesOfSymbolAsync(
foundSymbol,
editorSession.Workspace.ExpandScriptReferences(scriptFile),
editorSession.Workspace);
Location[] referenceLocations = s_emptyLocationResult;
if (referencesResult != null)
{
var locations = new List<Location>();
foreach (SymbolReference foundReference in referencesResult.FoundReferences)
{
locations.Add(new Location
{
Uri = GetFileUri(foundReference.FilePath),
Range = GetRangeFromScriptRegion(foundReference.ScriptRegion)
});
}
referenceLocations = locations.ToArray();
}
await requestContext.SendResultAsync(referenceLocations);
}
protected async Task HandleCompletionRequestAsync(
TextDocumentPositionParams textDocumentPositionParams,
RequestContext<CompletionItem[]> requestContext)
{
int cursorLine = textDocumentPositionParams.Position.Line + 1;
int cursorColumn = textDocumentPositionParams.Position.Character + 1;
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
textDocumentPositionParams.TextDocument.Uri);
CompletionResults completionResults =
await editorSession.LanguageService.GetCompletionsInFileAsync(
scriptFile,
cursorLine,
cursorColumn);
CompletionItem[] completionItems = s_emptyCompletionResult;
if (completionResults != null)
{
completionItems = new CompletionItem[completionResults.Completions.Length];
for (int i = 0; i < completionItems.Length; i++)
{
completionItems[i] = CreateCompletionItem(completionResults.Completions[i], completionResults.ReplacedRange, i + 1);
}
}
await requestContext.SendResultAsync(completionItems);
}
protected async Task HandleCompletionResolveRequestAsync(
CompletionItem completionItem,
RequestContext<CompletionItem> requestContext)
{
if (completionItem.Kind == CompletionItemKind.Function)
{
// Get the documentation for the function
CommandInfo commandInfo =
await CommandHelpers.GetCommandInfoAsync(
completionItem.Label,
this.editorSession.PowerShellContext);
if (commandInfo != null)
{
completionItem.Documentation =
await CommandHelpers.GetCommandSynopsisAsync(
commandInfo,
this.editorSession.PowerShellContext);
}
}
// Send back the updated CompletionItem
await requestContext.SendResultAsync(completionItem);
}
protected async Task HandleSignatureHelpRequestAsync(
TextDocumentPositionParams textDocumentPositionParams,
RequestContext<SignatureHelp> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
textDocumentPositionParams.TextDocument.Uri);
ParameterSetSignatures parameterSets =
await editorSession.LanguageService.FindParameterSetsInFileAsync(
scriptFile,
textDocumentPositionParams.Position.Line + 1,
textDocumentPositionParams.Position.Character + 1);
SignatureInformation[] signatures = s_emptySignatureResult;
if (parameterSets != null)
{
signatures = new SignatureInformation[parameterSets.Signatures.Length];
for (int i = 0; i < signatures.Length; i++)
{
var parameters = new ParameterInformation[parameterSets.Signatures[i].Parameters.Count()];
int j = 0;
foreach (ParameterInfo param in parameterSets.Signatures[i].Parameters)
{
parameters[j] = CreateParameterInfo(param);
j++;
}
signatures[i] = new SignatureInformation
{
Label = parameterSets.CommandName + " " + parameterSets.Signatures[i].SignatureText,
Documentation = null,
Parameters = parameters,
};
}
}
await requestContext.SendResultAsync(
new SignatureHelp
{
Signatures = signatures,
ActiveParameter = null,
ActiveSignature = 0
});
}
protected async Task HandleDocumentHighlightRequestAsync(
TextDocumentPositionParams textDocumentPositionParams,
RequestContext<DocumentHighlight[]> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
textDocumentPositionParams.TextDocument.Uri);
FindOccurrencesResult occurrencesResult =
editorSession.LanguageService.FindOccurrencesInFile(
scriptFile,
textDocumentPositionParams.Position.Line + 1,
textDocumentPositionParams.Position.Character + 1);
DocumentHighlight[] documentHighlights = s_emptyHighlightResult;
if (occurrencesResult != null)
{
var highlights = new List<DocumentHighlight>();
foreach (SymbolReference foundOccurrence in occurrencesResult.FoundOccurrences)
{
highlights.Add(new DocumentHighlight
{
Kind = DocumentHighlightKind.Write, // TODO: Which symbol types are writable?
Range = GetRangeFromScriptRegion(foundOccurrence.ScriptRegion)
});
}
documentHighlights = highlights.ToArray();
}
await requestContext.SendResultAsync(documentHighlights);
}
protected async Task HandleHoverRequestAsync(
TextDocumentPositionParams textDocumentPositionParams,
RequestContext<Hover> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
textDocumentPositionParams.TextDocument.Uri);
SymbolDetails symbolDetails =
await editorSession
.LanguageService
.FindSymbolDetailsAtLocationAsync(
scriptFile,
textDocumentPositionParams.Position.Line + 1,
textDocumentPositionParams.Position.Character + 1);
List<MarkedString> symbolInfo = new List<MarkedString>();
Range symbolRange = null;
if (symbolDetails != null)
{
symbolInfo.Add(
new MarkedString
{
Language = "PowerShell",
Value = symbolDetails.DisplayString
});
if (!string.IsNullOrEmpty(symbolDetails.Documentation))
{
symbolInfo.Add(
new MarkedString
{
Language = "markdown",
Value = symbolDetails.Documentation
});
}
symbolRange = GetRangeFromScriptRegion(symbolDetails.SymbolReference.ScriptRegion);
}
await requestContext.SendResultAsync(
new Hover
{
Contents = symbolInfo.ToArray(),
Range = symbolRange
});
}
protected async Task HandleDocumentSymbolRequestAsync(
DocumentSymbolParams documentSymbolParams,
RequestContext<SymbolInformation[]> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
documentSymbolParams.TextDocument.Uri);