-
Notifications
You must be signed in to change notification settings - Fork 0
/
LineEditor.cs
1323 lines (1120 loc) · 43.2 KB
/
LineEditor.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
//
// getline.cs: A command line editor
//
// Authors:
// Miguel de Icaza (miguel@novell.com)
//
// Modifications/bugfixes for PowerShell 3.0 and CLR4 on Windows:
// Oisin Grehan (oising@gmail.com)
//
// Copyright 2008 Novell, Inc.
//
// Dual-licensed under the terms of the MIT X11 license or the
// Apache License 2.0
//
// Modified 2023 by Bruce Payette to support the Tiny language interpreter.
//
using System;
using System.Collections;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace Tiny
{
public class LineEditor
{
public class Completion
{
public string[] Result;
public int ReplacementIndex;
public string Prefix;
public Completion(string prefix, string[] result, int index)
{
Prefix = prefix;
Result = result;
ReplacementIndex = index;
}
}
public delegate Completion AutoCompleteHandler(string text, int pos);
//static StreamWriter log;
// The text being edited.
private StringBuilder _text;
// The text as it is rendered (replaces (char)1 with ^A on display for example).
private readonly StringBuilder _renderedText;
// The prompt specified, and the prompt shown to the user.
private Func<string> _prompt;
private string _shownPrompt;
// powershell already evaluates the prompt, so we should not but still take it into account
private bool _shouldShowPrompt;
// The current cursor position, indexes into "text", for an index
// into rendered_text, use TextToRenderPos
private int _cursor;
// The row where we started displaying data.
private int _homeRow;
// The maximum length that has been displayed on the screen
private int _maxRendered;
// If we are done editing, this breaks the interactive loop
private bool _done = false;
// The thread where the Editing started taking place
private Thread _editThread;
// Our object that tracks history
public History CommandHistory { get { return _history; }}
private readonly History _history;
// The contents of the kill buffer (cut/paste in Emacs parlance)
private string _killBuffer = "";
// The string being searched for
private string _search;
private string _lastSearch;
// whether we are searching (-1= reverse; 0 = no; 1 = forward)
private int _searching;
// The position where we found the match.
private int _matchAt;
// Used to implement the Kill semantics (multiple Alt-Ds accumulate)
private KeyHandler _lastHandler;
private delegate void KeyHandler();
private struct Handler
{
public readonly ConsoleKeyInfo KeyInfo;
public readonly KeyHandler KeyHandler;
public Handler(ConsoleKey key, KeyHandler h)
{
this.KeyInfo = new ConsoleKeyInfo((char)0, key, shift: false, alt: false, control: false);
KeyHandler = h;
}
public Handler(char c, KeyHandler h)
{
KeyHandler = h;
// Use the "Zoom" as a flag that we only have a character.
this.KeyInfo = new ConsoleKeyInfo(c, ConsoleKey.Zoom, shift: false, alt: false, control: false);
}
public Handler(ConsoleKeyInfo keyInfo, KeyHandler h)
{
this.KeyInfo = keyInfo;
KeyHandler = h;
}
public static Handler Control(char c, KeyHandler h)
{
return new Handler((char)(c - 'A' + 1), h);
}
public static Handler Alt(char c, ConsoleKey k, KeyHandler h)
{
var cki = new ConsoleKeyInfo(c, k, shift: false, alt: true, control: false);
return new Handler(cki, h);
}
}
/// <summary>
/// Invoked when the user requests auto-completion using the tab character
/// </summary>
/// <remarks>
/// The result is null for no values found, an array with a single
/// string, in that case the string should be the text to be inserted
/// for example if the word at pos is "T", the result for a completion
/// of "ToString" should be "oString", not "ToString".
///
/// When there are multiple results, the result should be the full
/// text
/// </remarks>
public /*AutoCompleteHandler*/ Func<string, int, Completion> AutoCompleteEvent;
private static Handler[] _handlers;
private string _defaultPrompt;
// Used by the autocomplete handler to complete properties on variables
public static Dictionary<string, object> TinyVars {get; set;}
public static ScriptBlock TinyCompleter {get; set;}
// Used by the autocomplete handler to complete types
public static List<string> TypeNames;
public LineEditor(string name)
: this(name, 100)
{
}
public LineEditor(string name, int histsize) {
_handlers = new[] {
new Handler(ConsoleKey.Home, CmdHome),
new Handler(ConsoleKey.End, CmdEnd),
new Handler(ConsoleKey.LeftArrow, CmdLeft),
new Handler(ConsoleKey.RightArrow, CmdRight),
new Handler(ConsoleKey.UpArrow, CmdHistoryPrev),
new Handler(ConsoleKey.DownArrow, CmdHistoryNext),
new Handler(ConsoleKey.Enter, CmdDone),
new Handler(ConsoleKey.Backspace, CmdBackspace),
new Handler(ConsoleKey.Delete, CmdDeleteChar),
new Handler(ConsoleKey.Tab, CmdTabOrComplete),
new Handler(ConsoleKey.Escape, CmdClearBuffer),
new Handler(new ConsoleKeyInfo('\0', ConsoleKey.LeftArrow, false, false, true), CmdBackwardWord),
new Handler(new ConsoleKeyInfo('\0', ConsoleKey.RightArrow, false, false, true), CmdForwardWord),
// Emacs keys
Handler.Control('H', CmdHome),
Handler.Control('A', CmdHome),
Handler.Control('E', CmdEnd),
Handler.Control('B', CmdLeft),
Handler.Control('F', CmdRight),
// stubed out for matchingHandler.Control('P', CmdHistoryPrev),
Handler.Control('N', CmdHistoryNext),
Handler.Control('K', CmdKillToEOF),
Handler.Alt('K', ConsoleKey.K, CmdClearBuffer),
Handler.Control('P', MatchParen),
Handler.Control('Y', CmdYank),
// Edit the current line in vi
Handler.Control('\\', CmdVisualEdit),
Handler.Control('D', CmdDeleteChar),
Handler.Control('L', CmdRefresh),
Handler.Control('R', CmdReverseSearch),
// Don't beep.
Handler.Control('G', delegate { }),
Handler.Alt('V', ConsoleKey.V, CmdVisualEdit),
Handler.Alt('B', ConsoleKey.B, CmdBackwardWord),
Handler.Alt('F', ConsoleKey.F, CmdForwardWord),
Handler.Alt('D', ConsoleKey.D, CmdDeleteWord),
Handler.Alt('0', ConsoleKey.D0, CmdHome),
Handler.Alt('9', ConsoleKey.D9, CmdEnd),
Handler.Alt('/', ConsoleKey.Divide, CmdReverseSearch),
Handler.Alt((char)8, ConsoleKey.Backspace, CmdDeleteBackword),
// DEBUG
//Handler.Control ('T', CmdDebug),
// quote a character
Handler.Control('Q', () => this.HandleChar(Console.ReadKey(true).KeyChar))
};
//-----------------------------------
// The autocompletion callback
this.AutoCompleteEvent += (input, position) =>
{
int beginning = position;
string inputString = (string)input;
string[] results = new string[] { };
string prefix = null;
while (--beginning >= 0 && !char.IsWhiteSpace(input[beginning]))
;
if (beginning < position)
{
prefix = inputString.Substring(++beginning, position - beginning);
// Set up for tab completion
List<string> matches = new List<string>();
var candidates = new List<string>();
// Add types if it looks likes a type literal
if (prefix.StartsWith("[<") && ! prefix.Contains(">]"))
{
if (TypeNames == null)
{
TypeNames = new List<string>();
string typePrefix = prefix.Substring(2);
try
{
foreach (var asmb in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var t in asmb.GetExportedTypes())
{
TypeNames.Add("[<" + t.FullName + ">]");
}
}
}
catch (Exception)
{
// Ignore exception
}
}
candidates.AddRange(TypeNames);
}
else if (TinyCompleter != null) {
try {
PSObject psresult = TinyCompleter.InvokeReturnAsIs(prefix) as PSObject;
if (psresult != null) {
object[] sbresults = psresult.BaseObject as object[];
if (sbresults != null) {
foreach (var r in sbresults) {
if (r != null) {
candidates.Add(r.ToString());
}
}
}
else {
candidates.Add(psresult.ToString());
}
}
}
catch (Exception) {
// Ignore errors (mkes it hard to debug
}
}
candidates = candidates.Distinct().ToList();
candidates.Sort();
foreach (var k in candidates)
{
if (k.Length > prefix.Length
&& string.Equals(prefix, k.Substring(0, prefix.Length), StringComparison.OrdinalIgnoreCase))
{
matches.Add(k.Substring(prefix.Length));
}
}
results = matches.ToArray();
}
return new LineEditor.Completion(prefix, results, position);
};
this._renderedText = new StringBuilder();
this._text = new StringBuilder();
this._history = new History(name, histsize);
}
private void Render()
{
if (_shouldShowPrompt)
{
var oldColor = Console.ForegroundColor;
try
{
//BUGBUG consolidate with old prompt function
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(this._shownPrompt);
}
finally
{
Console.ForegroundColor = oldColor;
}
}
Console.Write(this._renderedText);
int max = Math.Max(this._renderedText.Length + this._shownPrompt.Length, this._maxRendered);
for (int i = this._renderedText.Length + this._shownPrompt.Length; i < this._maxRendered; i++)
{
Console.Write(' ');
}
this._maxRendered = this._shownPrompt.Length + this._renderedText.Length;
// Write one more to ensure that we always wrap around properly if we are at the
// end of a line.
Console.Write(' ');
UpdateHomeRow(max);
}
private void UpdateHomeRow(int screenpos)
{
//int lines = 1 + (screenpos / 120);
//BUGBUG
int conwidth = Console.WindowWidth;
int lines = 1 + (screenpos / conwidth);
this._homeRow = Console.CursorTop - (lines - 1);
if (this._homeRow < 0) this._homeRow = 0;
}
private void RenderFrom(int pos)
{
int rpos = TextToRenderPos(pos);
int i;
for (i = rpos; i < this._renderedText.Length; i++) Console.Write(this._renderedText[i]);
int maxExtra = this._maxRendered - this._shownPrompt.Length;
if ((this._shownPrompt.Length + this._renderedText.Length) > this._maxRendered)
{
this._maxRendered = this._shownPrompt.Length + this._renderedText.Length;
}
else
{
for (; i < maxExtra; i++) Console.Write(' ');
}
}
private void ComputeRendered()
{
this._renderedText.Length = 0;
for (int i = 0; i < this._text.Length; i++)
{
int c = (int)this._text[i];
if (c < 26)
{
if (c == '\t') this._renderedText.Append(" ");
else
{
this._renderedText.Append('^');
this._renderedText.Append((char)(c + (int)'A' - 1));
}
}
else this._renderedText.Append((char)c);
}
}
private int TextToRenderPos(int pos)
{
int p = 0;
for (int i = 0; i < pos; i++) {
int c = (int)this._text[i];
if (c < 26)
{
if (c == 9) p += 4;
else p += 2;
}
else p++;
}
return p;
}
private int TextToScreenPos(int pos)
{
return this._shownPrompt.Length + TextToRenderPos(pos);
}
private string GetPromptSafe()
{
string promptText = _defaultPrompt;
try {
promptText = _prompt();
}
catch (Exception ex) {
// swallow prompt delegate errors
Trace.WriteLine("GetPromptSafe error: " + ex);
}
return promptText;
}
private int LineCount
{
get
{
return (this._shownPrompt.Length + this._renderedText.Length) / Console.WindowWidth;
}
}
private void ForceCursor(int newpos)
{
this._cursor = newpos;
int actualPos = this._shownPrompt.Length + TextToRenderPos(this._cursor);
//int row = this._homeRow + (actualPos / 120);
//int col = actualPos % 120;
var conwidth = Console.WindowWidth;
int row = this._homeRow + (actualPos / conwidth);
int col = actualPos % conwidth;
if (row >= Console.BufferHeight) row = Console.BufferHeight - 1;
Console.SetCursorPosition(col, row);
//log.WriteLine ("Going to cursor={0} row={1} col={2} actual={3} prompt={4} ttr={5} old={6}", newpos, row, col, actual_pos, prompt.Length, TextToRenderPos (cursor), cursor);
//log.Flush ();
}
private void UpdateCursor(int newpos)
{
if (this._cursor == newpos) return;
ForceCursor(newpos);
}
private void InsertChar(char c)
{
int prevLines = LineCount;
this._text = this._text.Insert(this._cursor, c);
ComputeRendered();
if (prevLines != LineCount)
{
Console.SetCursorPosition(0, this._homeRow);
Render();
ForceCursor(++this._cursor);
}
else
{
RenderFrom(this._cursor);
ForceCursor(++this._cursor);
UpdateHomeRow(TextToScreenPos(this._cursor));
}
}
//
// Commands
//
private void CmdDone()
{
this._done = true;
}
private void CmdTabOrComplete()
{
bool complete = false;
if (AutoCompleteEvent != null)
{
if (TabAtStartCompletes) complete = true;
else
{
for (int i = 0; i < this._cursor; i++)
{
if (!Char.IsWhiteSpace(this._text[i]))
{
complete = true;
break;
}
}
}
if (complete)
{
Completion completion = AutoCompleteEvent(this._text.ToString(), this._cursor);
string[] completions = completion.Result;
if (completions == null) return;
int ncompletions = completions.Length;
if (ncompletions == 0) return;
if (completions.Length == 1)
{
InsertTextAtCursor(completions[0]);
}
else
{
int last = -1;
for (int p = 0; p < completions[0].Length; p++)
{
char c = completions[0][p];
for (int i = 1; i < ncompletions; i++)
{
if (completions[i].Length < p)
{
goto mismatch;
}
if (completions[i][p] != c)
{
goto mismatch;
}
}
last = p;
}
mismatch:
if (last != -1)
{
// Needed to insert renderafter and cmdkilltoeof to fixup for NT
RenderAfter(completion.ReplacementIndex);
InsertTextAtCursor(completions[0].Substring(0, last + 1));
CmdKillToEOF();
}
Console.WriteLine();
var fg = Console.ForegroundColor;
try
{
Console.ForegroundColor = ConsoleColor.Yellow;
foreach (string s in completions)
{
Console.Write(completion.Prefix);
Console.Write(s);
Console.Write(' ');
}
}
finally
{
Console.ForegroundColor = fg;
}
Console.WriteLine();
Render();
ForceCursor(this._cursor);
}
}
else HandleChar('\t');
}
else HandleChar('\t');
}
private void CmdHome()
{
UpdateCursor(0);
}
private void CmdEnd()
{
UpdateCursor(this._text.Length);
}
private void CmdLeft()
{
if (this._cursor == 0) return;
UpdateCursor(this._cursor - 1);
}
private void CmdBackwardWord()
{
int p = WordBackward(this._cursor);
if (p == -1) return;
UpdateCursor(p);
}
private void CmdForwardWord()
{
int p = WordForward(this._cursor);
if (p == -1) return;
UpdateCursor(p);
}
private void CmdRight()
{
if (this._cursor == this._text.Length) return;
UpdateCursor(this._cursor + 1);
}
private void RenderAfter(int p)
{
ForceCursor(p);
RenderFrom(p);
ForceCursor(this._cursor);
}
private void CmdBackspace()
{
if (this._cursor == 0) return;
this._text.Remove(--this._cursor, 1);
ComputeRendered();
RenderAfter(this._cursor);
}
private void CmdDeleteChar()
{
// If there is no input, this behaves like EOF
if (this._text.Length == 0)
{
this._done = true;
this._text = null;
Console.WriteLine();
return;
}
if (this._cursor == this._text.Length) return;
this._text.Remove(this._cursor, 1);
ComputeRendered();
RenderAfter(this._cursor);
}
private void MatchParen() {
int p = this._cursor;
if (p >= this._text.Length) return;
int i = p;
if (this._text[p] == ')') {
int count = 1;
while (p-- > 0) {
if (this._text[p] == '(') {
if (--count == 0) {
break;
}
}
else if (this._text[p] == ')') {
count++;
}
}
if (count == 0) {
this._cursor = p;
RenderAfter(this._cursor);
}
}
else if (this._text[p] == '(') {
int count = 1;
while (p++ < this._text.Length) {
if (this._text[p] == ')') {
if (--count == 0) {
break;
}
}
else if (this._text[p] == '(') {
count++;
}
}
if (count == 0) {
this._cursor = p;
RenderAfter(this._cursor);
}
}
}
private int WordForward(int p)
{
if (p >= this._text.Length) return -1;
int i = p;
if (Char.IsPunctuation(this._text[p]) || Char.IsWhiteSpace(this._text[p]))
{
for (; i < this._text.Length; i++)
{
if (Char.IsLetterOrDigit(this._text[i])) break;
}
for (; i < this._text.Length; i++)
{
if (!Char.IsLetterOrDigit(this._text[i])) break;
}
}
else
{
for (; i < this._text.Length; i++)
{
if (!Char.IsLetterOrDigit(this._text[i])) break;
}
}
if (i != p) return i;
return -1;
}
private int WordBackward(int p)
{
if (p == 0) return -1;
int i = p - 1;
if (i == 0) return 0;
if (Char.IsPunctuation(this._text[i]) || Char.IsSymbol(this._text[i]) || Char.IsWhiteSpace(this._text[i]))
{
for (; i >= 0; i--)
{
if (Char.IsLetterOrDigit(this._text[i])) break;
}
for (; i >= 0; i--)
{
if (!Char.IsLetterOrDigit(this._text[i])) break;
}
}
else
{
for (; i >= 0; i--)
{
if (!Char.IsLetterOrDigit(this._text[i])) break;
}
}
i++;
if (i != p) return i;
return -1;
}
private void CmdDeleteWord()
{
int pos = WordForward(this._cursor);
if (pos == -1) return;
string k = this._text.ToString(this._cursor, pos - this._cursor);
if (this._lastHandler == CmdDeleteWord) this._killBuffer = this._killBuffer + k;
else this._killBuffer = k;
this._text.Remove(this._cursor, pos - this._cursor);
ComputeRendered();
RenderAfter(this._cursor);
}
private void CmdDeleteBackword()
{
int pos = WordBackward(this._cursor);
if (pos == -1) return;
string k = this._text.ToString(pos, this._cursor - pos);
if (this._lastHandler == CmdDeleteBackword) this._killBuffer = k + this._killBuffer;
else this._killBuffer = k;
this._text.Remove(pos, this._cursor - pos);
ComputeRendered();
RenderAfter(pos);
}
//
// Adds the current line to the history if needed
//
private void HistoryUpdateLine()
{
this._history.Update(this._text.ToString());
}
private void CmdHistoryPrev()
{
if (!this._history.PreviousAvailable()) return;
HistoryUpdateLine();
SetText(this._history.Previous());
}
// Edit the current cmdlet in Vim
// BUGBUGBUG - this shouldn't be hardcoded to vim.
private void CmdVisualEdit()
{
string tempFile = System.IO.Path.GetTempFileName() + ".tiny";
System.IO.File.WriteAllText(tempFile, this._text.ToString());
var process = System.Diagnostics.Process.Start("vim", " -n " + tempFile);
process.WaitForExit();
string newText = System.IO.File.ReadAllText(tempFile).Trim('\n');
System.IO.File.Delete(tempFile);
SetText(newText);
CmdDone();
}
private void CmdHistoryNext()
{
if (!this._history.NextAvailable()) return;
this._history.Update(this._text.ToString());
SetText(this._history.Next());
}
private void CmdKillToEOF()
{
this._killBuffer = this._text.ToString(this._cursor, this._text.Length - this._cursor);
this._text.Length = this._cursor;
ComputeRendered();
RenderAfter(this._cursor);
}
private void CmdClearBuffer()
{
CmdHome();
CmdKillToEOF();
}
private void CmdYank()
{
InsertTextAtCursor(this._killBuffer);
}
private void InsertTextAtCursor(string str)
{
int prevLines = LineCount;
this._text.Insert(this._cursor, str);
ComputeRendered();
if (prevLines != LineCount)
{
Console.SetCursorPosition(0, this._homeRow);
Render();
this._cursor += str.Length;
ForceCursor(this._cursor);
}
else
{
RenderFrom(this._cursor);
this._cursor += str.Length;
ForceCursor(this._cursor);
UpdateHomeRow(TextToScreenPos(this._cursor));
}
}
private void SetSearchPrompt(string s)
{
SetPrompt("(reverse-i-search) " + s + "': ");
}
private void ReverseSearch()
{
int p;
if (this._cursor == this._text.Length)
{
// The cursor is at the end of the string
p = this._text.ToString().LastIndexOf(this._search, StringComparison.OrdinalIgnoreCase);
if (p != -1)
{
this._matchAt = p;
this._cursor = p;
ForceCursor(this._cursor);
return;
}
}
else
{
// The cursor is somewhere in the middle of the string
int start = (this._cursor == this._matchAt) ? this._cursor - 1 : this._cursor;
if (start != -1)
{
p = this._text.ToString().LastIndexOf(this._search, start, StringComparison.OrdinalIgnoreCase);
if (p != -1)
{
this._matchAt = p;
this._cursor = p;
ForceCursor(this._cursor);
return;
}
}
}
// Need to search backwards in history
HistoryUpdateLine();
string s = this._history.SearchBackward(this._search);
if (s != null)
{
this._matchAt = -1;
SetText(s);
ReverseSearch();
}
}
private void CmdReverseSearch()
{
if (this._searching == 0)
{
this._matchAt = -1;
this._lastSearch = this._search;
this._searching = -1;
this._search = string.Empty;
SetSearchPrompt(string.Empty);
}
else
{
if (this._search == "")
{
if (!string.IsNullOrEmpty(this._lastSearch))
{
this._search = this._lastSearch;
SetSearchPrompt(this._search);
ReverseSearch();
}
return;
}
ReverseSearch();
}
}
private void SearchAppend(char c)
{
this._search = this._search + c;
SetSearchPrompt(this._search);
//
// If the new typed data still matches the current text, stay here
//
if (this._cursor < this._text.Length)
{
string r = this._text.ToString(this._cursor, this._text.Length - this._cursor);
if (r.StartsWith(this._search)) return;
}
ReverseSearch();
}
private void CmdRefresh()
{
Console.Clear();
this._maxRendered = 0;
Render();
ForceCursor(this._cursor);
}
private void InterruptEdit(object sender, ConsoleCancelEventArgs a)
{
// Do not abort our program:
a.Cancel = true;
// BUGBUG thread abort is not supported in .Net Core
// Interrupt the editor
// this._editThread.Abort();
}
private void HandleChar(char c)
{
if (this._searching != 0) SearchAppend(c);
else InsertChar(c);
}
private void EditLoop()
{
ConsoleKeyInfo cki;
while (!this._done)
{
ConsoleModifiers mod;
cki = Console.ReadKey(true);
mod = cki.Modifiers;
if (cki.Key == ConsoleKey.Escape)
{
cki = Console.ReadKey(true);
//BUGBUG mod = ConsoleModifiers.Alt;
}