This repository has been archived by the owner on Oct 28, 2020. It is now read-only.
forked from antirez/linenoise
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathlinenoise.cpp
3457 lines (3132 loc) · 112 KB
/
linenoise.cpp
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.c -- guerrilla line editing library against the idea that a
* line editing lib needs to be 20,000 lines of C code.
*
* 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.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* 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.
*
* line editing lib needs to be 20,000 lines of C code.
*
* You can find the latest source code at:
*
* http://github.com/antirez/linenoise
*
* Does a number of crazy assumptions that happen to be true in 99.9999% of
* the 2010 UNIX computers around.
*
* References:
* - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
*
* Todo list:
* - Switch to gets() if $TERM is something we can't support.
* - Filter bogus Ctrl+<char> combinations.
* - Win32 support
*
* Bloat:
* - Completion?
* - History search like Ctrl+r in readline?
*
* List of escape sequences used by this program, we do everything just
* with three sequences. In order to be so cheap we may have some
* flickering effect with some slow terminal, but the lesser sequences
* the more compatible.
*
* CHA (Cursor Horizontal Absolute)
* Sequence: ESC [ n G
* Effect: moves cursor to column n (1 based)
*
* EL (Erase Line)
* Sequence: ESC [ n K
* Effect: if n is 0 or missing, clear from cursor to end of line
* Effect: if n is 1, clear from beginning of line to cursor
* Effect: if n is 2, clear entire line
*
* CUF (Cursor Forward)
* Sequence: ESC [ n C
* Effect: moves cursor forward of n chars
*
* The following are used to clear the screen: ESC [ H ESC [ 2 J
* This is actually composed of two sequences:
*
* cursorhome
* Sequence: ESC [ H
* Effect: moves the cursor to upper left corner
*
* ED2 (Clear entire screen)
* Sequence: ESC [ 2 J
* Effect: clear the whole screen
*
*/
#ifdef _WIN32
#include <conio.h>
#include <windows.h>
#include <io.h>
#if defined(_MSC_VER) && _MSC_VER < 1900
#define snprintf _snprintf // Microsoft headers use underscores in some names
#endif
#if !defined GNUC
#define strcasecmp _stricmp
#endif
#define strdup _strdup
#define isatty _isatty
#define write _write
#define STDIN_FILENO 0
#else /* _WIN32 */
#include <signal.h>
#include <termios.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <cctype>
#include <wctype.h>
#endif /* _WIN32 */
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include "linenoise.h"
#include "ConvertUTF.h"
#include <string>
#include <vector>
#include <memory>
using std::string;
using std::vector;
using std::unique_ptr;
using namespace linenoise_ng;
typedef unsigned char char8_t;
static ConversionResult copyString8to32(char32_t* dst, size_t dstSize,
size_t& dstCount, const char* src) {
const UTF8* sourceStart = reinterpret_cast<const UTF8*>(src);
const UTF8* sourceEnd = sourceStart + strlen(src);
UTF32* targetStart = reinterpret_cast<UTF32*>(dst);
UTF32* targetEnd = targetStart + dstSize;
ConversionResult res = ConvertUTF8toUTF32(
&sourceStart, sourceEnd, &targetStart, targetEnd, lenientConversion);
if (res == conversionOK) {
dstCount = targetStart - reinterpret_cast<UTF32*>(dst);
if (dstCount < dstSize) {
*targetStart = 0;
}
}
return res;
}
static ConversionResult copyString8to32(char32_t* dst, size_t dstSize,
size_t& dstCount, const char8_t* src) {
return copyString8to32(dst, dstSize, dstCount,
reinterpret_cast<const char*>(src));
}
static size_t strlen32(const char32_t* str) {
const char32_t* ptr = str;
while (*ptr) {
++ptr;
}
return ptr - str;
}
static size_t strlen8(const char8_t* str) {
return strlen(reinterpret_cast<const char*>(str));
}
static char8_t* strdup8(const char* src) {
return reinterpret_cast<char8_t*>(strdup(src));
}
#ifdef _WIN32
static const int FOREGROUND_WHITE =
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
static const int BACKGROUND_WHITE =
BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE;
static const int INTENSITY = FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
class WinAttributes {
public:
WinAttributes() {
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
_defaultAttribute = info.wAttributes & INTENSITY;
_defaultColor = info.wAttributes & FOREGROUND_WHITE;
_defaultBackground = info.wAttributes & BACKGROUND_WHITE;
_consoleAttribute = _defaultAttribute;
_consoleColor = _defaultColor | _defaultBackground;
}
public:
int _defaultAttribute;
int _defaultColor;
int _defaultBackground;
int _consoleAttribute;
int _consoleColor;
};
static WinAttributes WIN_ATTR;
static void copyString32to16(char16_t* dst, size_t dstSize, size_t* dstCount,
const char32_t* src, size_t srcSize) {
const UTF32* sourceStart = reinterpret_cast<const UTF32*>(src);
const UTF32* sourceEnd = sourceStart + srcSize;
char16_t* targetStart = reinterpret_cast<char16_t*>(dst);
char16_t* targetEnd = targetStart + dstSize;
ConversionResult res = ConvertUTF32toUTF16(
&sourceStart, sourceEnd, &targetStart, targetEnd, lenientConversion);
if (res == conversionOK) {
*dstCount = targetStart - reinterpret_cast<char16_t*>(dst);
if (*dstCount < dstSize) {
*targetStart = 0;
}
}
}
#endif
static void copyString32to8(char* dst, size_t dstSize, size_t* dstCount,
const char32_t* src, size_t srcSize) {
const UTF32* sourceStart = reinterpret_cast<const UTF32*>(src);
const UTF32* sourceEnd = sourceStart + srcSize;
UTF8* targetStart = reinterpret_cast<UTF8*>(dst);
UTF8* targetEnd = targetStart + dstSize;
ConversionResult res = ConvertUTF32toUTF8(
&sourceStart, sourceEnd, &targetStart, targetEnd, lenientConversion);
if (res == conversionOK) {
*dstCount = targetStart - reinterpret_cast<UTF8*>(dst);
if (*dstCount < dstSize) {
*targetStart = 0;
}
}
}
static void copyString32to8(char* dst, size_t dstLen, const char32_t* src) {
size_t dstCount = 0;
copyString32to8(dst, dstLen, &dstCount, src, strlen32(src));
}
static void copyString32(char32_t* dst, const char32_t* src, size_t len) {
while (0 < len && *src) {
*dst++ = *src++;
--len;
}
*dst = 0;
}
static int strncmp32(const char32_t* left, const char32_t* right, size_t len) {
while (0 < len && *left) {
if (*left != *right) {
return *left - *right;
}
++left;
++right;
--len;
}
return 0;
}
#ifdef _WIN32
#include <iostream>
static size_t OutputWin(char16_t* text16, char32_t* text32, size_t len32) {
size_t count16 = 0;
copyString32to16(text16, len32, &count16, text32, len32);
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), text16,
static_cast<DWORD>(count16), nullptr, nullptr);
return count16;
}
static char32_t* HandleEsc(char32_t* p, char32_t* end) {
if (*p == '[') {
int code = 0;
for (++p; p < end; ++p) {
char32_t c = *p;
if ('0' <= c && c <= '9') {
code = code * 10 + (c - '0');
} else if (c == 'm' || c == ';') {
switch (code) {
case 0:
WIN_ATTR._consoleAttribute = WIN_ATTR._defaultAttribute;
WIN_ATTR._consoleColor =
WIN_ATTR._defaultColor | WIN_ATTR._defaultBackground;
break;
case 1: // BOLD
case 5: // BLINK
WIN_ATTR._consoleAttribute =
(WIN_ATTR._defaultAttribute ^ FOREGROUND_INTENSITY) & INTENSITY;
break;
case 30:
WIN_ATTR._consoleColor = BACKGROUND_WHITE;
break;
case 31:
WIN_ATTR._consoleColor =
FOREGROUND_RED | WIN_ATTR._defaultBackground;
break;
case 32:
WIN_ATTR._consoleColor =
FOREGROUND_GREEN | WIN_ATTR._defaultBackground;
break;
case 33:
WIN_ATTR._consoleColor =
FOREGROUND_RED | FOREGROUND_GREEN | WIN_ATTR._defaultBackground;
break;
case 34:
WIN_ATTR._consoleColor =
FOREGROUND_BLUE | WIN_ATTR._defaultBackground;
break;
case 35:
WIN_ATTR._consoleColor =
FOREGROUND_BLUE | FOREGROUND_RED | WIN_ATTR._defaultBackground;
break;
case 36:
WIN_ATTR._consoleColor = FOREGROUND_BLUE | FOREGROUND_GREEN |
WIN_ATTR._defaultBackground;
break;
case 37:
WIN_ATTR._consoleColor = FOREGROUND_GREEN | FOREGROUND_RED |
FOREGROUND_BLUE |
WIN_ATTR._defaultBackground;
break;
}
code = 0;
}
if (*p == 'm') {
++p;
break;
}
}
} else {
++p;
}
auto handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle,
WIN_ATTR._consoleAttribute | WIN_ATTR._consoleColor);
return p;
}
static size_t WinWrite32(char16_t* text16, char32_t* text32, size_t len32) {
char32_t* p = text32;
char32_t* q = p;
char32_t* e = text32 + len32;
size_t count16 = 0;
while (p < e) {
if (*p == 27) {
if (q < p) {
count16 += OutputWin(text16, q, p - q);
}
q = p = HandleEsc(p + 1, e);
} else {
++p;
}
}
if (q < p) {
count16 += OutputWin(text16, q, p - q);
}
return count16;
}
#endif
static int write32(int fd, char32_t* text32, int len32) {
#ifdef _WIN32
if (isatty(fd)) {
size_t len16 = 2 * len32 + 1;
unique_ptr<char16_t[]> text16(new char16_t[len16]);
size_t count16 = WinWrite32(text16.get(), text32, len32);
return static_cast<int>(count16);
} else {
size_t len8 = 4 * len32 + 1;
unique_ptr<char[]> text8(new char[len8]);
size_t count8 = 0;
copyString32to8(text8.get(), len8, &count8, text32, len32);
return write(fd, text8.get(), static_cast<unsigned int>(count8));
}
#else
size_t len8 = 4 * len32 + 1;
unique_ptr<char[]> text8(new char[len8]);
size_t count8 = 0;
copyString32to8(text8.get(), len8, &count8, text32, len32);
return write(fd, text8.get(), count8);
#endif
}
class Utf32String {
public:
Utf32String() : _length(0), _data(nullptr) {
// note: parens intentional, _data must be properly initialized
_data = new char32_t[1]();
}
explicit Utf32String(const char* src) : _length(0), _data(nullptr) {
size_t len = strlen(src);
// note: parens intentional, _data must be properly initialized
_data = new char32_t[len + 1]();
copyString8to32(_data, len + 1, _length, src);
}
explicit Utf32String(const char8_t* src) : _length(0), _data(nullptr) {
size_t len = strlen(reinterpret_cast<const char*>(src));
// note: parens intentional, _data must be properly initialized
_data = new char32_t[len + 1]();
copyString8to32(_data, len + 1, _length, src);
}
explicit Utf32String(const char32_t* src) : _length(0), _data(nullptr) {
for (_length = 0; src[_length] != 0; ++_length) {
}
// note: parens intentional, _data must be properly initialized
_data = new char32_t[_length + 1]();
memcpy(_data, src, _length * sizeof(char32_t));
}
explicit Utf32String(const char32_t* src, int len) : _length(len), _data(nullptr) {
// note: parens intentional, _data must be properly initialized
_data = new char32_t[len + 1]();
memcpy(_data, src, len * sizeof(char32_t));
}
explicit Utf32String(int len) : _length(0), _data(nullptr) {
// note: parens intentional, _data must be properly initialized
_data = new char32_t[len]();
}
explicit Utf32String(const Utf32String& that) : _length(that._length), _data(nullptr) {
// note: parens intentional, _data must be properly initialized
_data = new char32_t[_length + 1]();
memcpy(_data, that._data, sizeof(char32_t) * _length);
}
Utf32String& operator=(const Utf32String& that) {
if (this != &that) {
delete[] _data;
_data = new char32_t[that._length]();
_length = that._length;
memcpy(_data, that._data, sizeof(char32_t) * _length);
}
return *this;
}
~Utf32String() { delete[] _data; }
public:
char32_t* get() const { return _data; }
size_t length() const { return _length; }
size_t chars() const { return _length; }
void initFromBuffer() {
for (_length = 0; _data[_length] != 0; ++_length) {
}
}
const char32_t& operator[](size_t pos) const { return _data[pos]; }
char32_t& operator[](size_t pos) { return _data[pos]; }
private:
size_t _length;
char32_t* _data;
};
class Utf8String {
Utf8String(const Utf8String&) = delete;
Utf8String& operator=(const Utf8String&) = delete;
public:
explicit Utf8String(const Utf32String& src) {
size_t len = src.length() * 4 + 1;
_data = new char[len];
copyString32to8(_data, len, src.get());
}
~Utf8String() { delete[] _data; }
public:
char* get() const { return _data; }
private:
char* _data;
};
struct linenoiseCompletions {
vector<Utf32String> completionStrings;
};
#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
#define LINENOISE_MAX_LINE 4096
// make control-characters more readable
#define ctrlChar(upperCaseASCII) (upperCaseASCII - 0x40)
/**
* Recompute widths of all characters in a char32_t buffer
* @param text input buffer of Unicode characters
* @param widths output buffer of character widths
* @param charCount number of characters in buffer
*/
namespace linenoise_ng {
int mk_wcwidth(char32_t ucs);
}
static void recomputeCharacterWidths(const char32_t* text, char* widths,
int charCount) {
for (int i = 0; i < charCount; ++i) {
widths[i] = mk_wcwidth(text[i]);
}
}
/**
* Calculate a new screen position given a starting position, screen width and
* character count
* @param x initial x position (zero-based)
* @param y initial y position (zero-based)
* @param screenColumns screen column count
* @param charCount character positions to advance
* @param xOut returned x position (zero-based)
* @param yOut returned y position (zero-based)
*/
static void calculateScreenPosition(int x, int y, int screenColumns,
int charCount, int& xOut, int& yOut) {
xOut = x;
yOut = y;
int charsRemaining = charCount;
while (charsRemaining > 0) {
int charsThisRow = (x + charsRemaining < screenColumns) ? charsRemaining
: screenColumns - x;
xOut = x + charsThisRow;
yOut = y;
charsRemaining -= charsThisRow;
x = 0;
++y;
}
if (xOut == screenColumns) { // we have to special-case line wrap
xOut = 0;
++yOut;
}
}
/**
* Calculate a column width using mk_wcswidth()
* @param buf32 text to calculate
* @param len length of text to calculate
*/
namespace linenoise_ng {
int mk_wcswidth(const char32_t* pwcs, size_t n);
}
static int calculateColumnPosition(char32_t* buf32, int len) {
int width = mk_wcswidth(reinterpret_cast<const char32_t*>(buf32), len);
if (width == -1)
return len;
else
return width;
}
static bool isControlChar(char32_t testChar) {
return (testChar < ' ') || // C0 controls
(testChar >= 0x7F && testChar <= 0x9F); // DEL and C1 controls
}
struct PromptBase { // a convenience struct for grouping prompt info
Utf32String promptText; // our copy of the prompt text, edited
char* promptCharWidths; // character widths from mk_wcwidth()
int promptChars; // chars in promptText
int promptBytes; // bytes in promptText
int promptExtraLines; // extra lines (beyond 1) occupied by prompt
int promptIndentation; // column offset to end of prompt
int promptLastLinePosition; // index into promptText where last line begins
int promptPreviousInputLen; // promptChars of previous input line, for
// clearing
int promptCursorRowOffset; // where the cursor is relative to the start of
// the prompt
int promptScreenColumns; // width of screen in columns
int promptPreviousLen; // help erasing
int promptErrorCode; // error code (invalid UTF-8) or zero
PromptBase() : promptPreviousInputLen(0) {}
bool write() {
if (write32(1, promptText.get(), promptBytes) == -1) return false;
return true;
}
};
struct PromptInfo : public PromptBase {
PromptInfo(const char* textPtr, int columns) {
promptExtraLines = 0;
promptLastLinePosition = 0;
promptPreviousLen = 0;
promptScreenColumns = columns;
Utf32String tempUnicode(textPtr);
// strip control characters from the prompt -- we do allow newline
char32_t* pIn = tempUnicode.get();
char32_t* pOut = pIn;
int len = 0;
int x = 0;
bool const strip = (isatty(1) == 0);
while (*pIn) {
char32_t c = *pIn;
if ('\n' == c || !isControlChar(c)) {
*pOut = c;
++pOut;
++pIn;
++len;
if ('\n' == c || ++x >= promptScreenColumns) {
x = 0;
++promptExtraLines;
promptLastLinePosition = len;
}
} else if (c == '\x1b') {
if (strip) {
// jump over control chars
++pIn;
if (*pIn == '[') {
++pIn;
while (*pIn && ((*pIn == ';') || ((*pIn >= '0' && *pIn <= '9')))) {
++pIn;
}
if (*pIn == 'm') {
++pIn;
}
}
} else {
// copy control chars
*pOut = *pIn;
++pOut;
++pIn;
if (*pIn == '[') {
*pOut = *pIn;
++pOut;
++pIn;
while (*pIn && ((*pIn == ';') || ((*pIn >= '0' && *pIn <= '9')))) {
*pOut = *pIn;
++pOut;
++pIn;
}
if (*pIn == 'm') {
*pOut = *pIn;
++pOut;
++pIn;
}
}
}
} else {
++pIn;
}
}
*pOut = 0;
promptChars = len;
promptBytes = static_cast<int>(pOut - tempUnicode.get());
promptText = tempUnicode;
promptIndentation = len - promptLastLinePosition;
promptCursorRowOffset = promptExtraLines;
}
};
// Used with DynamicPrompt (history search)
//
static const Utf32String forwardSearchBasePrompt("(i-search)`");
static const Utf32String reverseSearchBasePrompt("(reverse-i-search)`");
static const Utf32String endSearchBasePrompt("': ");
static Utf32String
previousSearchText; // remembered across invocations of linenoise()
// changing prompt for "(reverse-i-search)`text':" etc.
//
struct DynamicPrompt : public PromptBase {
Utf32String searchText; // text we are searching for
char* searchCharWidths; // character widths from mk_wcwidth()
int searchTextLen; // chars in searchText
int direction; // current search direction, 1=forward, -1=reverse
DynamicPrompt(PromptBase& pi, int initialDirection)
: searchTextLen(0), direction(initialDirection) {
promptScreenColumns = pi.promptScreenColumns;
promptCursorRowOffset = 0;
Utf32String emptyString(1);
searchText = emptyString;
const Utf32String* basePrompt =
(direction > 0) ? &forwardSearchBasePrompt : &reverseSearchBasePrompt;
size_t promptStartLength = basePrompt->length();
promptChars =
static_cast<int>(promptStartLength + endSearchBasePrompt.length());
promptBytes = promptChars;
promptLastLinePosition = promptChars; // TODO fix this, we are asssuming
// that the history prompt won't wrap
// (!)
promptPreviousLen = promptChars;
Utf32String tempUnicode(promptChars + 1);
memcpy(tempUnicode.get(), basePrompt->get(),
sizeof(char32_t) * promptStartLength);
memcpy(&tempUnicode[promptStartLength], endSearchBasePrompt.get(),
sizeof(char32_t) * (endSearchBasePrompt.length() + 1));
tempUnicode.initFromBuffer();
promptText = tempUnicode;
calculateScreenPosition(0, 0, pi.promptScreenColumns, promptChars,
promptIndentation, promptExtraLines);
}
void updateSearchPrompt(void) {
const Utf32String* basePrompt =
(direction > 0) ? &forwardSearchBasePrompt : &reverseSearchBasePrompt;
size_t promptStartLength = basePrompt->length();
promptChars = static_cast<int>(promptStartLength + searchTextLen +
endSearchBasePrompt.length());
promptBytes = promptChars;
Utf32String tempUnicode(promptChars + 1);
memcpy(tempUnicode.get(), basePrompt->get(),
sizeof(char32_t) * promptStartLength);
memcpy(&tempUnicode[promptStartLength], searchText.get(),
sizeof(char32_t) * searchTextLen);
size_t endIndex = promptStartLength + searchTextLen;
memcpy(&tempUnicode[endIndex], endSearchBasePrompt.get(),
sizeof(char32_t) * (endSearchBasePrompt.length() + 1));
tempUnicode.initFromBuffer();
promptText = tempUnicode;
}
void updateSearchText(const char32_t* textPtr) {
Utf32String tempUnicode(textPtr);
searchTextLen = static_cast<int>(tempUnicode.chars());
searchText = tempUnicode;
updateSearchPrompt();
}
};
class KillRing {
static const int capacity = 10;
int size;
int index;
char indexToSlot[10];
vector<Utf32String> theRing;
public:
enum action { actionOther, actionKill, actionYank };
action lastAction;
size_t lastYankSize;
KillRing() : size(0), index(0), lastAction(actionOther) {
theRing.reserve(capacity);
}
void kill(const char32_t* text, int textLen, bool forward) {
if (textLen == 0) {
return;
}
Utf32String killedText(text, textLen);
if (lastAction == actionKill && size > 0) {
int slot = indexToSlot[0];
int currentLen = static_cast<int>(theRing[slot].length());
int resultLen = currentLen + textLen;
Utf32String temp(resultLen + 1);
if (forward) {
memcpy(temp.get(), theRing[slot].get(), currentLen * sizeof(char32_t));
memcpy(&temp[currentLen], killedText.get(), textLen * sizeof(char32_t));
} else {
memcpy(temp.get(), killedText.get(), textLen * sizeof(char32_t));
memcpy(&temp[textLen], theRing[slot].get(),
currentLen * sizeof(char32_t));
}
temp[resultLen] = 0;
temp.initFromBuffer();
theRing[slot] = temp;
} else {
if (size < capacity) {
if (size > 0) {
memmove(&indexToSlot[1], &indexToSlot[0], size);
}
indexToSlot[0] = size;
size++;
theRing.push_back(killedText);
} else {
int slot = indexToSlot[capacity - 1];
theRing[slot] = killedText;
memmove(&indexToSlot[1], &indexToSlot[0], capacity - 1);
indexToSlot[0] = slot;
}
index = 0;
}
}
Utf32String* yank() { return (size > 0) ? &theRing[indexToSlot[index]] : 0; }
Utf32String* yankPop() {
if (size == 0) {
return 0;
}
++index;
if (index == size) {
index = 0;
}
return &theRing[indexToSlot[index]];
}
};
class InputBuffer {
char32_t* buf32; // input buffer
char* charWidths; // character widths from mk_wcwidth()
int buflen; // buffer size in characters
int len; // length of text in input buffer
int pos; // character position in buffer ( 0 <= pos <= len )
void clearScreen(PromptBase& pi);
int incrementalHistorySearch(PromptBase& pi, int startChar);
int completeLine(PromptBase& pi);
void refreshLine(PromptBase& pi);
public:
InputBuffer(char32_t* buffer, char* widthArray, int bufferLen)
: buf32(buffer),
charWidths(widthArray),
buflen(bufferLen - 1),
len(0),
pos(0) {
buf32[0] = 0;
}
void preloadBuffer(const char* preloadText) {
size_t ucharCount = 0;
copyString8to32(buf32, buflen + 1, ucharCount, preloadText);
recomputeCharacterWidths(buf32, charWidths, static_cast<int>(ucharCount));
len = static_cast<int>(ucharCount);
pos = static_cast<int>(ucharCount);
}
int getInputLine(PromptBase& pi);
int length(void) const { return len; }
};
// Special codes for keyboard input:
//
// Between Windows and the various Linux "terminal" programs, there is some
// pretty diverse behavior in the "scan codes" and escape sequences we are
// presented with. So ... we'll translate them all into our own pidgin
// pseudocode, trying to stay out of the way of UTF-8 and international
// characters. Here's the general plan.
//
// "User input keystrokes" (key chords, whatever) will be encoded as a single
// value.
// The low 21 bits are reserved for Unicode characters. Popular function-type
// keys
// get their own codes in the range 0x10200000 to (if needed) 0x1FE00000,
// currently
// just arrow keys, Home, End and Delete. Keypresses with Ctrl get ORed with
// 0x20000000, with Alt get ORed with 0x40000000. So, Ctrl+Alt+Home is encoded
// as 0x20000000 + 0x40000000 + 0x10A00000 == 0x70A00000. To keep things
// complicated,
// the Alt key is equivalent to prefixing the keystroke with ESC, so ESC
// followed by
// D is treated the same as Alt + D ... we'll just use Emacs terminology and
// call
// this "Meta". So, we will encode both ESC followed by D and Alt held down
// while D
// is pressed the same, as Meta-D, encoded as 0x40000064.
//
// Here are the definitions of our component constants:
//
// Maximum unsigned 32-bit value = 0xFFFFFFFF; // For reference, max 32-bit
// value
// Highest allocated Unicode char = 0x001FFFFF; // For reference, max
// Unicode value
static const int META = 0x40000000; // Meta key combination
static const int CTRL = 0x20000000; // Ctrl key combination
// static const int SPECIAL_KEY = 0x10000000; // Common bit for all special
// keys
static const int UP_ARROW_KEY = 0x10200000; // Special keys
static const int DOWN_ARROW_KEY = 0x10400000;
static const int RIGHT_ARROW_KEY = 0x10600000;
static const int LEFT_ARROW_KEY = 0x10800000;
static const int HOME_KEY = 0x10A00000;
static const int END_KEY = 0x10C00000;
static const int DELETE_KEY = 0x10E00000;
static const int PAGE_UP_KEY = 0x11000000;
static const int PAGE_DOWN_KEY = 0x11200000;
static const char* unsupported_term[] = {"dumb", "cons25", "emacs", NULL};
static linenoiseCompletionCallback* completionCallback = NULL;
#ifdef _WIN32
static HANDLE console_in, console_out;
static DWORD oldMode;
static WORD oldDisplayAttribute;
#else
static struct termios orig_termios; /* in order to restore at exit */
#endif
static KillRing killRing;
static int rawmode = 0; /* for atexit() function to check if restore is needed*/
static int atexit_registered = 0; /* register atexit just 1 time */
static int historyMaxLen = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
static int historyLen = 0;
static int historyIndex = 0;
static char8_t** history = NULL;
// used to emulate Windows command prompt on down-arrow after a recall
// we use -2 as our "not set" value because we add 1 to the previous index on
// down-arrow,
// and zero is a valid index (so -1 is a valid "previous index")
static int historyPreviousIndex = -2;
static bool historyRecallMostRecent = false;
static void linenoiseAtExit(void);
static bool isUnsupportedTerm(void) {
char* term = getenv("TERM");
if (term == NULL) return false;
for (int j = 0; unsupported_term[j]; ++j)
if (!strcasecmp(term, unsupported_term[j])) {
return true;
}
return false;
}
static void beep() {
fprintf(stderr, "\x7"); // ctrl-G == bell/beep
fflush(stderr);
}
void linenoiseHistoryFree(void) {
if (history) {
for (int j = 0; j < historyLen; ++j) free(history[j]);
historyLen = 0;
free(history);
history = 0;
}
}
static int enableRawMode(void) {
#ifdef _WIN32
if (!console_in) {
console_in = GetStdHandle(STD_INPUT_HANDLE);
console_out = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleMode(console_in, &oldMode);
SetConsoleMode(console_in, oldMode &
~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT |
ENABLE_PROCESSED_INPUT));
}
return 0;
#else
struct termios raw;
if (!isatty(STDIN_FILENO)) goto fatal;
if (!atexit_registered) {
atexit(linenoiseAtExit);