-
Notifications
You must be signed in to change notification settings - Fork 55
/
linenoise.hpp
2415 lines (2192 loc) · 90.3 KB
/
linenoise.hpp
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
/*
* linenoise.hpp -- Multi-platform C++ header-only linenoise library.
*
* All credits and commendations have to go to the authors of the
* following excellent libraries.
*
* - linenoise.h and linenoise.c (https://github.com/antirez/linenoise)
* - ANSI.c (https://github.com/adoxa/ansicon)
* - Win32_ANSI.h and Win32_ANSI.c (https://github.com/MSOpenTech/redis)
*
* ------------------------------------------------------------------------
*
* Copyright (c) 2015 yhirose
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* linenoise.h -- guerrilla line editing library against the idea that a
* line editing lib needs to be 20,000 lines of C code.
*
* See linenoise.c for more information.
*
* ------------------------------------------------------------------------
*
* Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* ANSI.c - ANSI escape sequence console driver.
*
* Copyright (C) 2005-2014 Jason Hood
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the author be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
* Jason Hood
*/
/*
* Win32_ANSI.h and Win32_ANSI.c
*
* Derived from ANSI.c by Jason Hood, from his ansicon project (https://github.com/adoxa/ansicon), with modifications.
*
* Copyright (c), Microsoft Open Technologies, Inc.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LINENOISE_HPP
#define LINENOISE_HPP
#ifndef _WIN32
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#else
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Windows.h>
#include <io.h>
#ifndef STDIN_FILENO
#define STDIN_FILENO (_fileno(stdin))
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#define isatty _isatty
#define write win32_write
#define read _read
#pragma warning(push)
#pragma warning(disable : 4996)
#endif
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <string>
#include <fstream>
#include <functional>
#include <vector>
#include <iostream>
namespace linenoise {
typedef std::function<void (const char*, std::vector<std::string>&)> CompletionCallback;
#ifdef _WIN32
namespace ansi {
#define lenof(array) (sizeof(array)/sizeof(*(array)))
typedef struct
{
BYTE foreground; // ANSI base color (0 to 7; add 30)
BYTE background; // ANSI base color (0 to 7; add 40)
BYTE bold; // console FOREGROUND_INTENSITY bit
BYTE underline; // console BACKGROUND_INTENSITY bit
BYTE rvideo; // swap foreground/bold & background/underline
BYTE concealed; // set foreground/bold to background/underline
BYTE reverse; // swap console foreground & background attributes
} GRM, *PGRM; // Graphic Rendition Mode
inline bool is_digit(char c) { return '0' <= c && c <= '9'; }
// ========== Global variables and constants
HANDLE hConOut; // handle to CONOUT$
const char ESC = '\x1B'; // ESCape character
const char BEL = '\x07';
const char SO = '\x0E'; // Shift Out
const char SI = '\x0F'; // Shift In
const int MAX_ARG = 16; // max number of args in an escape sequence
int state; // automata state
WCHAR prefix; // escape sequence prefix ( '[', ']' or '(' );
WCHAR prefix2; // secondary prefix ( '?' or '>' );
WCHAR suffix; // escape sequence suffix
int es_argc; // escape sequence args count
int es_argv[MAX_ARG]; // escape sequence args
WCHAR Pt_arg[MAX_PATH * 2]; // text parameter for Operating System Command
int Pt_len;
BOOL shifted;
// DEC Special Graphics Character Set from
// http://vt100.net/docs/vt220-rm/table2-4.html
// Some of these may not look right, depending on the font and code page (in
// particular, the Control Pictures probably won't work at all).
const WCHAR G1[] =
{
' ', // _ - blank
L'\x2666', // ` - Black Diamond Suit
L'\x2592', // a - Medium Shade
L'\x2409', // b - HT
L'\x240c', // c - FF
L'\x240d', // d - CR
L'\x240a', // e - LF
L'\x00b0', // f - Degree Sign
L'\x00b1', // g - Plus-Minus Sign
L'\x2424', // h - NL
L'\x240b', // i - VT
L'\x2518', // j - Box Drawings Light Up And Left
L'\x2510', // k - Box Drawings Light Down And Left
L'\x250c', // l - Box Drawings Light Down And Right
L'\x2514', // m - Box Drawings Light Up And Right
L'\x253c', // n - Box Drawings Light Vertical And Horizontal
L'\x00af', // o - SCAN 1 - Macron
L'\x25ac', // p - SCAN 3 - Black Rectangle
L'\x2500', // q - SCAN 5 - Box Drawings Light Horizontal
L'_', // r - SCAN 7 - Low Line
L'_', // s - SCAN 9 - Low Line
L'\x251c', // t - Box Drawings Light Vertical And Right
L'\x2524', // u - Box Drawings Light Vertical And Left
L'\x2534', // v - Box Drawings Light Up And Horizontal
L'\x252c', // w - Box Drawings Light Down And Horizontal
L'\x2502', // x - Box Drawings Light Vertical
L'\x2264', // y - Less-Than Or Equal To
L'\x2265', // z - Greater-Than Or Equal To
L'\x03c0', // { - Greek Small Letter Pi
L'\x2260', // | - Not Equal To
L'\x00a3', // } - Pound Sign
L'\x00b7', // ~ - Middle Dot
};
#define FIRST_G1 '_'
#define LAST_G1 '~'
// color constants
#define FOREGROUND_BLACK 0
#define FOREGROUND_WHITE FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE
#define BACKGROUND_BLACK 0
#define BACKGROUND_WHITE BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE
const BYTE foregroundcolor[8] =
{
FOREGROUND_BLACK, // black foreground
FOREGROUND_RED, // red foreground
FOREGROUND_GREEN, // green foreground
FOREGROUND_RED | FOREGROUND_GREEN, // yellow foreground
FOREGROUND_BLUE, // blue foreground
FOREGROUND_BLUE | FOREGROUND_RED, // magenta foreground
FOREGROUND_BLUE | FOREGROUND_GREEN, // cyan foreground
FOREGROUND_WHITE // white foreground
};
const BYTE backgroundcolor[8] =
{
BACKGROUND_BLACK, // black background
BACKGROUND_RED, // red background
BACKGROUND_GREEN, // green background
BACKGROUND_RED | BACKGROUND_GREEN, // yellow background
BACKGROUND_BLUE, // blue background
BACKGROUND_BLUE | BACKGROUND_RED, // magenta background
BACKGROUND_BLUE | BACKGROUND_GREEN, // cyan background
BACKGROUND_WHITE, // white background
};
const BYTE attr2ansi[8] = // map console attribute to ANSI number
{
0, // black
4, // blue
2, // green
6, // cyan
1, // red
5, // magenta
3, // yellow
7 // white
};
GRM grm;
// saved cursor position
COORD SavePos;
// ========== Print Buffer functions
#define BUFFER_SIZE 2048
int nCharInBuffer;
WCHAR ChBuffer[BUFFER_SIZE];
//-----------------------------------------------------------------------------
// FlushBuffer()
// Writes the buffer to the console and empties it.
//-----------------------------------------------------------------------------
inline void FlushBuffer(void)
{
DWORD nWritten;
if (nCharInBuffer <= 0) return;
WriteConsoleW(hConOut, ChBuffer, nCharInBuffer, &nWritten, NULL);
nCharInBuffer = 0;
}
//-----------------------------------------------------------------------------
// PushBuffer( WCHAR c )
// Adds a character in the buffer.
//-----------------------------------------------------------------------------
inline void PushBuffer(WCHAR c)
{
if (shifted && c >= FIRST_G1 && c <= LAST_G1)
c = G1[c - FIRST_G1];
ChBuffer[nCharInBuffer] = c;
if (++nCharInBuffer == BUFFER_SIZE)
FlushBuffer();
}
//-----------------------------------------------------------------------------
// SendSequence( LPCWSTR seq )
// Send the string to the input buffer.
//-----------------------------------------------------------------------------
inline void SendSequence(LPCWSTR seq)
{
DWORD out;
INPUT_RECORD in;
HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
in.EventType = KEY_EVENT;
in.Event.KeyEvent.bKeyDown = TRUE;
in.Event.KeyEvent.wRepeatCount = 1;
in.Event.KeyEvent.wVirtualKeyCode = 0;
in.Event.KeyEvent.wVirtualScanCode = 0;
in.Event.KeyEvent.dwControlKeyState = 0;
for (; *seq; ++seq)
{
in.Event.KeyEvent.uChar.UnicodeChar = *seq;
WriteConsoleInput(hStdIn, &in, 1, &out);
}
}
// ========== Print functions
//-----------------------------------------------------------------------------
// InterpretEscSeq()
// Interprets the last escape sequence scanned by ParseAndPrintANSIString
// prefix escape sequence prefix
// es_argc escape sequence args count
// es_argv[] escape sequence args array
// suffix escape sequence suffix
//
// for instance, with \e[33;45;1m we have
// prefix = '[',
// es_argc = 3, es_argv[0] = 33, es_argv[1] = 45, es_argv[2] = 1
// suffix = 'm'
//-----------------------------------------------------------------------------
inline void InterpretEscSeq(void)
{
int i;
WORD attribute;
CONSOLE_SCREEN_BUFFER_INFO Info;
CONSOLE_CURSOR_INFO CursInfo;
DWORD len, NumberOfCharsWritten;
COORD Pos;
SMALL_RECT Rect;
CHAR_INFO CharInfo;
if (prefix == '[')
{
if (prefix2 == '?' && (suffix == 'h' || suffix == 'l'))
{
if (es_argc == 1 && es_argv[0] == 25)
{
GetConsoleCursorInfo(hConOut, &CursInfo);
CursInfo.bVisible = (suffix == 'h');
SetConsoleCursorInfo(hConOut, &CursInfo);
return;
}
}
// Ignore any other \e[? or \e[> sequences.
if (prefix2 != 0)
return;
GetConsoleScreenBufferInfo(hConOut, &Info);
switch (suffix)
{
case 'm':
if (es_argc == 0) es_argv[es_argc++] = 0;
for (i = 0; i < es_argc; i++)
{
if (30 <= es_argv[i] && es_argv[i] <= 37)
grm.foreground = es_argv[i] - 30;
else if (40 <= es_argv[i] && es_argv[i] <= 47)
grm.background = es_argv[i] - 40;
else switch (es_argv[i])
{
case 0:
case 39:
case 49:
{
WCHAR def[4];
int a;
*def = '7'; def[1] = '\0';
GetEnvironmentVariableW(L"ANSICON_DEF", def, lenof(def));
a = wcstol(def, NULL, 16);
grm.reverse = FALSE;
if (a < 0)
{
grm.reverse = TRUE;
a = -a;
}
if (es_argv[i] != 49)
grm.foreground = attr2ansi[a & 7];
if (es_argv[i] != 39)
grm.background = attr2ansi[(a >> 4) & 7];
if (es_argv[i] == 0)
{
if (es_argc == 1)
{
grm.bold = a & FOREGROUND_INTENSITY;
grm.underline = a & BACKGROUND_INTENSITY;
}
else
{
grm.bold = 0;
grm.underline = 0;
}
grm.rvideo = 0;
grm.concealed = 0;
}
}
break;
case 1: grm.bold = FOREGROUND_INTENSITY; break;
case 5: // blink
case 4: grm.underline = BACKGROUND_INTENSITY; break;
case 7: grm.rvideo = 1; break;
case 8: grm.concealed = 1; break;
case 21: // oops, this actually turns on double underline
case 22: grm.bold = 0; break;
case 25:
case 24: grm.underline = 0; break;
case 27: grm.rvideo = 0; break;
case 28: grm.concealed = 0; break;
}
}
if (grm.concealed)
{
if (grm.rvideo)
{
attribute = foregroundcolor[grm.foreground]
| backgroundcolor[grm.foreground];
if (grm.bold)
attribute |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
}
else
{
attribute = foregroundcolor[grm.background]
| backgroundcolor[grm.background];
if (grm.underline)
attribute |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
}
}
else if (grm.rvideo)
{
attribute = foregroundcolor[grm.background]
| backgroundcolor[grm.foreground];
if (grm.bold)
attribute |= BACKGROUND_INTENSITY;
if (grm.underline)
attribute |= FOREGROUND_INTENSITY;
}
else
attribute = foregroundcolor[grm.foreground] | grm.bold
| backgroundcolor[grm.background] | grm.underline;
if (grm.reverse)
attribute = ((attribute >> 4) & 15) | ((attribute & 15) << 4);
SetConsoleTextAttribute(hConOut, attribute);
return;
case 'J':
if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[J == ESC[0J
if (es_argc != 1) return;
switch (es_argv[0])
{
case 0: // ESC[0J erase from cursor to end of display
len = (Info.dwSize.Y - Info.dwCursorPosition.Y - 1) * Info.dwSize.X
+ Info.dwSize.X - Info.dwCursorPosition.X - 1;
FillConsoleOutputCharacter(hConOut, ' ', len,
Info.dwCursorPosition,
&NumberOfCharsWritten);
FillConsoleOutputAttribute(hConOut, Info.wAttributes, len,
Info.dwCursorPosition,
&NumberOfCharsWritten);
return;
case 1: // ESC[1J erase from start to cursor.
Pos.X = 0;
Pos.Y = 0;
len = Info.dwCursorPosition.Y * Info.dwSize.X
+ Info.dwCursorPosition.X + 1;
FillConsoleOutputCharacter(hConOut, ' ', len, Pos,
&NumberOfCharsWritten);
FillConsoleOutputAttribute(hConOut, Info.wAttributes, len, Pos,
&NumberOfCharsWritten);
return;
case 2: // ESC[2J Clear screen and home cursor
Pos.X = 0;
Pos.Y = 0;
len = Info.dwSize.X * Info.dwSize.Y;
FillConsoleOutputCharacter(hConOut, ' ', len, Pos,
&NumberOfCharsWritten);
FillConsoleOutputAttribute(hConOut, Info.wAttributes, len, Pos,
&NumberOfCharsWritten);
SetConsoleCursorPosition(hConOut, Pos);
return;
default:
return;
}
case 'K':
if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[K == ESC[0K
if (es_argc != 1) return;
switch (es_argv[0])
{
case 0: // ESC[0K Clear to end of line
len = Info.dwSize.X - Info.dwCursorPosition.X + 1;
FillConsoleOutputCharacter(hConOut, ' ', len,
Info.dwCursorPosition,
&NumberOfCharsWritten);
FillConsoleOutputAttribute(hConOut, Info.wAttributes, len,
Info.dwCursorPosition,
&NumberOfCharsWritten);
return;
case 1: // ESC[1K Clear from start of line to cursor
Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y;
FillConsoleOutputCharacter(hConOut, ' ',
Info.dwCursorPosition.X + 1, Pos,
&NumberOfCharsWritten);
FillConsoleOutputAttribute(hConOut, Info.wAttributes,
Info.dwCursorPosition.X + 1, Pos,
&NumberOfCharsWritten);
return;
case 2: // ESC[2K Clear whole line.
Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y;
FillConsoleOutputCharacter(hConOut, ' ', Info.dwSize.X, Pos,
&NumberOfCharsWritten);
FillConsoleOutputAttribute(hConOut, Info.wAttributes,
Info.dwSize.X, Pos,
&NumberOfCharsWritten);
return;
default:
return;
}
case 'X': // ESC[#X Erase # characters.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[X == ESC[1X
if (es_argc != 1) return;
FillConsoleOutputCharacter(hConOut, ' ', es_argv[0],
Info.dwCursorPosition,
&NumberOfCharsWritten);
FillConsoleOutputAttribute(hConOut, Info.wAttributes, es_argv[0],
Info.dwCursorPosition,
&NumberOfCharsWritten);
return;
case 'L': // ESC[#L Insert # blank lines.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[L == ESC[1L
if (es_argc != 1) return;
Rect.Left = 0;
Rect.Top = Info.dwCursorPosition.Y;
Rect.Right = Info.dwSize.X - 1;
Rect.Bottom = Info.dwSize.Y - 1;
Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Pos, &CharInfo);
return;
case 'M': // ESC[#M Delete # lines.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[M == ESC[1M
if (es_argc != 1) return;
if (es_argv[0] > Info.dwSize.Y - Info.dwCursorPosition.Y)
es_argv[0] = Info.dwSize.Y - Info.dwCursorPosition.Y;
Rect.Left = 0;
Rect.Top = Info.dwCursorPosition.Y + es_argv[0];
Rect.Right = Info.dwSize.X - 1;
Rect.Bottom = Info.dwSize.Y - 1;
Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y;
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Pos, &CharInfo);
return;
case 'P': // ESC[#P Delete # characters.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[P == ESC[1P
if (es_argc != 1) return;
if (Info.dwCursorPosition.X + es_argv[0] > Info.dwSize.X - 1)
es_argv[0] = Info.dwSize.X - Info.dwCursorPosition.X;
Rect.Left = Info.dwCursorPosition.X + es_argv[0];
Rect.Top = Info.dwCursorPosition.Y;
Rect.Right = Info.dwSize.X - 1;
Rect.Bottom = Info.dwCursorPosition.Y;
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Info.dwCursorPosition,
&CharInfo);
return;
case '@': // ESC[#@ Insert # blank characters.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[@ == ESC[1@
if (es_argc != 1) return;
if (Info.dwCursorPosition.X + es_argv[0] > Info.dwSize.X - 1)
es_argv[0] = Info.dwSize.X - Info.dwCursorPosition.X;
Rect.Left = Info.dwCursorPosition.X;
Rect.Top = Info.dwCursorPosition.Y;
Rect.Right = Info.dwSize.X - 1 - es_argv[0];
Rect.Bottom = Info.dwCursorPosition.Y;
Pos.X = Info.dwCursorPosition.X + es_argv[0];
Pos.Y = Info.dwCursorPosition.Y;
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Pos, &CharInfo);
return;
case 'k': // ESC[#k
case 'A': // ESC[#A Moves cursor up # lines
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[A == ESC[1A
if (es_argc != 1) return;
Pos.Y = Info.dwCursorPosition.Y - es_argv[0];
if (Pos.Y < 0) Pos.Y = 0;
Pos.X = Info.dwCursorPosition.X;
SetConsoleCursorPosition(hConOut, Pos);
return;
case 'e': // ESC[#e
case 'B': // ESC[#B Moves cursor down # lines
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[B == ESC[1B
if (es_argc != 1) return;
Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
Pos.X = Info.dwCursorPosition.X;
SetConsoleCursorPosition(hConOut, Pos);
return;
case 'a': // ESC[#a
case 'C': // ESC[#C Moves cursor forward # spaces
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[C == ESC[1C
if (es_argc != 1) return;
Pos.X = Info.dwCursorPosition.X + es_argv[0];
if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
Pos.Y = Info.dwCursorPosition.Y;
SetConsoleCursorPosition(hConOut, Pos);
return;
case 'j': // ESC[#j
case 'D': // ESC[#D Moves cursor back # spaces
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[D == ESC[1D
if (es_argc != 1) return;
Pos.X = Info.dwCursorPosition.X - es_argv[0];
if (Pos.X < 0) Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y;
SetConsoleCursorPosition(hConOut, Pos);
return;
case 'E': // ESC[#E Moves cursor down # lines, column 1.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[E == ESC[1E
if (es_argc != 1) return;
Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
Pos.X = 0;
SetConsoleCursorPosition(hConOut, Pos);
return;
case 'F': // ESC[#F Moves cursor up # lines, column 1.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[F == ESC[1F
if (es_argc != 1) return;
Pos.Y = Info.dwCursorPosition.Y - es_argv[0];
if (Pos.Y < 0) Pos.Y = 0;
Pos.X = 0;
SetConsoleCursorPosition(hConOut, Pos);
return;
case '`': // ESC[#`
case 'G': // ESC[#G Moves cursor column # in current row.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[G == ESC[1G
if (es_argc != 1) return;
Pos.X = es_argv[0] - 1;
if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
if (Pos.X < 0) Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y;
SetConsoleCursorPosition(hConOut, Pos);
return;
case 'd': // ESC[#d Moves cursor row #, current column.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[d == ESC[1d
if (es_argc != 1) return;
Pos.Y = es_argv[0] - 1;
if (Pos.Y < 0) Pos.Y = 0;
if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
SetConsoleCursorPosition(hConOut, Pos);
return;
case 'f': // ESC[#;#f
case 'H': // ESC[#;#H Moves cursor to line #, column #
if (es_argc == 0)
es_argv[es_argc++] = 1; // ESC[H == ESC[1;1H
if (es_argc == 1)
es_argv[es_argc++] = 1; // ESC[#H == ESC[#;1H
if (es_argc > 2) return;
Pos.X = es_argv[1] - 1;
if (Pos.X < 0) Pos.X = 0;
if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
Pos.Y = es_argv[0] - 1;
if (Pos.Y < 0) Pos.Y = 0;
if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
SetConsoleCursorPosition(hConOut, Pos);
return;
case 's': // ESC[s Saves cursor position for recall later
if (es_argc != 0) return;
SavePos = Info.dwCursorPosition;
return;
case 'u': // ESC[u Return to saved cursor position
if (es_argc != 0) return;
SetConsoleCursorPosition(hConOut, SavePos);
return;
case 'n': // ESC[#n Device status report
if (es_argc != 1) return; // ESC[n == ESC[0n -> ignored
switch (es_argv[0])
{
case 5: // ESC[5n Report status
SendSequence(L"\33[0n"); // "OK"
return;
case 6: // ESC[6n Report cursor position
{
WCHAR buf[32];
swprintf(buf, 32, L"\33[%d;%dR", Info.dwCursorPosition.Y + 1,
Info.dwCursorPosition.X + 1);
SendSequence(buf);
}
return;
default:
return;
}
case 't': // ESC[#t Window manipulation
if (es_argc != 1) return;
if (es_argv[0] == 21) // ESC[21t Report xterm window's title
{
WCHAR buf[MAX_PATH * 2];
len = GetConsoleTitleW(buf + 3, lenof(buf) - 3 - 2);
// Too bad if it's too big or fails.
buf[0] = ESC;
buf[1] = ']';
buf[2] = 'l';
buf[3 + len] = ESC;
buf[3 + len + 1] = '\\';
buf[3 + len + 2] = '\0';
SendSequence(buf);
}
return;
default:
return;
}
}
else // (prefix == ']')
{
// Ignore any \e]? or \e]> sequences.
if (prefix2 != 0)
return;
if (es_argc == 1 && es_argv[0] == 0) // ESC]0;titleST
{
SetConsoleTitleW(Pt_arg);
}
}
}
//-----------------------------------------------------------------------------
// ParseAndPrintANSIString(hDev, lpBuffer, nNumberOfBytesToWrite)
// Parses the string lpBuffer, interprets the escapes sequences and prints the
// characters in the device hDev (console).
// The lexer is a three states automata.
// If the number of arguments es_argc > MAX_ARG, only the MAX_ARG-1 firsts and
// the last arguments are processed (no es_argv[] overflow).
//-----------------------------------------------------------------------------
inline BOOL ParseAndPrintANSIString(HANDLE hDev, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten)
{
DWORD i;
LPCSTR s;
if (hDev != hConOut) // reinit if device has changed
{
hConOut = hDev;
state = 1;
shifted = FALSE;
}
for (i = nNumberOfBytesToWrite, s = (LPCSTR)lpBuffer; i > 0; i--, s++)
{
if (state == 1)
{
if (*s == ESC) state = 2;
else if (*s == SO) shifted = TRUE;
else if (*s == SI) shifted = FALSE;
else PushBuffer(*s);
}
else if (state == 2)
{
if (*s == ESC); // \e\e...\e == \e
else if ((*s == '[') || (*s == ']'))
{
FlushBuffer();
prefix = *s;
prefix2 = 0;
state = 3;
Pt_len = 0;
*Pt_arg = '\0';
}
else if (*s == ')' || *s == '(') state = 6;
else state = 1;
}
else if (state == 3)
{
if (is_digit(*s))
{
es_argc = 0;
es_argv[0] = *s - '0';
state = 4;
}
else if (*s == ';')
{
es_argc = 1;
es_argv[0] = 0;
es_argv[1] = 0;
state = 4;
}
else if (*s == '?' || *s == '>')
{
prefix2 = *s;
}
else
{
es_argc = 0;
suffix = *s;
InterpretEscSeq();
state = 1;
}
}
else if (state == 4)
{
if (is_digit(*s))
{
es_argv[es_argc] = 10 * es_argv[es_argc] + (*s - '0');
}
else if (*s == ';')
{
if (es_argc < MAX_ARG - 1) es_argc++;
es_argv[es_argc] = 0;
if (prefix == ']')
state = 5;
}
else
{
es_argc++;
suffix = *s;
InterpretEscSeq();
state = 1;
}
}
else if (state == 5)
{
if (*s == BEL)
{
Pt_arg[Pt_len] = '\0';
InterpretEscSeq();
state = 1;
}
else if (*s == '\\' && Pt_len > 0 && Pt_arg[Pt_len - 1] == ESC)
{
Pt_arg[--Pt_len] = '\0';
InterpretEscSeq();
state = 1;
}
else if (Pt_len < lenof(Pt_arg) - 1)
Pt_arg[Pt_len++] = *s;
}
else if (state == 6)
{
// Ignore it (ESC ) 0 is implicit; nothing else is supported).
state = 1;
}
}
FlushBuffer();
if (lpNumberOfBytesWritten != NULL)
*lpNumberOfBytesWritten = nNumberOfBytesToWrite - i;
return (i == 0);
}
} // namespace ansi
HANDLE hOut;
HANDLE hIn;
DWORD consolemodeIn = 0;
inline int win32read(int *c) {
DWORD foo;
INPUT_RECORD b;
KEY_EVENT_RECORD e;
BOOL altgr;
while (1) {
if (!ReadConsoleInput(hIn, &b, 1, &foo)) return 0;
if (!foo) return 0;
if (b.EventType == KEY_EVENT && b.Event.KeyEvent.bKeyDown) {
e = b.Event.KeyEvent;
*c = b.Event.KeyEvent.uChar.AsciiChar;
altgr = e.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_ALT_PRESSED);
if (e.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED) && !altgr) {
/* Ctrl+Key */
switch (*c) {
case 'D':
*c = 4;
return 1;
case 'C':
*c = 3;
return 1;
case 'H':
*c = 8;
return 1;
case 'T':
*c = 20;
return 1;
case 'B': /* ctrl-b, left_arrow */
*c = 2;
return 1;
case 'F': /* ctrl-f right_arrow*/
*c = 6;
return 1;
case 'P': /* ctrl-p up_arrow*/
*c = 16;
return 1;
case 'N': /* ctrl-n down_arrow*/
*c = 14;
return 1;
case 'U': /* Ctrl+u, delete the whole line. */
*c = 21;
return 1;
case 'K': /* Ctrl+k, delete from current to end of line. */
*c = 11;
return 1;
case 'A': /* Ctrl+a, go to the start of the line */
*c = 1;
return 1;
case 'E': /* ctrl+e, go to the end of the line */
*c = 5;
return 1;
}
/* Other Ctrl+KEYs ignored */
} else {
switch (e.wVirtualKeyCode) {
case VK_ESCAPE: /* ignore - send ctrl-c, will return -1 */