[getline] Improve the embedded sample
[mono.git] / mcs / tools / csharp / getline.cs
1 //
2 // getline.cs: A command line editor
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@novell.com)
6 //
7 // Copyright 2008 Novell, Inc.
8 // Copyright 2016 Xamarin Inc
9 //
10 // Completion wanted:
11 //
12 //   * Enable bash-like completion window the window as an option for non-GUI people?
13 //
14 //   * Continue completing when Backspace is used?
15 //
16 //   * Should we keep the auto-complete on "."?
17 //
18 //   * Completion produces an error if the value is not resolvable, we should hide those errors
19 //
20 // Dual-licensed under the terms of the MIT X11 license or the
21 // Apache License 2.0
22 //
23 // USE -define:DEMO to build this as a standalone file and test it
24 //
25 // TODO:
26 //    Enter an error (a = 1);  Notice how the prompt is in the wrong line
27 //              This is caused by Stderr not being tracked by System.Console.
28 //    Completion support
29 //    Why is Thread.Interrupt not working?   Currently I resort to Abort which is too much.
30 //
31 // Limitations in System.Console:
32 //    Console needs SIGWINCH support of some sort
33 //    Console needs a way of updating its position after things have been written
34 //    behind its back (P/Invoke puts for example).
35 //    System.Console needs to get the DELETE character, and report accordingly.
36 //
37 // Bug:
38 //   About 8 lines missing, type "Con<TAB>" and not enough lines are inserted at the bottom.
39 // 
40 //
41 using System;
42 using System.Text;
43 using System.IO;
44 using System.Threading;
45 using System.Reflection;
46
47 namespace Mono.Terminal {
48
49         public class LineEditor {
50
51                 public class Completion {
52                         public string [] Result;
53                         public string Prefix;
54
55                         public Completion (string prefix, string [] result)
56                         {
57                                 Prefix = prefix;
58                                 Result = result;
59                         }
60                 }
61                 
62                 public delegate Completion AutoCompleteHandler (string text, int pos);
63
64                 // null does nothing, "csharp" uses some heuristics that make sense for C#
65                 public string HeuristicsMode;
66                 
67                 //static StreamWriter log;
68                 
69                 // The text being edited.
70                 StringBuilder text;
71
72                 // The text as it is rendered (replaces (char)1 with ^A on display for example).
73                 StringBuilder rendered_text;
74
75                 // The prompt specified, and the prompt shown to the user.
76                 string prompt;
77                 string shown_prompt;
78                 
79                 // The current cursor position, indexes into "text", for an index
80                 // into rendered_text, use TextToRenderPos
81                 int cursor;
82
83                 // The row where we started displaying data.
84                 int home_row;
85
86                 // The maximum length that has been displayed on the screen
87                 int max_rendered;
88
89                 // If we are done editing, this breaks the interactive loop
90                 bool done = false;
91
92                 // The thread where the Editing started taking place
93                 Thread edit_thread;
94
95                 // Our object that tracks history
96                 History history;
97
98                 // The contents of the kill buffer (cut/paste in Emacs parlance)
99                 string kill_buffer = "";
100
101                 // The string being searched for
102                 string search;
103                 string last_search;
104
105                 // whether we are searching (-1= reverse; 0 = no; 1 = forward)
106                 int searching;
107
108                 // The position where we found the match.
109                 int match_at;
110                 
111                 // Used to implement the Kill semantics (multiple Alt-Ds accumulate)
112                 KeyHandler last_handler;
113
114                 // If we have a popup completion, this is not null and holds the state.
115                 CompletionState current_completion;
116
117                 // If this is set, it contains an escape sequence to reset the Unix colors to the ones that were used on startup
118                 static byte [] unix_reset_colors;
119
120                 // This contains a raw stream pointing to stdout, used to bypass the TermInfoDriver
121                 static Stream unix_raw_output;
122                 
123                 delegate void KeyHandler ();
124                 
125                 struct Handler {
126                         public ConsoleKeyInfo CKI;
127                         public KeyHandler KeyHandler;
128                         public bool ResetCompletion;
129                         
130                         public Handler (ConsoleKey key, KeyHandler h, bool resetCompletion = true)
131                         {
132                                 CKI = new ConsoleKeyInfo ((char) 0, key, false, false, false);
133                                 KeyHandler = h;
134                                 ResetCompletion = resetCompletion;
135                         }
136
137                         public Handler (char c, KeyHandler h, bool resetCompletion = true)
138                         {
139                                 KeyHandler = h;
140                                 // Use the "Zoom" as a flag that we only have a character.
141                                 CKI = new ConsoleKeyInfo (c, ConsoleKey.Zoom, false, false, false);
142                                 ResetCompletion = resetCompletion;
143                         }
144
145                         public Handler (ConsoleKeyInfo cki, KeyHandler h, bool resetCompletion = true)
146                         {
147                                 CKI = cki;
148                                 KeyHandler = h;
149                                 ResetCompletion = resetCompletion;
150                         }
151                         
152                         public static Handler Control (char c, KeyHandler h, bool resetCompletion = true)
153                         {
154                                 return new Handler ((char) (c - 'A' + 1), h, resetCompletion);
155                         }
156
157                         public static Handler Alt (char c, ConsoleKey k, KeyHandler h)
158                         {
159                                 ConsoleKeyInfo cki = new ConsoleKeyInfo ((char) c, k, false, true, false);
160                                 return new Handler (cki, h);
161                         }
162                 }
163
164                 /// <summary>
165                 ///   Invoked when the user requests auto-completion using the tab character
166                 /// </summary>
167                 /// <remarks>
168                 ///    The result is null for no values found, an array with a single
169                 ///    string, in that case the string should be the text to be inserted
170                 ///    for example if the word at pos is "T", the result for a completion
171                 ///    of "ToString" should be "oString", not "ToString".
172                 ///
173                 ///    When there are multiple results, the result should be the full
174                 ///    text
175                 /// </remarks>
176                 public AutoCompleteHandler AutoCompleteEvent;
177
178                 static Handler [] handlers;
179
180                 public LineEditor (string name) : this (name, 10) { }
181                 
182                 public LineEditor (string name, int histsize)
183                 {
184                         handlers = new Handler [] {
185                                 new Handler (ConsoleKey.Home,       CmdHome),
186                                 new Handler (ConsoleKey.End,        CmdEnd),
187                                 new Handler (ConsoleKey.LeftArrow,  CmdLeft),
188                                 new Handler (ConsoleKey.RightArrow, CmdRight),
189                                 new Handler (ConsoleKey.UpArrow,    CmdUp, resetCompletion: false),
190                                 new Handler (ConsoleKey.DownArrow,  CmdDown, resetCompletion: false),
191                                 new Handler (ConsoleKey.Enter,      CmdDone, resetCompletion: false),
192                                 new Handler (ConsoleKey.Backspace,  CmdBackspace, resetCompletion: false),
193                                 new Handler (ConsoleKey.Delete,     CmdDeleteChar),
194                                 new Handler (ConsoleKey.Tab,        CmdTabOrComplete, resetCompletion: false),
195                                 
196                                 // Emacs keys
197                                 Handler.Control ('A', CmdHome),
198                                 Handler.Control ('E', CmdEnd),
199                                 Handler.Control ('B', CmdLeft),
200                                 Handler.Control ('F', CmdRight),
201                                 Handler.Control ('P', CmdUp, resetCompletion: false),
202                                 Handler.Control ('N', CmdDown, resetCompletion: false),
203                                 Handler.Control ('K', CmdKillToEOF),
204                                 Handler.Control ('Y', CmdYank),
205                                 Handler.Control ('D', CmdDeleteChar),
206                                 Handler.Control ('L', CmdRefresh),
207                                 Handler.Control ('R', CmdReverseSearch),
208                                 Handler.Control ('G', delegate {} ),
209                                 Handler.Alt ('B', ConsoleKey.B, CmdBackwardWord),
210                                 Handler.Alt ('F', ConsoleKey.F, CmdForwardWord),
211                                 
212                                 Handler.Alt ('D', ConsoleKey.D, CmdDeleteWord),
213                                 Handler.Alt ((char) 8, ConsoleKey.Backspace, CmdDeleteBackword),
214                                 
215                                 // DEBUG
216                                 //Handler.Control ('T', CmdDebug),
217
218                                 // quote
219                                 Handler.Control ('Q', delegate { HandleChar (Console.ReadKey (true).KeyChar); })
220                         };
221
222                         rendered_text = new StringBuilder ();
223                         text = new StringBuilder ();
224
225                         history = new History (name, histsize);
226
227                         GetUnixConsoleReset ();
228                         //if (File.Exists ("log"))File.Delete ("log");
229                         //log = File.CreateText ("log"); 
230                 }
231
232                 // On Unix, there is a "default" color which is not represented by any colors in
233                 // ConsoleColor and it is not possible to set is by setting the ForegroundColor or
234                 // BackgroundColor properties, so we have to use the terminfo driver in Mono to
235                 // fetch these values
236
237                 void GetUnixConsoleReset ()
238                 {
239                         //
240                         // On Unix, we want to be able to reset the color for the pop-up completion
241                         //
242                         int p = (int) Environment.OSVersion.Platform;
243                         var is_unix = (p == 4) || (p == 128);
244                         if (!is_unix)
245                                 return;
246
247                         // Sole purpose of this call is to initialize the Terminfo driver
248                         var x = Console.CursorLeft;
249                         
250                         try {
251                                 var terminfo_driver = Type.GetType ("System.ConsoleDriver")?.GetField ("driver", BindingFlags.Static | BindingFlags.NonPublic)?.GetValue (null);
252                                 if (terminfo_driver == null)
253                                         return;
254
255                                 var unix_reset_colors_str = (terminfo_driver?.GetType ()?.GetField ("origPair", BindingFlags.Instance | BindingFlags.NonPublic))?.GetValue (terminfo_driver) as string;
256                                 
257                                 if (unix_reset_colors_str != null)
258                                         unix_reset_colors = Encoding.UTF8.GetBytes ((string)unix_reset_colors_str);
259                                 unix_raw_output = Console.OpenStandardOutput ();
260                         } catch (Exception e){
261                                 Console.WriteLine ("Error: " + e);
262                         }
263                 }
264                 
265
266                 void CmdDebug ()
267                 {
268                         history.Dump ();
269                         Console.WriteLine ();
270                         Render ();
271                 }
272
273                 void Render ()
274                 {
275                         Console.Write (shown_prompt);
276                         Console.Write (rendered_text);
277
278                         int max = System.Math.Max (rendered_text.Length + shown_prompt.Length, max_rendered);
279                         
280                         for (int i = rendered_text.Length + shown_prompt.Length; i < max_rendered; i++)
281                                 Console.Write (' ');
282                         max_rendered = shown_prompt.Length + rendered_text.Length;
283
284                         // Write one more to ensure that we always wrap around properly if we are at the
285                         // end of a line.
286                         Console.Write (' ');
287
288                         UpdateHomeRow (max);
289                 }
290
291                 void UpdateHomeRow (int screenpos)
292                 {
293                         int lines = 1 + (screenpos / Console.WindowWidth);
294
295                         home_row = Console.CursorTop - (lines - 1);
296                         if (home_row < 0)
297                                 home_row = 0;
298                 }
299                 
300
301                 void RenderFrom (int pos)
302                 {
303                         int rpos = TextToRenderPos (pos);
304                         int i;
305                         
306                         for (i = rpos; i < rendered_text.Length; i++)
307                                 Console.Write (rendered_text [i]);
308
309                         if ((shown_prompt.Length + rendered_text.Length) > max_rendered)
310                                 max_rendered = shown_prompt.Length + rendered_text.Length;
311                         else {
312                                 int max_extra = max_rendered - shown_prompt.Length;
313                                 for (; i < max_extra; i++)
314                                         Console.Write (' ');
315                         }
316                 }
317
318                 void ComputeRendered ()
319                 {
320                         rendered_text.Length = 0;
321
322                         for (int i = 0; i < text.Length; i++){
323                                 int c = (int) text [i];
324                                 if (c < 26){
325                                         if (c == '\t')
326                                                 rendered_text.Append ("    ");
327                                         else {
328                                                 rendered_text.Append ('^');
329                                                 rendered_text.Append ((char) (c + (int) 'A' - 1));
330                                         }
331                                 } else
332                                         rendered_text.Append ((char)c);
333                         }
334                 }
335
336                 int TextToRenderPos (int pos)
337                 {
338                         int p = 0;
339
340                         for (int i = 0; i < pos; i++){
341                                 int c;
342
343                                 c = (int) text [i];
344                                 
345                                 if (c < 26){
346                                         if (c == 9)
347                                                 p += 4;
348                                         else
349                                                 p += 2;
350                                 } else
351                                         p++;
352                         }
353
354                         return p;
355                 }
356
357                 int TextToScreenPos (int pos)
358                 {
359                         return shown_prompt.Length + TextToRenderPos (pos);
360                 }
361                 
362                 string Prompt {
363                         get { return prompt; }
364                         set { prompt = value; }
365                 }
366
367                 int LineCount {
368                         get {
369                                 return (shown_prompt.Length + rendered_text.Length)/Console.WindowWidth;
370                         }
371                 }
372                 
373                 void ForceCursor (int newpos)
374                 {
375                         cursor = newpos;
376
377                         int actual_pos = shown_prompt.Length + TextToRenderPos (cursor);
378                         int row = home_row + (actual_pos/Console.WindowWidth);
379                         int col = actual_pos % Console.WindowWidth;
380
381                         if (row >= Console.BufferHeight)
382                                 row = Console.BufferHeight-1;
383                         Console.SetCursorPosition (col, row);
384                         
385                         //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);
386                         //log.Flush ();
387                 }
388
389                 void UpdateCursor (int newpos)
390                 {
391                         if (cursor == newpos)
392                                 return;
393
394                         ForceCursor (newpos);
395                 }
396
397                 void InsertChar (char c)
398                 {
399                         int prev_lines = LineCount;
400                         text = text.Insert (cursor, c);
401                         ComputeRendered ();
402                         if (prev_lines != LineCount){
403
404                                 Console.SetCursorPosition (0, home_row);
405                                 Render ();
406                                 ForceCursor (++cursor);
407                         } else {
408                                 RenderFrom (cursor);
409                                 ForceCursor (++cursor);
410                                 UpdateHomeRow (TextToScreenPos (cursor));
411                         }
412                 }
413
414                 static void SaveExcursion (Action code)
415                 {
416                         var saved_col = Console.CursorLeft;
417                         var saved_row = Console.CursorTop;
418                         var saved_fore = Console.ForegroundColor;
419                         var saved_back = Console.BackgroundColor;
420                         
421                         code ();
422                         
423                         Console.CursorLeft = saved_col;
424                         Console.CursorTop = saved_row;
425                         if (unix_reset_colors != null){
426                                 unix_raw_output.Write (unix_reset_colors, 0, unix_reset_colors.Length);
427                         } else {
428                                 Console.ForegroundColor = saved_fore;
429                                 Console.BackgroundColor = saved_back;
430                         }
431                 }
432                 
433                 class CompletionState {
434                         public string Prefix;
435                         public string [] Completions;
436                         public int Col, Row, Width, Height;
437                         int selected_item, top_item;
438
439                         public CompletionState (int col, int row, int width, int height)
440                         {
441                                 Col = col;
442                                 Row = row;
443                                 Width = width;
444                                 Height = height;
445
446                                 if (Col < 0)
447                                         throw new ArgumentException ("Cannot be less than zero" + Col, "Col");
448                                 if (Row < 0)
449                                         throw new ArgumentException ("Cannot be less than zero", "Row");
450                                 if (Width < 1)
451                                         throw new ArgumentException ("Cannot be less than one", "Width");
452                                 if (Height < 1)
453                                         throw new ArgumentException ("Cannot be less than one", "Height");
454                                 
455                         }
456                         
457                         void DrawSelection ()
458                         {
459                                 for (int r = 0; r < Height; r++){
460                                         int item_idx = top_item + r;
461                                         bool selected = (item_idx == selected_item);
462                                         
463                                         Console.ForegroundColor = selected ? ConsoleColor.Black : ConsoleColor.Gray;
464                                         Console.BackgroundColor = selected ? ConsoleColor.Cyan : ConsoleColor.Blue;
465
466                                         var item = Prefix + Completions [item_idx];
467                                         if (item.Length > Width)
468                                                 item = item.Substring (0, Width);
469
470                                         Console.CursorLeft = Col;
471                                         Console.CursorTop = Row + r;
472                                         Console.Write (item);
473                                         for (int space = item.Length; space <= Width; space++)
474                                                 Console.Write (" ");
475                                 }
476                         }
477
478                         public string Current {
479                                 get {
480                                         return Completions [selected_item];
481                                 }
482                         }
483                         
484                         public void Show ()
485                         {
486                                 SaveExcursion (DrawSelection);
487                         }
488
489                         public void SelectNext ()
490                         {
491                                 if (selected_item+1 < Completions.Length){
492                                         selected_item++;
493                                         if (selected_item - top_item >= Height)
494                                                 top_item++;
495                                         SaveExcursion (DrawSelection);
496                                 }
497                         }
498
499                         public void SelectPrevious ()
500                         {
501                                 if (selected_item > 0){
502                                         selected_item--;
503                                         if (selected_item < top_item)
504                                                 top_item = selected_item;
505                                         SaveExcursion (DrawSelection);
506                                 }
507                         }
508
509                         void Clear ()
510                         {
511                                 for (int r = 0; r < Height; r++){
512                                         Console.CursorLeft = Col;
513                                         Console.CursorTop = Row + r;
514                                         for (int space = 0; space <= Width; space++)
515                                                 Console.Write (" ");
516                                 }
517                         }
518                         
519                         public void Remove ()
520                         {
521                                 SaveExcursion (Clear);
522                         }
523                 }
524
525                 void ShowCompletions (string prefix, string [] completions)
526                 {
527                         // Ensure we have space, determine window size
528                         int window_height = System.Math.Min (completions.Length, Console.WindowHeight/5);
529                         int target_line = Console.WindowHeight-window_height-1;
530                         if (Console.CursorTop > target_line){
531                                 var saved_left = Console.CursorLeft;
532                                 var delta = Console.CursorTop-target_line;
533                                 Console.CursorLeft = 0;
534                                 Console.CursorTop = Console.WindowHeight-1;
535                                 for (int i = 0; i < delta+1; i++){
536                                         for (int c = Console.WindowWidth; c > 0; c--)
537                                                 Console.Write (" "); // To debug use ("{0}", i%10);
538                                 }
539                                 Console.CursorTop = target_line;
540                                 Console.CursorLeft = 0;
541                                 Render ();
542                         }
543
544                         const int MaxWidth = 50;
545                         int window_width = 12;
546                         int plen = prefix.Length;
547                         foreach (var s in completions)
548                                 window_width = System.Math.Max (plen + s.Length, window_width);
549                         window_width = System.Math.Min (window_width, MaxWidth);
550
551                         if (current_completion == null){
552                                 int left = Console.CursorLeft-prefix.Length;
553                                 
554                                 if (left + window_width + 1 >= Console.WindowWidth)
555                                         left = Console.WindowWidth-window_width-1;
556                                 
557                                 current_completion = new CompletionState (left, Console.CursorTop+1, window_width, window_height) {
558                                         Prefix = prefix,
559                                         Completions = completions,
560                                 };
561                         } else {
562                                 current_completion.Prefix = prefix;
563                                 current_completion.Completions = completions;
564                         }
565                         current_completion.Show ();
566                         Console.CursorLeft = 0;
567                 }
568
569                 void HideCompletions ()
570                 {
571                         if (current_completion == null)
572                                 return;
573                         current_completion.Remove ();
574                         current_completion = null;
575                 }
576
577                 //
578                 // Triggers the completion engine, if insertBestMatch is true, then this will
579                 // insert the best match found, this behaves like the shell "tab" which will
580                 // complete as much as possible given the options.
581                 //
582                 void Complete ()
583                 {
584                         Completion completion = AutoCompleteEvent (text.ToString (), cursor);
585                         string [] completions = completion.Result;
586                         if (completions == null){
587                                 HideCompletions ();
588                                 return;
589                         }
590                                         
591                         int ncompletions = completions.Length;
592                         if (ncompletions == 0){
593                                 HideCompletions ();
594                                 return;
595                         }
596                                         
597                         if (completions.Length == 1){
598                                 InsertTextAtCursor (completions [0]);
599                         } else {
600                                 int last = -1;
601
602                                 for (int p = 0; p < completions [0].Length; p++){
603                                         char c = completions [0][p];
604
605
606                                         for (int i = 1; i < ncompletions; i++){
607                                                 if (completions [i].Length < p)
608                                                         goto mismatch;
609                                                         
610                                                 if (completions [i][p] != c){
611                                                         goto mismatch;
612                                                 }
613                                         }
614                                         last = p;
615                                 }
616                         mismatch:
617                                 var prefix = completion.Prefix;
618                                 if (last != -1){
619                                         InsertTextAtCursor (completions [0].Substring (0, last+1));
620
621                                         // Adjust the completions to skip the common prefix
622                                         prefix += completions [0].Substring (0, last+1);
623                                         for (int i = 0; i < completions.Length; i++)
624                                                 completions [i] = completions [i].Substring (last+1);
625                                 }
626                                 ShowCompletions (prefix, completions);
627                                 Render ();
628                                 ForceCursor (cursor);
629                         }
630                 }
631
632                 //
633                 // When the user has triggered a completion window, this will try to update
634                 // the contents of it.   The completion window is assumed to be hidden at this
635                 // point
636                 // 
637                 void UpdateCompletionWindow ()
638                 {
639                         if (current_completion != null)
640                                 throw new Exception ("This method should only be called if the window has been hidden");
641                         
642                         Completion completion = AutoCompleteEvent (text.ToString (), cursor);
643                         string [] completions = completion.Result;
644                         if (completions == null)
645                                 return;
646                                         
647                         int ncompletions = completions.Length;
648                         if (ncompletions == 0)
649                                 return;
650                         
651                         ShowCompletions (completion.Prefix, completion.Result);
652                         Render ();
653                         ForceCursor (cursor);
654                 }
655                 
656                 
657                 //
658                 // Commands
659                 //
660                 void CmdDone ()
661                 {
662                         if (current_completion != null){
663                                 InsertTextAtCursor (current_completion.Current);
664                                 HideCompletions ();
665                                 return;
666                         }
667                         done = true;
668                 }
669
670                 void CmdTabOrComplete ()
671                 {
672                         bool complete = false;
673
674                         if (AutoCompleteEvent != null){
675                                 if (TabAtStartCompletes)
676                                         complete = true;
677                                 else {
678                                         for (int i = 0; i < cursor; i++){
679                                                 if (!Char.IsWhiteSpace (text [i])){
680                                                         complete = true;
681                                                         break;
682                                                 }
683                                         }
684                                 }
685
686                                 if (complete)
687                                         Complete ();
688                                 else
689                                         HandleChar ('\t');
690                         } else
691                                 HandleChar ('t');
692                 }
693                 
694                 void CmdHome ()
695                 {
696                         UpdateCursor (0);
697                 }
698
699                 void CmdEnd ()
700                 {
701                         UpdateCursor (text.Length);
702                 }
703                 
704                 void CmdLeft ()
705                 {
706                         if (cursor == 0)
707                                 return;
708
709                         UpdateCursor (cursor-1);
710                 }
711
712                 void CmdBackwardWord ()
713                 {
714                         int p = WordBackward (cursor);
715                         if (p == -1)
716                                 return;
717                         UpdateCursor (p);
718                 }
719
720                 void CmdForwardWord ()
721                 {
722                         int p = WordForward (cursor);
723                         if (p == -1)
724                                 return;
725                         UpdateCursor (p);
726                 }
727
728                 void CmdRight ()
729                 {
730                         if (cursor == text.Length)
731                                 return;
732
733                         UpdateCursor (cursor+1);
734                 }
735
736                 void RenderAfter (int p)
737                 {
738                         ForceCursor (p);
739                         RenderFrom (p);
740                         ForceCursor (cursor);
741                 }
742                 
743                 void CmdBackspace ()
744                 {
745                         if (cursor == 0)
746                                 return;
747
748                         bool completing = current_completion != null;
749                         HideCompletions ();
750                         
751                         text.Remove (--cursor, 1);
752                         ComputeRendered ();
753                         RenderAfter (cursor);
754                         if (completing)
755                                 UpdateCompletionWindow ();
756                 }
757
758                 void CmdDeleteChar ()
759                 {
760                         // If there is no input, this behaves like EOF
761                         if (text.Length == 0){
762                                 done = true;
763                                 text = null;
764                                 Console.WriteLine ();
765                                 return;
766                         }
767                         
768                         if (cursor == text.Length)
769                                 return;
770                         text.Remove (cursor, 1);
771                         ComputeRendered ();
772                         RenderAfter (cursor);
773                 }
774
775                 int WordForward (int p)
776                 {
777                         if (p >= text.Length)
778                                 return -1;
779
780                         int i = p;
781                         if (Char.IsPunctuation (text [p]) || Char.IsSymbol (text [p]) || Char.IsWhiteSpace (text[p])){
782                                 for (; i < text.Length; i++){
783                                         if (Char.IsLetterOrDigit (text [i]))
784                                             break;
785                                 }
786                                 for (; i < text.Length; i++){
787                                         if (!Char.IsLetterOrDigit (text [i]))
788                                             break;
789                                 }
790                         } else {
791                                 for (; i < text.Length; i++){
792                                         if (!Char.IsLetterOrDigit (text [i]))
793                                             break;
794                                 }
795                         }
796                         if (i != p)
797                                 return i;
798                         return -1;
799                 }
800
801                 int WordBackward (int p)
802                 {
803                         if (p == 0)
804                                 return -1;
805
806                         int i = p-1;
807                         if (i == 0)
808                                 return 0;
809                         
810                         if (Char.IsPunctuation (text [i]) || Char.IsSymbol (text [i]) || Char.IsWhiteSpace (text[i])){
811                                 for (; i >= 0; i--){
812                                         if (Char.IsLetterOrDigit (text [i]))
813                                                 break;
814                                 }
815                                 for (; i >= 0; i--){
816                                         if (!Char.IsLetterOrDigit (text[i]))
817                                                 break;
818                                 }
819                         } else {
820                                 for (; i >= 0; i--){
821                                         if (!Char.IsLetterOrDigit (text [i]))
822                                                 break;
823                                 }
824                         }
825                         i++;
826                         
827                         if (i != p)
828                                 return i;
829
830                         return -1;
831                 }
832                 
833                 void CmdDeleteWord ()
834                 {
835                         int pos = WordForward (cursor);
836
837                         if (pos == -1)
838                                 return;
839
840                         string k = text.ToString (cursor, pos-cursor);
841                         
842                         if (last_handler == CmdDeleteWord)
843                                 kill_buffer = kill_buffer + k;
844                         else
845                                 kill_buffer = k;
846                         
847                         text.Remove (cursor, pos-cursor);
848                         ComputeRendered ();
849                         RenderAfter (cursor);
850                 }
851                 
852                 void CmdDeleteBackword ()
853                 {
854                         int pos = WordBackward (cursor);
855                         if (pos == -1)
856                                 return;
857
858                         string k = text.ToString (pos, cursor-pos);
859                         
860                         if (last_handler == CmdDeleteBackword)
861                                 kill_buffer = k + kill_buffer;
862                         else
863                                 kill_buffer = k;
864                         
865                         text.Remove (pos, cursor-pos);
866                         ComputeRendered ();
867                         RenderAfter (pos);
868                 }
869                 
870                 //
871                 // Adds the current line to the history if needed
872                 //
873                 void HistoryUpdateLine ()
874                 {
875                         history.Update (text.ToString ());
876                 }
877                 
878                 void CmdHistoryPrev ()
879                 {
880                         if (!history.PreviousAvailable ())
881                                 return;
882
883                         HistoryUpdateLine ();
884                         
885                         SetText (history.Previous ());
886                 }
887
888                 void CmdHistoryNext ()
889                 {
890                         if (!history.NextAvailable())
891                                 return;
892
893                         history.Update (text.ToString ());
894                         SetText (history.Next ());
895                         
896                 }
897
898                 void CmdUp ()
899                 {
900                         if (current_completion == null)
901                                 CmdHistoryPrev ();
902                         else
903                                 current_completion.SelectPrevious ();
904                 }
905
906                 void CmdDown ()
907                 {
908                         if (current_completion == null)
909                                 CmdHistoryNext ();
910                         else
911                                 current_completion.SelectNext ();
912                 }
913                 
914                 void CmdKillToEOF ()
915                 {
916                         kill_buffer = text.ToString (cursor, text.Length-cursor);
917                         text.Length = cursor;
918                         ComputeRendered ();
919                         RenderAfter (cursor);
920                 }
921
922                 void CmdYank ()
923                 {
924                         InsertTextAtCursor (kill_buffer);
925                 }
926
927                 void InsertTextAtCursor (string str)
928                 {
929                         int prev_lines = LineCount;
930                         text.Insert (cursor, str);
931                         ComputeRendered ();
932                         if (prev_lines != LineCount){
933                                 Console.SetCursorPosition (0, home_row);
934                                 Render ();
935                                 cursor += str.Length;
936                                 ForceCursor (cursor);
937                         } else {
938                                 RenderFrom (cursor);
939                                 cursor += str.Length;
940                                 ForceCursor (cursor);
941                                 UpdateHomeRow (TextToScreenPos (cursor));
942                         }
943                 }
944                 
945                 void SetSearchPrompt (string s)
946                 {
947                         SetPrompt ("(reverse-i-search)`" + s + "': ");
948                 }
949
950                 void ReverseSearch ()
951                 {
952                         int p;
953
954                         if (cursor == text.Length){
955                                 // The cursor is at the end of the string
956                                 
957                                 p = text.ToString ().LastIndexOf (search);
958                                 if (p != -1){
959                                         match_at = p;
960                                         cursor = p;
961                                         ForceCursor (cursor);
962                                         return;
963                                 }
964                         } else {
965                                 // The cursor is somewhere in the middle of the string
966                                 int start = (cursor == match_at) ? cursor - 1 : cursor;
967                                 if (start != -1){
968                                         p = text.ToString ().LastIndexOf (search, start);
969                                         if (p != -1){
970                                                 match_at = p;
971                                                 cursor = p;
972                                                 ForceCursor (cursor);
973                                                 return;
974                                         }
975                                 }
976                         }
977
978                         // Need to search backwards in history
979                         HistoryUpdateLine ();
980                         string s = history.SearchBackward (search);
981                         if (s != null){
982                                 match_at = -1;
983                                 SetText (s);
984                                 ReverseSearch ();
985                         }
986                 }
987                 
988                 void CmdReverseSearch ()
989                 {
990                         if (searching == 0){
991                                 match_at = -1;
992                                 last_search = search;
993                                 searching = -1;
994                                 search = "";
995                                 SetSearchPrompt ("");
996                         } else {
997                                 if (search == ""){
998                                         if (last_search != "" && last_search != null){
999                                                 search = last_search;
1000                                                 SetSearchPrompt (search);
1001
1002                                                 ReverseSearch ();
1003                                         }
1004                                         return;
1005                                 }
1006                                 ReverseSearch ();
1007                         } 
1008                 }
1009
1010                 void SearchAppend (char c)
1011                 {
1012                         search = search + c;
1013                         SetSearchPrompt (search);
1014
1015                         //
1016                         // If the new typed data still matches the current text, stay here
1017                         //
1018                         if (cursor < text.Length){
1019                                 string r = text.ToString (cursor, text.Length - cursor);
1020                                 if (r.StartsWith (search))
1021                                         return;
1022                         }
1023
1024                         ReverseSearch ();
1025                 }
1026                 
1027                 void CmdRefresh ()
1028                 {
1029                         Console.Clear ();
1030                         max_rendered = 0;
1031                         Render ();
1032                         ForceCursor (cursor);
1033                 }
1034
1035                 void InterruptEdit (object sender, ConsoleCancelEventArgs a)
1036                 {
1037                         // Do not abort our program:
1038                         a.Cancel = true;
1039
1040                         // Interrupt the editor
1041                         edit_thread.Abort();
1042                 }
1043
1044                 //
1045                 // Implements heuristics to show the completion window based on the mode
1046                 //
1047                 bool HeuristicAutoComplete (bool wasCompleting, char insertedChar)
1048                 {
1049                         if (HeuristicsMode == "csharp"){
1050                                 // csharp heuristics
1051                                 if (wasCompleting){
1052                                         if (insertedChar == ' '){
1053                                                 return false;
1054                                         }
1055                                         return true;
1056                                 } 
1057                                 // If we were not completing, determine if we want to now
1058                                 if (insertedChar == '.'){
1059                                         // Avoid completing for numbers "1.2" for example
1060                                         if (cursor > 1 && Char.IsDigit (text[cursor-2])){
1061                                                 for (int p = cursor-3; p >= 0; p--){
1062                                                         char c = text[p];
1063                                                         if (Char.IsDigit (c))
1064                                                                 continue;
1065                                                         if (c == '_')
1066                                                                 return true;
1067                                                         if (Char.IsLetter (c) || Char.IsPunctuation (c) || Char.IsSymbol (c) || Char.IsControl (c))
1068                                                                 return true;
1069                                                 }
1070                                                 return false;
1071                                         }
1072                                         return true;
1073                                 }
1074                         }
1075                         return false;
1076                 }
1077                 
1078                 void HandleChar (char c)
1079                 {
1080                         if (searching != 0)
1081                                 SearchAppend (c);
1082                         else {
1083                                 bool completing = current_completion != null;
1084                                 HideCompletions ();
1085
1086                                 InsertChar (c);
1087                                 if (HeuristicAutoComplete (completing, c))
1088                                         UpdateCompletionWindow ();
1089                         }
1090                 }
1091
1092                 void EditLoop ()
1093                 {
1094                         ConsoleKeyInfo cki;
1095
1096                         while (!done){
1097                                 ConsoleModifiers mod;
1098                                 
1099                                 cki = Console.ReadKey (true);
1100                                 if (cki.Key == ConsoleKey.Escape){
1101                                         if (current_completion != null){
1102                                                 HideCompletions ();
1103                                                 continue;
1104                                         } else {
1105                                                 cki = Console.ReadKey (true);
1106                                                 
1107                                                 mod = ConsoleModifiers.Alt;
1108                                         }
1109                                 } else
1110                                         mod = cki.Modifiers;
1111                                 
1112                                 bool handled = false;
1113
1114                                 foreach (Handler handler in handlers){
1115                                         ConsoleKeyInfo t = handler.CKI;
1116
1117                                         if (t.Key == cki.Key && t.Modifiers == mod){
1118                                                 handled = true;
1119                                                 if (handler.ResetCompletion)
1120                                                         HideCompletions ();
1121                                                 handler.KeyHandler ();
1122                                                 last_handler = handler.KeyHandler;
1123                                                 break;
1124                                         } else if (t.KeyChar == cki.KeyChar && t.Key == ConsoleKey.Zoom){
1125                                                 handled = true;
1126                                                 if (handler.ResetCompletion)
1127                                                         HideCompletions ();
1128
1129                                                 handler.KeyHandler ();
1130                                                 last_handler = handler.KeyHandler;
1131                                                 break;
1132                                         }
1133                                 }
1134                                 if (handled){
1135                                         if (searching != 0){
1136                                                 if (last_handler != CmdReverseSearch){
1137                                                         searching = 0;
1138                                                         SetPrompt (prompt);
1139                                                 }
1140                                         }
1141                                         continue;
1142                                 }
1143
1144                                 if (cki.KeyChar != (char) 0){
1145                                         HandleChar (cki.KeyChar);
1146                                 }
1147                         } 
1148                 }
1149
1150                 void InitText (string initial)
1151                 {
1152                         text = new StringBuilder (initial);
1153                         ComputeRendered ();
1154                         cursor = text.Length;
1155                         Render ();
1156                         ForceCursor (cursor);
1157                 }
1158
1159                 void SetText (string newtext)
1160                 {
1161                         Console.SetCursorPosition (0, home_row);
1162                         InitText (newtext);
1163                 }
1164
1165                 void SetPrompt (string newprompt)
1166                 {
1167                         shown_prompt = newprompt;
1168                         Console.SetCursorPosition (0, home_row);
1169                         Render ();
1170                         ForceCursor (cursor);
1171                 }
1172                 
1173                 public string Edit (string prompt, string initial)
1174                 {
1175                         edit_thread = Thread.CurrentThread;
1176                         searching = 0;
1177                         Console.CancelKeyPress += InterruptEdit;
1178                                                 
1179                         done = false;
1180                         history.CursorToEnd ();
1181                         max_rendered = 0;
1182                         
1183                         Prompt = prompt;
1184                         shown_prompt = prompt;
1185                         InitText (initial);
1186                         history.Append (initial);
1187
1188                         do {
1189                                 try {
1190                                         EditLoop ();
1191                                 } catch (ThreadAbortException){
1192                                         searching = 0;
1193                                         Thread.ResetAbort ();
1194                                         Console.WriteLine ();
1195                                         SetPrompt (prompt);
1196                                         SetText ("");
1197                                 }
1198                         } while (!done);
1199                         Console.WriteLine ();
1200                         
1201                         Console.CancelKeyPress -= InterruptEdit;
1202
1203                         if (text == null){
1204                                 history.Close ();
1205                                 return null;
1206                         }
1207
1208                         string result = text.ToString ();
1209                         if (result != "")
1210                                 history.Accept (result);
1211                         else
1212                                 history.RemoveLast ();
1213
1214                         return result;
1215                 }
1216                 
1217                 public void SaveHistory ()
1218                 {
1219                         if (history != null) {
1220                                 history.Close ();
1221                         }
1222                 }
1223
1224                 public bool TabAtStartCompletes { get; set; }
1225                         
1226                 //
1227                 // Emulates the bash-like behavior, where edits done to the
1228                 // history are recorded
1229                 //
1230                 class History {
1231                         string [] history;
1232                         int head, tail;
1233                         int cursor, count;
1234                         string histfile;
1235                         
1236                         public History (string app, int size)
1237                         {
1238                                 if (size < 1)
1239                                         throw new ArgumentException ("size");
1240
1241                                 if (app != null){
1242                                         string dir = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
1243                                         //Console.WriteLine (dir);
1244                                         if (!Directory.Exists (dir)){
1245                                                 try {
1246                                                         Directory.CreateDirectory (dir);
1247                                                 } catch {
1248                                                         app = null;
1249                                                 }
1250                                         }
1251                                         if (app != null)
1252                                                 histfile = Path.Combine (dir, app) + ".history";
1253                                 }
1254                                 
1255                                 history = new string [size];
1256                                 head = tail = cursor = 0;
1257
1258                                 if (File.Exists (histfile)){
1259                                         using (StreamReader sr = File.OpenText (histfile)){
1260                                                 string line;
1261                                                 
1262                                                 while ((line = sr.ReadLine ()) != null){
1263                                                         if (line != "")
1264                                                                 Append (line);
1265                                                 }
1266                                         }
1267                                 }
1268                         }
1269
1270                         public void Close ()
1271                         {
1272                                 if (histfile == null)
1273                                         return;
1274
1275                                 try {
1276                                         using (StreamWriter sw = File.CreateText (histfile)){
1277                                                 int start = (count == history.Length) ? head : tail;
1278                                                 for (int i = start; i < start+count; i++){
1279                                                         int p = i % history.Length;
1280                                                         sw.WriteLine (history [p]);
1281                                                 }
1282                                         }
1283                                 } catch {
1284                                         // ignore
1285                                 }
1286                         }
1287                         
1288                         //
1289                         // Appends a value to the history
1290                         //
1291                         public void Append (string s)
1292                         {
1293                                 //Console.WriteLine ("APPENDING {0} head={1} tail={2}", s, head, tail);
1294                                 history [head] = s;
1295                                 head = (head+1) % history.Length;
1296                                 if (head == tail)
1297                                         tail = (tail+1 % history.Length);
1298                                 if (count != history.Length)
1299                                         count++;
1300                                 //Console.WriteLine ("DONE: head={1} tail={2}", s, head, tail);
1301                         }
1302
1303                         //
1304                         // Updates the current cursor location with the string,
1305                         // to support editing of history items.   For the current
1306                         // line to participate, an Append must be done before.
1307                         //
1308                         public void Update (string s)
1309                         {
1310                                 history [cursor] = s;
1311                         }
1312
1313                         public void RemoveLast ()
1314                         {
1315                                 head = head-1;
1316                                 if (head < 0)
1317                                         head = history.Length-1;
1318                         }
1319                         
1320                         public void Accept (string s)
1321                         {
1322                                 int t = head-1;
1323                                 if (t < 0)
1324                                         t = history.Length-1;
1325                                 
1326                                 history [t] = s;
1327                         }
1328                         
1329                         public bool PreviousAvailable ()
1330                         {
1331                                 //Console.WriteLine ("h={0} t={1} cursor={2}", head, tail, cursor);
1332                                 if (count == 0)
1333                                         return false;
1334                                 int next = cursor-1;
1335                                 if (next < 0)
1336                                         next = count-1;
1337
1338                                 if (next == head)
1339                                         return false;
1340
1341                                 return true;
1342                         }
1343
1344                         public bool NextAvailable ()
1345                         {
1346                                 if (count == 0)
1347                                         return false;
1348                                 int next = (cursor + 1) % history.Length;
1349                                 if (next == head)
1350                                         return false;
1351                                 return true;
1352                         }
1353                         
1354                         
1355                         //
1356                         // Returns: a string with the previous line contents, or
1357                         // nul if there is no data in the history to move to.
1358                         //
1359                         public string Previous ()
1360                         {
1361                                 if (!PreviousAvailable ())
1362                                         return null;
1363
1364                                 cursor--;
1365                                 if (cursor < 0)
1366                                         cursor = history.Length - 1;
1367
1368                                 return history [cursor];
1369                         }
1370
1371                         public string Next ()
1372                         {
1373                                 if (!NextAvailable ())
1374                                         return null;
1375
1376                                 cursor = (cursor + 1) % history.Length;
1377                                 return history [cursor];
1378                         }
1379
1380                         public void CursorToEnd ()
1381                         {
1382                                 if (head == tail)
1383                                         return;
1384
1385                                 cursor = head;
1386                         }
1387
1388                         public void Dump ()
1389                         {
1390                                 Console.WriteLine ("Head={0} Tail={1} Cursor={2} count={3}", head, tail, cursor, count);
1391                                 for (int i = 0; i < history.Length;i++){
1392                                         Console.WriteLine (" {0} {1}: {2}", i == cursor ? "==>" : "   ", i, history[i]);
1393                                 }
1394                                 //log.Flush ();
1395                         }
1396
1397                         public string SearchBackward (string term)
1398                         {
1399                                 for (int i = 0; i < count; i++){
1400                                         int slot = cursor-i-1;
1401                                         if (slot < 0)
1402                                                 slot = history.Length+slot;
1403                                         if (slot >= history.Length)
1404                                                 slot = 0;
1405                                         if (history [slot] != null && history [slot].IndexOf (term) != -1){
1406                                                 cursor = slot;
1407                                                 return history [slot];
1408                                         }
1409                                 }
1410
1411                                 return null;
1412                         }
1413                         
1414                 }
1415         }
1416
1417 #if DEMO
1418         class Demo {
1419                 static void Main ()
1420                 {
1421                         LineEditor le = new LineEditor ("foo") {
1422                                 HeuristicsMode = "csharp"
1423                         };
1424                         le.AutoCompleteEvent += delegate (string a, int pos){
1425                                 string prefix = "";
1426                                 var completions = new string [] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" };
1427                                 return new Mono.Terminal.LineEditor.Completion (prefix, completions);
1428                         };
1429                         
1430                         string s;
1431                         
1432                         while ((s = le.Edit ("shell> ", "")) != null){
1433                                 Console.WriteLine ("----> [{0}]", s);
1434                         }
1435                 }
1436         }
1437 #endif
1438 }