-
Notifications
You must be signed in to change notification settings - Fork 325
Expand file tree
/
Copy pathCmdlets.cs
More file actions
1260 lines (1094 loc) · 45.5 KB
/
Cmdlets.cs
File metadata and controls
1260 lines (1094 loc) · 45.5 KB
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.
--********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Reflection;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.PowerShell.PSReadLine;
using Microsoft.PowerShell.Internal;
using AllowNull = System.Management.Automation.AllowNullAttribute;
namespace Microsoft.PowerShell
{
#pragma warning disable 1591
public enum EditMode
{
Windows,
Emacs,
Vi,
}
public enum BellStyle
{
None,
Visual,
Audible
}
public enum ViModeStyle
{
None,
Prompt,
Cursor,
Script
}
public enum ViMode
{
Insert,
Command
}
public enum HistorySaveStyle
{
SaveIncrementally,
SaveAtExit,
SaveNothing
}
public enum AddToHistoryOption
{
SkipAdding,
MemoryOnly,
MemoryAndFile
}
public enum PredictionSource
{
None = 1,
History = 2,
Plugin = 4,
HistoryAndPlugin = History | Plugin,
}
public enum PredictionViewStyle
{
InlineView,
ListView,
}
public class PSConsoleReadLineOptions
{
public const ConsoleColor DefaultCommentColor = ConsoleColor.DarkGreen;
public const ConsoleColor DefaultKeywordColor = ConsoleColor.Green;
public const ConsoleColor DefaultStringColor = ConsoleColor.DarkCyan;
public const ConsoleColor DefaultOperatorColor = ConsoleColor.DarkGray;
public const ConsoleColor DefaultVariableColor = ConsoleColor.Green;
public const ConsoleColor DefaultCommandColor = ConsoleColor.Yellow;
public const ConsoleColor DefaultParameterColor = ConsoleColor.DarkGray;
public const ConsoleColor DefaultTypeColor = ConsoleColor.Gray;
public const ConsoleColor DefaultNumberColor = ConsoleColor.White;
public const ConsoleColor DefaultMemberColor = ConsoleColor.Gray;
public const ConsoleColor DefaultEmphasisColor = ConsoleColor.Cyan;
public const ConsoleColor DefaultErrorColor = ConsoleColor.Red;
// Find the most suitable color using https://stackoverflow.com/a/33206814
// Default prediction color settings:
// - use FG color 'yellow' for the list-view suggestion text
// - use BG color 'dark black' for the selected list-view suggestion text
public const string DefaultListPredictionColor = "\x1b[33m";
public const string DefaultListPredictionSelectedColor = "\x1b[48;5;238m";
public static readonly string DefaultInlinePredictionColor;
public static readonly string DefaultListPredictionTooltipColor;
public static readonly EditMode DefaultEditMode;
public const string DefaultContinuationPrompt = ">> ";
/// <summary>
/// The maximum number of commands to store in the history.
/// </summary>
public const int DefaultMaximumHistoryCount = 4096;
/// <summary>
/// The maximum number of items to store in the kill ring.
/// </summary>
public const int DefaultMaximumKillRingCount = 10;
/// <summary>
/// In Emacs, when searching history, the cursor doesn't move.
/// In 4NT, the cursor moves to the end. This option allows
/// for either behavior.
/// </summary>
public const bool DefaultHistorySearchCursorMovesToEnd = false;
/// <summary>
/// When displaying possible completions, either display
/// tooltips or display just the completions.
/// </summary>
public const bool DefaultShowToolTips = true;
/// <summary>
/// When ringing the bell, what frequency do we use?
/// </summary>
public const int DefaultDingTone = 1221;
public const int DefaultDingDuration = 50;
public const int DefaultCompletionQueryItems = 100;
// Default includes all characters PowerShell treats like a dash - em dash, en dash, horizontal bar
public const string DefaultWordDelimiters = @";:,.[]{}()/\|!?^&*-=+'""" + "\u2013\u2014\u2015";
/// <summary>
/// When ringing the bell, what should be done?
/// </summary>
public const BellStyle DefaultBellStyle = BellStyle.Audible;
public const bool DefaultHistorySearchCaseSensitive = false;
public const HistorySaveStyle DefaultHistorySaveStyle = HistorySaveStyle.SaveIncrementally;
public const PredictionViewStyle DefaultPredictionViewStyle = PredictionViewStyle.InlineView;
/// <summary>
/// How long in milliseconds should we wait before concluding
/// the input is not an escape sequence?
/// </summary>
public const int DefaultAnsiEscapeTimeout = 100;
static PSConsoleReadLineOptions()
{
// For inline-view suggestion text, we use the new FG color 'dim white italic' when possible, because it provides
// sufficient contrast in terminals that don't use a pure black background (like VSCode terminal).
// However, on Windows 10 and Windows Server, the ConHost doesn't support font effect VT sequences, such as 'dim'
// and 'italic', so we need to use the old FG color 'dark black' as in the v2.2.6.
const string newInlinePredictionColor = "\x1b[97;2;3m";
const string oldInlinePredictionColor = "\x1b[38;5;238m";
ColorSetters = null;
DefaultEditMode = EditMode.Emacs;
DefaultInlinePredictionColor = newInlinePredictionColor;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
DefaultEditMode = EditMode.Windows;
// Our tests expect that the default inline-view color is set to the new color, so we configure
// the color based on system environment only if we are not in test runs.
if (AppDomain.CurrentDomain.FriendlyName is not "testhost")
{
DefaultInlinePredictionColor =
Environment.OSVersion.Version.Build >= 22621 // on Windows 11 22H2 or newer versions
|| Environment.GetEnvironmentVariable("WT_SESSION") is not null // in Windows Terminal
? newInlinePredictionColor
: oldInlinePredictionColor;
}
}
// Use the same color for the list prediction tooltips.
DefaultListPredictionTooltipColor = DefaultInlinePredictionColor;
DefaultAddToHistoryHandler = s => PSConsoleReadLine.GetDefaultAddToHistoryOption(s);
}
public PSConsoleReadLineOptions(string hostName, bool usingLegacyConsole)
{
ResetColors();
EditMode = DefaultEditMode;
ScreenReaderModeEnabled = Accessibility.IsScreenReaderActive();
ContinuationPrompt = DefaultContinuationPrompt;
ContinuationPromptColor = Console.ForegroundColor;
ExtraPromptLineCount = DefaultExtraPromptLineCount;
AddToHistoryHandler = DefaultAddToHistoryHandler;
HistoryNoDuplicates = DefaultHistoryNoDuplicates;
MaximumKillRingCount = DefaultMaximumKillRingCount;
HistorySearchCursorMovesToEnd = DefaultHistorySearchCursorMovesToEnd;
ShowToolTips = DefaultShowToolTips;
DingDuration = DefaultDingDuration;
DingTone = DefaultDingTone;
BellStyle = DefaultBellStyle;
CompletionQueryItems = DefaultCompletionQueryItems;
WordDelimiters = DefaultWordDelimiters;
HistorySearchCaseSensitive = DefaultHistorySearchCaseSensitive;
HistorySaveStyle = DefaultHistorySaveStyle;
AnsiEscapeTimeout = DefaultAnsiEscapeTimeout;
PredictionSource = usingLegacyConsole
? PredictionSource.None
: Environment.Version.Major < 6
? PredictionSource.History
: PredictionSource.HistoryAndPlugin;
PredictionViewStyle = DefaultPredictionViewStyle;
MaximumHistoryCount = 0;
var historyFileName = hostName + "_history.txt";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
HistorySavePath = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"Microsoft",
"Windows",
"PowerShell",
"PSReadLine",
historyFileName);
}
else
{
// PSReadLine can't use Utils.CorePSPlatform (6.0+ only), so do the equivalent:
string historyPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
if (!String.IsNullOrEmpty(historyPath))
{
HistorySavePath = System.IO.Path.Combine(
historyPath,
"powershell",
"PSReadLine",
historyFileName);
}
else
{
// History is data, so it goes into .local/share/powershell folder
var home = Environment.GetEnvironmentVariable("HOME");
if (!String.IsNullOrEmpty(home))
{
HistorySavePath = System.IO.Path.Combine(
home,
".local",
"share",
"powershell",
"PSReadLine",
historyFileName);
}
else
{
// No HOME, then don't save anything
HistorySavePath = "/dev/null";
}
}
}
CommandValidationHandler = null;
CommandsToValidateScriptBlockArguments = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"ForEach-Object", "%",
"Invoke-Command", "icm",
"Measure-Command",
"New-Module", "nmo",
"Register-EngineEvent",
"Register-ObjectEvent",
"Register-WMIEvent",
"Set-PSBreakpoint", "sbp",
"Start-Job", "sajb",
"Trace-Command", "trcm",
"Use-Transaction",
"Where-Object", "?", "where",
};
}
public EditMode EditMode { get; set; }
public string ContinuationPrompt { get; set; }
public object ContinuationPromptColor
{
get => _continuationPromptColor;
set => _continuationPromptColor = VTColorUtils.AsEscapeSequence(value);
}
internal string _continuationPromptColor;
/// <summary>
/// Prompts are typically 1 line, but sometimes they may span lines. This
/// count is used to make sure we can display the full prompt after showing
/// ambiguous completions
/// </summary>
public int ExtraPromptLineCount { get; set; }
public const int DefaultExtraPromptLineCount = 0;
/// <summary>
/// This handler is called before adding a command line to history.
/// The return value indicates if the command line should be skipped,
/// or added to memory only, or added to both memory and history file.
/// </summary>
public Func<string, object> AddToHistoryHandler { get; set; }
public static readonly Func<string, object> DefaultAddToHistoryHandler;
/// <summary>
/// This handler is called from ValidateAndAcceptLine.
/// If an exception is thrown, validation fails and the error is reported.
/// </summary>
public Action<CommandAst> CommandValidationHandler { get; set; }
/// <summary>
/// Most commands do not accept script blocks, but for those that do,
/// we want to validate commands in the script block arguments.
/// Unfortunately, we can't know how the argument is used. In the worst
/// case, for commands like Get-ADUser, the script block actually
/// specifies a different language.
///
/// Because we can't know ahead of time all of the commands that do
/// odd things with script blocks, we create a white-list of commands
/// that do invoke the script block - this covers the most useful cases.
/// </summary>
public HashSet<string> CommandsToValidateScriptBlockArguments { get; set; }
/// <summary>
/// When true, duplicates will not be recalled from history more than once.
/// </summary>
public bool HistoryNoDuplicates { get; set; }
public const bool DefaultHistoryNoDuplicates = true;
public int MaximumHistoryCount { get; set; }
public int MaximumKillRingCount { get; set; }
public bool HistorySearchCursorMovesToEnd { get; set; }
public bool ShowToolTips { get; set; }
public int DingTone { get; set; }
public int CompletionQueryItems { get; set; }
public string WordDelimiters { get; set; }
/// <summary>
/// When ringing the bell, how long (in ms)?
/// </summary>
public int DingDuration { get; set; }
public BellStyle BellStyle { get; set; }
public bool HistorySearchCaseSensitive { get; set; }
internal StringComparison HistoryStringComparison => HistorySearchCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
internal StringComparer HistoryStringComparer => HistorySearchCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
/// <summary>
/// How are command and insert modes indicated when in vi edit mode?
/// </summary>
public ViModeStyle ViModeIndicator { get; set; }
/// <summary>
/// The script block to execute when the indicator mode is set to Script.
/// </summary>
public ScriptBlock ViModeChangeHandler { get; set; }
/// <summary>
/// The path to the saved history.
/// </summary>
public string HistorySavePath { get; set; }
public HistorySaveStyle HistorySaveStyle { get; set; }
/// <summary>
/// Sets the source to get predictive suggestions.
/// </summary>
public PredictionSource PredictionSource { get; set; }
/// <summary>
/// Sets the view style for rendering predictive suggestions.
/// </summary>
public PredictionViewStyle PredictionViewStyle { get; set; }
/// <summary>
/// How long in milliseconds should we wait before concluding
/// the input is not an escape sequence?
/// </summary>
public int AnsiEscapeTimeout { get; set; }
/// <summary>
/// This is the text you want turned red on parse errors, but must
/// occur immediately before the cursor when readline starts.
/// If the prompt function is pure, this value can be inferred, e.g.
/// the default prompt will use "> " for this value.
/// </summary>
public string[] PromptText
{
get => _promptText;
set
{
_promptText = value;
if (_promptText == null || _promptText.Length == 0)
return;
// For texts with VT sequences, reset all attributes if not already.
// We only handle the first 2 elements because that's all will potentially be used.
int minLength = _promptText.Length == 1 ? 1 : 2;
for (int i = 0; i < minLength; i ++)
{
var text = _promptText[i];
if (text.Contains('\x1b') && !text.EndsWith(VTColorUtils.AnsiReset, StringComparison.Ordinal))
{
_promptText[i] = string.Concat(text, VTColorUtils.AnsiReset);
}
}
}
}
private string[] _promptText;
public object DefaultTokenColor
{
get => _defaultTokenColor;
set => _defaultTokenColor = VTColorUtils.AsEscapeSequence(value);
}
public object CommentColor
{
get => _commentColor;
set => _commentColor = VTColorUtils.AsEscapeSequence(value);
}
public object KeywordColor
{
get => _keywordColor;
set => _keywordColor = VTColorUtils.AsEscapeSequence(value);
}
public object StringColor
{
get => _stringColor;
set => _stringColor = VTColorUtils.AsEscapeSequence(value);
}
public object OperatorColor
{
get => _operatorColor;
set => _operatorColor = VTColorUtils.AsEscapeSequence(value);
}
public object VariableColor
{
get => _variableColor;
set => _variableColor = VTColorUtils.AsEscapeSequence(value);
}
public object CommandColor
{
get => _commandColor;
set => _commandColor = VTColorUtils.AsEscapeSequence(value);
}
public object ParameterColor
{
get => _parameterColor;
set => _parameterColor = VTColorUtils.AsEscapeSequence(value);
}
public object TypeColor
{
get => _typeColor;
set => _typeColor = VTColorUtils.AsEscapeSequence(value);
}
public object NumberColor
{
get => _numberColor;
set => _numberColor = VTColorUtils.AsEscapeSequence(value);
}
public object MemberColor
{
get => _memberColor;
set => _memberColor = VTColorUtils.AsEscapeSequence(value);
}
public object EmphasisColor
{
get => _emphasisColor;
set => _emphasisColor = VTColorUtils.AsEscapeSequence(value);
}
public object ErrorColor
{
get => _errorColor;
set => _errorColor = VTColorUtils.AsEscapeSequence(value);
}
public object SelectionColor
{
get => _selectionColor;
set => _selectionColor = VTColorUtils.AsEscapeSequence(value);
}
public object InlinePredictionColor
{
get => _inlinePredictionColor;
set => _inlinePredictionColor = VTColorUtils.AsEscapeSequence(value);
}
public object ListPredictionColor
{
get => _listPredictionColor;
set => _listPredictionColor = VTColorUtils.AsEscapeSequence(value);
}
public object ListPredictionSelectedColor
{
get => _listPredictionSelectedColor;
set => _listPredictionSelectedColor = VTColorUtils.AsEscapeSequence(value);
}
public object ListPredictionTooltipColor
{
get => _listPredictionTooltipColor;
set => _listPredictionTooltipColor = VTColorUtils.AsEscapeSequence(value);
}
public bool TerminateOrphanedConsoleApps { get; set; }
public bool ScreenReaderModeEnabled { get; set; }
internal string _defaultTokenColor;
internal string _commentColor;
internal string _keywordColor;
internal string _stringColor;
internal string _operatorColor;
internal string _variableColor;
internal string _commandColor;
internal string _parameterColor;
internal string _typeColor;
internal string _numberColor;
internal string _memberColor;
internal string _emphasisColor;
internal string _errorColor;
internal string _selectionColor;
internal string _inlinePredictionColor;
internal string _listPredictionColor;
internal string _listPredictionSelectedColor;
internal string _listPredictionTooltipColor;
internal void ResetColors()
{
var fg = Console.ForegroundColor;
DefaultTokenColor = fg;
CommentColor = DefaultCommentColor;
KeywordColor = DefaultKeywordColor;
StringColor = DefaultStringColor;
OperatorColor = DefaultOperatorColor;
VariableColor = DefaultVariableColor;
CommandColor = DefaultCommandColor;
ParameterColor = DefaultParameterColor;
TypeColor = DefaultTypeColor;
NumberColor = DefaultNumberColor;
MemberColor = DefaultMemberColor;
EmphasisColor = DefaultEmphasisColor;
ErrorColor = DefaultErrorColor;
InlinePredictionColor = DefaultInlinePredictionColor;
ListPredictionColor = DefaultListPredictionColor;
ListPredictionSelectedColor = DefaultListPredictionSelectedColor;
ListPredictionTooltipColor = DefaultListPredictionTooltipColor;
var bg = Console.BackgroundColor;
if (fg == VTColorUtils.UnknownColor || bg == VTColorUtils.UnknownColor)
{
// TODO: light vs. dark
fg = ConsoleColor.Gray;
bg = ConsoleColor.Black;
}
SelectionColor = VTColorUtils.AsEscapeSequence(bg, fg);
}
private static Dictionary<string, Action<PSConsoleReadLineOptions, object>> ColorSetters;
internal void SetColor(string property, object value)
{
if (ColorSetters == null)
{
var setters =
new Dictionary<string, Action<PSConsoleReadLineOptions, object>>(StringComparer.OrdinalIgnoreCase)
{
{"ContinuationPrompt", (o, v) => o.ContinuationPromptColor = v},
{"Emphasis", (o, v) => o.EmphasisColor = v},
{"Error", (o, v) => o.ErrorColor = v},
{"Default", (o, v) => o.DefaultTokenColor = v},
{"Comment", (o, v) => o.CommentColor = v},
{"Keyword", (o, v) => o.KeywordColor = v},
{"String", (o, v) => o.StringColor = v},
{"Operator", (o, v) => o.OperatorColor = v},
{"Variable", (o, v) => o.VariableColor = v},
{"Command", (o, v) => o.CommandColor = v},
{"Parameter", (o, v) => o.ParameterColor = v},
{"Type", (o, v) => o.TypeColor = v},
{"Number", (o, v) => o.NumberColor = v},
{"Member", (o, v) => o.MemberColor = v},
{"Selection", (o, v) => o.SelectionColor = v},
{"InlinePrediction", (o, v) => o.InlinePredictionColor = v},
{"ListPrediction", (o, v) => o.ListPredictionColor = v},
{"ListPredictionSelected", (o, v) => o.ListPredictionSelectedColor = v},
{"ListPredictionTooltip", (o, v) => o.ListPredictionTooltipColor = v},
};
Interlocked.CompareExchange(ref ColorSetters, setters, null);
}
if (ColorSetters.TryGetValue(property, out var setter))
{
setter(this, value);
}
else
{
throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, PSReadLineResources.InvalidColorProperty, property));
}
}
}
[Cmdlet("Get", "PSReadLineOption", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=528808")]
[OutputType(typeof(PSConsoleReadLineOptions))]
public class GetPSReadLineOption : PSCmdlet
{
[ExcludeFromCodeCoverage]
protected override void EndProcessing()
{
var options = PSConsoleReadLine.GetOptions();
WriteObject(options);
PSConsoleReadLine.WarnWhenWindowSizeTooSmallForView(options.PredictionViewStyle, this);
}
}
[Cmdlet("Set", "PSReadLineOption", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=528811")]
public class SetPSReadLineOption : PSCmdlet
{
[Parameter]
public EditMode EditMode
{
get => _editMode.GetValueOrDefault();
set => _editMode = value;
}
internal EditMode? _editMode;
[Parameter]
[AllowEmptyString]
public string ContinuationPrompt { get; set; }
[Parameter]
public SwitchParameter HistoryNoDuplicates
{
get => _historyNoDuplicates.GetValueOrDefault();
set => _historyNoDuplicates = value;
}
internal SwitchParameter? _historyNoDuplicates;
[Parameter]
[@AllowNull]
public Func<string, object> AddToHistoryHandler
{
get => _addToHistoryHandler;
set
{
_addToHistoryHandler = value;
_addToHistoryHandlerSpecified = true;
}
}
private Func<string, object> _addToHistoryHandler;
internal bool _addToHistoryHandlerSpecified;
[Parameter]
[@AllowNull]
public Action<CommandAst> CommandValidationHandler
{
get => _commandValidationHandler;
set
{
_commandValidationHandler = value;
_commandValidationHandlerSpecified = true;
}
}
private Action<CommandAst> _commandValidationHandler;
internal bool _commandValidationHandlerSpecified;
[Parameter]
public SwitchParameter HistorySearchCursorMovesToEnd
{
get => _historySearchCursorMovesToEnd.GetValueOrDefault();
set => _historySearchCursorMovesToEnd = value;
}
internal SwitchParameter? _historySearchCursorMovesToEnd;
[Parameter]
[ValidateRange(1, int.MaxValue)]
public int MaximumHistoryCount
{
get => _maximumHistoryCount.GetValueOrDefault();
set => _maximumHistoryCount = value;
}
internal int? _maximumHistoryCount;
[Parameter]
public int MaximumKillRingCount
{
get => _maximumKillRingCount.GetValueOrDefault();
set => _maximumKillRingCount = value;
}
internal int? _maximumKillRingCount;
[Parameter]
public SwitchParameter ShowToolTips
{
get => _showToolTips.GetValueOrDefault();
set => _showToolTips = value;
}
internal SwitchParameter? _showToolTips;
[Parameter]
public int ExtraPromptLineCount
{
get => _extraPromptLineCount.GetValueOrDefault();
set => _extraPromptLineCount = value;
}
internal int? _extraPromptLineCount;
[Parameter]
public int DingTone
{
get => _dingTone.GetValueOrDefault();
set => _dingTone = value;
}
internal int? _dingTone;
[Parameter]
public int DingDuration
{
get => _dingDuration.GetValueOrDefault();
set => _dingDuration = value;
}
internal int? _dingDuration;
[Parameter]
public BellStyle BellStyle
{
get => _bellStyle.GetValueOrDefault();
set => _bellStyle = value;
}
internal BellStyle? _bellStyle;
[Parameter]
public int CompletionQueryItems
{
get => _completionQueryItems.GetValueOrDefault();
set => _completionQueryItems = value;
}
internal int? _completionQueryItems;
[Parameter]
public string WordDelimiters { get; set; }
[Parameter]
public SwitchParameter HistorySearchCaseSensitive
{
get => _historySearchCaseSensitive.GetValueOrDefault();
set => _historySearchCaseSensitive = value;
}
internal SwitchParameter? _historySearchCaseSensitive;
[Parameter]
public HistorySaveStyle HistorySaveStyle
{
get => _historySaveStyle.GetValueOrDefault();
set => _historySaveStyle = value;
}
internal HistorySaveStyle? _historySaveStyle;
[Parameter]
[ValidateNotNullOrEmpty]
public string HistorySavePath
{
get => _historySavePath;
set
{
_historySavePath = GetUnresolvedProviderPathFromPSPath(value);
}
}
private string _historySavePath;
[Parameter]
[ValidateRange(25, 1000)]
public int AnsiEscapeTimeout
{
get => _ansiEscapeTimeout.GetValueOrDefault();
set => _ansiEscapeTimeout = value;
}
internal int? _ansiEscapeTimeout;
[Parameter]
[ValidateNotNull]
public string[] PromptText { get; set; }
[Parameter]
public ViModeStyle ViModeIndicator
{
get => _viModeIndicator.GetValueOrDefault();
set => _viModeIndicator = value;
}
internal ViModeStyle? _viModeIndicator;
[Parameter]
public ScriptBlock ViModeChangeHandler { get; set; }
[Parameter]
public PredictionSource PredictionSource
{
get => _predictionSource.GetValueOrDefault();
set => _predictionSource = value;
}
internal PredictionSource? _predictionSource;
[Parameter]
public PredictionViewStyle PredictionViewStyle
{
get => _predictionViewStyle.GetValueOrDefault();
set => _predictionViewStyle = value;
}
internal PredictionViewStyle? _predictionViewStyle;
[Parameter]
public Hashtable Colors { get; set; }
[Parameter]
public SwitchParameter TerminateOrphanedConsoleApps
{
get => _terminateOrphanedConsoleApps.GetValueOrDefault();
set => _terminateOrphanedConsoleApps = value;
}
internal SwitchParameter? _terminateOrphanedConsoleApps;
[Parameter]
public SwitchParameter EnableScreenReaderMode
{
get => _enableScreenReaderMode.GetValueOrDefault();
set => _enableScreenReaderMode = value;
}
internal SwitchParameter? _enableScreenReaderMode;
[ExcludeFromCodeCoverage]
protected override void EndProcessing()
{
PSConsoleReadLine.SetOptions(this);
}
}
public class ChangePSReadLineKeyHandlerCommandBase : PSCmdlet
{
[Parameter(Position = 0, Mandatory = true)]
[Alias("Key")]
[ValidateNotNullOrEmpty]
public string[] Chord { get; set; }
[Parameter]
public ViMode ViMode { get; set; }
[ExcludeFromCodeCoverage]
protected IDisposable UseRequestedDispatchTables()
{
bool inViMode = PSConsoleReadLine.GetOptions().EditMode == EditMode.Vi;
bool viModeParamPresent = MyInvocation.BoundParameters.ContainsKey("ViMode");
if (inViMode || viModeParamPresent)
{
if (!inViMode)
{
// "-ViMode" must have been specified explicitly. Well, okay... we can
// modify the Vi tables... but isn't that an odd thing to do from
// not-vi mode?
WriteWarning(PSReadLineResources.NotInViMode);
}
if (ViMode == ViMode.Command)
return PSConsoleReadLine.UseViCommandModeTables();
else // default if -ViMode not specified, invalid, or "Insert"
return PSConsoleReadLine.UseViInsertModeTables();
}
return null;
}
}
[Cmdlet("Set", "PSReadLineKeyHandler", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=528810")]
public class SetPSReadLineKeyHandlerCommand : ChangePSReadLineKeyHandlerCommandBase, IDynamicParameters
{
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "ScriptBlock")]
[ValidateNotNull]
public ScriptBlock ScriptBlock { get; set; }
[Parameter(ParameterSetName = "ScriptBlock")]
public string BriefDescription { get; set; }
[Parameter(ParameterSetName = "ScriptBlock")]
[Alias("LongDescription")] // Alias to stay compatible with previous releases
public string Description { get; set; }
private const string FunctionParameter = "Function";
private const string FunctionParameterSet = "Function";
[ExcludeFromCodeCoverage]
protected override void EndProcessing()
{
using (UseRequestedDispatchTables())
{
if (ParameterSetName.Equals(FunctionParameterSet))
{
var function = (string)_dynamicParameters.Value[FunctionParameter].Value;
var mi = typeof (PSConsoleReadLine).GetMethod(function,
BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase);
var keyHandler = (Action<ConsoleKeyInfo?, object>)
mi.CreateDelegate(typeof (Action<ConsoleKeyInfo?, object>));
var functionName = mi.Name;
var longDescription = PSReadLineResources.ResourceManager.GetString(functionName + "Description");
PSConsoleReadLine.SetKeyHandler(Chord, keyHandler, functionName, longDescription);
}
else
{
PSConsoleReadLine.SetKeyHandler(Chord, ScriptBlock, BriefDescription, Description);
}
}
}
private readonly Lazy<RuntimeDefinedParameterDictionary> _dynamicParameters = new(CreateDynamicParametersResult);
private static RuntimeDefinedParameterDictionary CreateDynamicParametersResult()
{
var bindableFunctions = (typeof(PSConsoleReadLine).GetMethods(BindingFlags.Public | BindingFlags.Static))
.Where(method =>
{
var parameters = method.GetParameters();
return parameters.Length == 2
&& parameters[0].ParameterType == typeof(ConsoleKeyInfo?)
&& parameters[1].ParameterType == typeof(object);
})
.Select(method => method.Name)
.OrderBy(name => name);
var attributes = new Collection<Attribute>
{
new ParameterAttribute
{
Position = 1,
Mandatory = true,
ParameterSetName = FunctionParameterSet
},
new ValidateSetAttribute(bindableFunctions.ToArray())
};
var parameter = new RuntimeDefinedParameter(FunctionParameter, typeof(string), attributes);
var result = new RuntimeDefinedParameterDictionary {{FunctionParameter, parameter}};
return result;
}
public object GetDynamicParameters()
{
return _dynamicParameters.Value;
}
}
[Cmdlet("Get", "PSReadLineKeyHandler", DefaultParameterSetName = "FullListing",
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=528807")]
[OutputType(typeof(KeyHandler))]
public class GetKeyHandlerCommand : PSCmdlet
{
[Parameter(ParameterSetName = "FullListing")]
public SwitchParameter Bound
{
get => _bound.GetValueOrDefault();
set => _bound = value;
}
private SwitchParameter? _bound;
[Parameter(ParameterSetName = "FullListing")]
public SwitchParameter Unbound
{
get => _unbound.GetValueOrDefault();
set => _unbound = value;
}
private SwitchParameter? _unbound;
[Parameter(ParameterSetName = "SpecificBindings", Position = 0, Mandatory = true)]
[ValidateNotNullOrEmpty]
[Alias("Key")]