forked from PowerShell/PowerShellEditorServices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConsoleReadLine.cs
616 lines (535 loc) · 24.3 KB
/
ConsoleReadLine.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
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.PowerShell.EditorServices.Console
{
using System;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Security;
internal class ConsoleReadLine
{
#region Private Field
private PowerShellContext powerShellContext;
#endregion
#region Constructors
public ConsoleReadLine(PowerShellContext powerShellContext)
{
this.powerShellContext = powerShellContext;
}
#endregion
#region Public Methods
public Task<string> ReadCommandLineAsync(CancellationToken cancellationToken)
{
return this.ReadLineAsync(true, cancellationToken);
}
public Task<string> ReadSimpleLineAsync(CancellationToken cancellationToken)
{
return this.ReadLineAsync(false, cancellationToken);
}
public async Task<SecureString> ReadSecureLineAsync(CancellationToken cancellationToken)
{
SecureString secureString = new SecureString();
int initialPromptRow = await ConsoleProxy.GetCursorTopAsync(cancellationToken);
int initialPromptCol = await ConsoleProxy.GetCursorLeftAsync(cancellationToken);
int previousInputLength = 0;
Console.TreatControlCAsInput = true;
try
{
while (!cancellationToken.IsCancellationRequested)
{
ConsoleKeyInfo keyInfo = await ReadKeyAsync(cancellationToken);
if ((int)keyInfo.Key == 3 ||
keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
{
throw new PipelineStoppedException();
}
if (keyInfo.Key == ConsoleKey.Enter)
{
// Break to return the completed string
break;
}
if (keyInfo.Key == ConsoleKey.Tab)
{
continue;
}
if (keyInfo.Key == ConsoleKey.Backspace)
{
if (secureString.Length > 0)
{
secureString.RemoveAt(secureString.Length - 1);
}
}
else if (keyInfo.KeyChar != 0 && !char.IsControl(keyInfo.KeyChar))
{
secureString.AppendChar(keyInfo.KeyChar);
}
// Re-render the secure string characters
int currentInputLength = secureString.Length;
int consoleWidth = Console.WindowWidth;
if (currentInputLength > previousInputLength)
{
Console.Write('*');
}
else if (previousInputLength > 0 && currentInputLength < previousInputLength)
{
int row = await ConsoleProxy.GetCursorTopAsync(cancellationToken);
int col = await ConsoleProxy.GetCursorLeftAsync(cancellationToken);
// Back up the cursor before clearing the character
col--;
if (col < 0)
{
col = consoleWidth - 1;
row--;
}
Console.SetCursorPosition(col, row);
Console.Write(' ');
Console.SetCursorPosition(col, row);
}
previousInputLength = currentInputLength;
}
}
finally
{
Console.TreatControlCAsInput = false;
}
return secureString;
}
#endregion
#region Private Methods
private static async Task<ConsoleKeyInfo> ReadKeyAsync(CancellationToken cancellationToken)
{
return await ConsoleProxy.ReadKeyAsync(intercept: true, cancellationToken);
}
private async Task<string> ReadLineAsync(bool isCommandLine, CancellationToken cancellationToken)
{
return await this.powerShellContext.InvokeReadLineAsync(isCommandLine, cancellationToken);
}
/// <summary>
/// Invokes a custom ReadLine method that is similar to but more basic than PSReadLine.
/// This method should be used when PSReadLine is disabled, either by user settings or
/// unsupported PowerShell versions.
/// </summary>
/// <param name="isCommandLine">
/// Indicates whether ReadLine should act like a command line.
/// </param>
/// <param name="cancellationToken">
/// The cancellation token that will be checked prior to completing the returned task.
/// </param>
/// <returns>
/// A task object representing the asynchronus operation. The Result property on
/// the task object returns the user input string.
/// </returns>
internal async Task<string> InvokeLegacyReadLineAsync(bool isCommandLine, CancellationToken cancellationToken)
{
string inputBeforeCompletion = null;
string inputAfterCompletion = null;
CommandCompletion currentCompletion = null;
int historyIndex = -1;
Collection<PSObject> currentHistory = null;
StringBuilder inputLine = new StringBuilder();
int initialCursorCol = await ConsoleProxy.GetCursorLeftAsync(cancellationToken);
int initialCursorRow = await ConsoleProxy.GetCursorTopAsync(cancellationToken);
int initialWindowLeft = Console.WindowLeft;
int initialWindowTop = Console.WindowTop;
int currentCursorIndex = 0;
Console.TreatControlCAsInput = true;
try
{
while (!cancellationToken.IsCancellationRequested)
{
ConsoleKeyInfo keyInfo = await ReadKeyAsync(cancellationToken);
// Do final position calculation after the key has been pressed
// because the window could have been resized before then
int promptStartCol = initialCursorCol;
int promptStartRow = initialCursorRow;
int consoleWidth = Console.WindowWidth;
if ((int)keyInfo.Key == 3 ||
keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
{
throw new PipelineStoppedException();
}
else if (keyInfo.Key == ConsoleKey.Tab && isCommandLine)
{
if (currentCompletion == null)
{
inputBeforeCompletion = inputLine.ToString();
inputAfterCompletion = null;
// TODO: This logic should be moved to AstOperations or similar!
if (this.powerShellContext.IsDebuggerStopped)
{
PSCommand command = new PSCommand();
command.AddCommand("TabExpansion2");
command.AddParameter("InputScript", inputBeforeCompletion);
command.AddParameter("CursorColumn", currentCursorIndex);
command.AddParameter("Options", null);
var results =
await this.powerShellContext.ExecuteCommandAsync<CommandCompletion>(command, false, false);
currentCompletion = results.FirstOrDefault();
}
else
{
using (RunspaceHandle runspaceHandle = await this.powerShellContext.GetRunspaceHandleAsync())
using (PowerShell powerShell = PowerShell.Create())
{
powerShell.Runspace = runspaceHandle.Runspace;
currentCompletion =
CommandCompletion.CompleteInput(
inputBeforeCompletion,
currentCursorIndex,
null,
powerShell);
if (currentCompletion.CompletionMatches.Count > 0)
{
int replacementEndIndex =
currentCompletion.ReplacementIndex +
currentCompletion.ReplacementLength;
inputAfterCompletion =
inputLine.ToString(
replacementEndIndex,
inputLine.Length - replacementEndIndex);
}
else
{
currentCompletion = null;
}
}
}
}
CompletionResult completion =
currentCompletion?.GetNextResult(
!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift));
if (completion != null)
{
currentCursorIndex =
this.InsertInput(
inputLine,
promptStartCol,
promptStartRow,
$"{completion.CompletionText}{inputAfterCompletion}",
currentCursorIndex,
insertIndex: currentCompletion.ReplacementIndex,
replaceLength: inputLine.Length - currentCompletion.ReplacementIndex,
finalCursorIndex: currentCompletion.ReplacementIndex + completion.CompletionText.Length);
}
}
else if (keyInfo.Key == ConsoleKey.LeftArrow)
{
currentCompletion = null;
if (currentCursorIndex > 0)
{
currentCursorIndex =
this.MoveCursorToIndex(
promptStartCol,
promptStartRow,
consoleWidth,
currentCursorIndex - 1);
}
}
else if (keyInfo.Key == ConsoleKey.Home)
{
currentCompletion = null;
currentCursorIndex =
this.MoveCursorToIndex(
promptStartCol,
promptStartRow,
consoleWidth,
0);
}
else if (keyInfo.Key == ConsoleKey.RightArrow)
{
currentCompletion = null;
if (currentCursorIndex < inputLine.Length)
{
currentCursorIndex =
this.MoveCursorToIndex(
promptStartCol,
promptStartRow,
consoleWidth,
currentCursorIndex + 1);
}
}
else if (keyInfo.Key == ConsoleKey.End)
{
currentCompletion = null;
currentCursorIndex =
this.MoveCursorToIndex(
promptStartCol,
promptStartRow,
consoleWidth,
inputLine.Length);
}
else if (keyInfo.Key == ConsoleKey.UpArrow && isCommandLine)
{
currentCompletion = null;
// TODO: Ctrl+Up should allow navigation in multi-line input
if (currentHistory == null)
{
historyIndex = -1;
PSCommand command = new PSCommand();
command.AddCommand("Get-History");
currentHistory =
await this.powerShellContext.ExecuteCommandAsync<PSObject>(
command,
false,
false) as Collection<PSObject>;
if (currentHistory != null)
{
historyIndex = currentHistory.Count;
}
}
if (currentHistory != null && currentHistory.Count > 0 && historyIndex > 0)
{
historyIndex--;
currentCursorIndex =
this.InsertInput(
inputLine,
promptStartCol,
promptStartRow,
(string)currentHistory[historyIndex].Properties["CommandLine"].Value,
currentCursorIndex,
insertIndex: 0,
replaceLength: inputLine.Length);
}
}
else if (keyInfo.Key == ConsoleKey.DownArrow && isCommandLine)
{
currentCompletion = null;
// The down arrow shouldn't cause history to be loaded,
// it's only for navigating an active history array
if (historyIndex > -1 && historyIndex < currentHistory.Count &&
currentHistory != null && currentHistory.Count > 0)
{
historyIndex++;
if (historyIndex < currentHistory.Count)
{
currentCursorIndex =
this.InsertInput(
inputLine,
promptStartCol,
promptStartRow,
(string)currentHistory[historyIndex].Properties["CommandLine"].Value,
currentCursorIndex,
insertIndex: 0,
replaceLength: inputLine.Length);
}
else if (historyIndex == currentHistory.Count)
{
currentCursorIndex =
this.InsertInput(
inputLine,
promptStartCol,
promptStartRow,
string.Empty,
currentCursorIndex,
insertIndex: 0,
replaceLength: inputLine.Length);
}
}
}
else if (keyInfo.Key == ConsoleKey.Escape)
{
currentCompletion = null;
historyIndex = currentHistory != null ? currentHistory.Count : -1;
currentCursorIndex =
this.InsertInput(
inputLine,
promptStartCol,
promptStartRow,
string.Empty,
currentCursorIndex,
insertIndex: 0,
replaceLength: inputLine.Length);
}
else if (keyInfo.Key == ConsoleKey.Backspace)
{
currentCompletion = null;
if (currentCursorIndex > 0)
{
currentCursorIndex =
this.InsertInput(
inputLine,
promptStartCol,
promptStartRow,
string.Empty,
currentCursorIndex,
insertIndex: currentCursorIndex - 1,
replaceLength: 1,
finalCursorIndex: currentCursorIndex - 1);
}
}
else if (keyInfo.Key == ConsoleKey.Delete)
{
currentCompletion = null;
if (currentCursorIndex < inputLine.Length)
{
currentCursorIndex =
this.InsertInput(
inputLine,
promptStartCol,
promptStartRow,
string.Empty,
currentCursorIndex,
replaceLength: 1,
finalCursorIndex: currentCursorIndex);
}
}
else if (keyInfo.Key == ConsoleKey.Enter)
{
string completedInput = inputLine.ToString();
currentCompletion = null;
currentHistory = null;
//if ((keyInfo.Modifiers & ConsoleModifiers.Shift) == ConsoleModifiers.Shift)
//{
// // TODO: Start a new line!
// continue;
//}
Parser.ParseInput(
completedInput,
out Token[] tokens,
out ParseError[] parseErrors);
//if (parseErrors.Any(e => e.IncompleteInput))
//{
// // TODO: Start a new line!
// continue;
//}
return completedInput;
}
else if (keyInfo.KeyChar != 0 && !char.IsControl(keyInfo.KeyChar))
{
// Normal character input
currentCompletion = null;
currentCursorIndex =
this.InsertInput(
inputLine,
promptStartCol,
promptStartRow,
keyInfo.KeyChar.ToString(),
currentCursorIndex,
finalCursorIndex: currentCursorIndex + 1);
}
}
}
finally
{
Console.TreatControlCAsInput = false;
}
return null;
}
private int CalculateIndexFromCursor(
int promptStartCol,
int promptStartRow,
int consoleWidth)
{
return
((ConsoleProxy.GetCursorTop() - promptStartRow) * consoleWidth) +
ConsoleProxy.GetCursorLeft() - promptStartCol;
}
private void CalculateCursorFromIndex(
int promptStartCol,
int promptStartRow,
int consoleWidth,
int inputIndex,
out int cursorCol,
out int cursorRow)
{
cursorCol = promptStartCol + inputIndex;
cursorRow = promptStartRow + cursorCol / consoleWidth;
cursorCol = cursorCol % consoleWidth;
}
private int InsertInput(
StringBuilder inputLine,
int promptStartCol,
int promptStartRow,
string insertedInput,
int cursorIndex,
int insertIndex = -1,
int replaceLength = 0,
int finalCursorIndex = -1)
{
int consoleWidth = Console.WindowWidth;
int previousInputLength = inputLine.Length;
if (insertIndex == -1)
{
insertIndex = cursorIndex;
}
// Move the cursor to the new insertion point
this.MoveCursorToIndex(
promptStartCol,
promptStartRow,
consoleWidth,
insertIndex);
// Edit the input string based on the insertion
if (insertIndex < inputLine.Length)
{
if (replaceLength > 0)
{
inputLine.Remove(insertIndex, replaceLength);
}
inputLine.Insert(insertIndex, insertedInput);
}
else
{
inputLine.Append(insertedInput);
}
// Re-render affected section
Console.Write(
inputLine.ToString(
insertIndex,
inputLine.Length - insertIndex));
if (inputLine.Length < previousInputLength)
{
Console.Write(
new string(
' ',
previousInputLength - inputLine.Length));
}
// Automatically set the final cursor position to the end
// of the new input string. This is needed if the previous
// input string is longer than the new one and needed to have
// its old contents overwritten. This will position the cursor
// back at the end of the new text
if (finalCursorIndex == -1 && inputLine.Length < previousInputLength)
{
finalCursorIndex = inputLine.Length;
}
if (finalCursorIndex > -1)
{
// Move the cursor to the final position
return
this.MoveCursorToIndex(
promptStartCol,
promptStartRow,
consoleWidth,
finalCursorIndex);
}
else
{
return inputLine.Length;
}
}
private int MoveCursorToIndex(
int promptStartCol,
int promptStartRow,
int consoleWidth,
int newCursorIndex)
{
this.CalculateCursorFromIndex(
promptStartCol,
promptStartRow,
consoleWidth,
newCursorIndex,
out int newCursorCol,
out int newCursorRow);
Console.SetCursorPosition(newCursorCol, newCursorRow);
return newCursorIndex;
}
#endregion
}
}