forked from antirez/linenoise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinenoise.c
3160 lines (2875 loc) · 104 KB
/
linenoise.c
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.
*
* You can find the latest source code at:
*
* http://github.com/oldium/linenoise
*
* Does a number of crazy assumptions that happen to be true in 99.9999% of
* the 2010 UNIX computers around.
*
* ------------------------------------------------------------------------
*
* Copyright (c) 2010-2013, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
* Copyright (c) 2013-2014, Oldrich Jedlicka <oldium dot pro at seznam dot cz>
*
* 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.
*
* ------------------------------------------------------------------------
*
* References:
* - http://github.com/antirez/linenoise
* - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
* - http://www.ecma-international.org/publications/standards/Ecma-035.htm
* - http://www.ecma-international.org/publications/standards/Ecma-048.htm
*
* 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
*
* 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
*
* When multi line mode is enabled, we also use an additional escape
* sequence. However multi line editing is disabled by default.
*
* CUU (Cursor Up)
* Sequence: ESC [ n A
* Effect: moves cursor up of n chars.
*
* CUD (Cursor Down)
* Sequence: ESC [ n B
* Effect: moves cursor down 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
*
*/
#ifndef _WIN32
#define _POSIX_C_SOURCE 200112L
#define _XOPEN_SOURCE 500
#define _BSD_SOURCE
#endif
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Windows.h>
#ifdef __cplusplus_cli
#include <vcclr.h>
#endif
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include "linenoise.h"
#ifndef _WIN32
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <time.h>
#include <locale.h>
#endif
#undef uchar_t
#undef char_t
#undef charpos_t
#undef unicode_t
#ifdef _WIN32
#define setError(x) SetLastError(x)
#define getError() GetLastError()
#define errno_t DWORD
#define ERROR_NONE 0
#define ERROR_EINVAL ERROR_BAD_ARGUMENTS
#define ERROR_ENOMEM ERROR_NOT_ENOUGH_MEMORY
#define ERROR_ERETRY ERROR_RETRY
#define ERROR_ECANCELLED ERROR_CANCELLED
#define ERROR_EAGAIN ERROR_CONTINUE
#define ERROR_EWOULDBLOCK ERROR_CONTINUE
#define bool int
#define true 1
#define false 0
#ifdef _UNICODE
#define TS_SPEC "ls"
#else
#define TS_SPEC "s"
#endif
#define uchar_t TCHAR
#define char_t TCHAR
#define charpos_t size_t
#define unicode_t __int32
#else // _WIN32
#define setError(x) errno = x
#define getError() errno
#define errno_t int
#define ERROR_NONE 0
#define ERROR_EINVAL EINVAL
#define ERROR_ENOMEM ENOMEM
#define ERROR_ERETRY EINTR
#define ERROR_ECANCELLED EINTR
#define ERROR_EAGAIN EAGAIN
#define ERROR_EWOULDBLOCK EWOULDBLOCK
#define ERROR_ENOTTY ENOTTY
#include <termios.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/select.h>
#define _tcslen strlen
#define _tcsdup strdup
#define _tcscmp strcmp
#define _tcsstr strstr
#define _fgetts fgets
#define _tprintf printf
#define _ftprintf_s fprintf
#define _fgetts fgets
#define _tcschr strchr
#define _T(x) x
#define TS_SPEC "s"
#define uchar_t unsigned char
#define char_t char
#define charpos_t size_t
#define unicode_t int32_t
#endif // _WIN32
#ifdef _WIN32
#define RETRY(expression) (expression)
#else
#define RETRY(expression) \
( { int result = (expression); while (result == -1 && getError() == ERROR_ERETRY ) result = (expression); result; } )
#endif
#ifndef CTRL
#define CTRL(c) ((c) & 0x1f)
#endif
#ifndef CERASE
#define CERASE 127
#endif
#define CESC CTRL('[')
typedef struct linenoiseSingleCompletion {
char_t *suggestion; /* Suggestion to display. */
char_t *text; /* Fully completed text. */
charpos_t pos; /* Cursor position. */
size_t suggestion_charlen; /* Length of suggestion string when displayed. */
} linenoiseSingleCompletion;
struct linenoiseCompletions {
bool is_initialized; /* True if completions are initialized. */
size_t len; /* Current number of completions. */
size_t max_charlen; /* Maximum suggestion text length. */
linenoiseSingleCompletion *cvec; /* Array of completions. */
};
#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
#define LINENOISE_LINE_INIT_MAX_AND_GROW 4096
#define LINENOISE_TEMP_STRING_SIZE 8
#define LINENOISE_COL_SPACING 2
#define ANSI_ESCAPE_MAX_LEN 16
#define ANSI_ESCAPE_WAIT_MS 50 /* Wait 50ms for further ANSI codes, otherwise return escape */
#define READ_BACK_MAX_LEN 32
#define MAX_RAW_CHARS 6 /* 6 UTF-8 characters */
#define MIN(a, b) ((a) < (b) ? (a) : (b))
static linenoiseCompletionCallback *completionCallback = NULL;
#ifdef _WIN32
static DWORD orig_inconsolemode; /* In order to restore at exit. */
static DWORD orig_outconsolemode; /* In order to restore at exit. */
static DWORD pending_console_event[16] = {0};
static int pending_console_event_len = 0;
#ifdef __cplusplus_cli
delegate BOOL ConsoleHandler(DWORD CtrlType);
#endif
#else
static struct termios orig_termios; /* In order to restore at exit.*/
#endif
static int rawmode = 0; /* For atexit() function to check if restore is needed*/
static int mlmode = 0; /* Multi line mode. Default is single line. */
static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
static int history_len = 0;
static char_t **history = NULL;
enum LinenoiseState {
LS_NEW_LINE, /* Processing new line. */
LS_READ, /* Reading new line. */
LS_COMPLETION, /* Completing with TAB. */
LS_HISTORY_SEARCH /* Searching with CTRL+R. */
};
enum ReadCharSpecials {
RCS_NONE = 0, /* No character read. */
RCS_ERROR = -1, /* Error. */
RCS_CLOSED = -2, /* Connection has been closed. */
RCS_CANCELLED = -3, /* Line editing has been cancelled. */
RCS_CURSOR_LEFT = -4, /* Left key. */
RCS_CURSOR_RIGHT = -5, /* Right key. */
RCS_CURSOR_UP = -6, /* Up key. */
RCS_CURSOR_DOWN = -7, /* Down key. */
RCS_DELETE = -8, /* Delete key. */
RCS_HOME = -9, /* Home key. */
RCS_END = -10 /* End key. */
};
enum AnsiEscapeState {
AES_NONE = 0, /* Not in escape sequence. */
AES_INTERMEDIATE = 1, /* Intermediate sequence. */
AES_CSI_PARAMETER = 2, /* Inside CSI parameter sequence. */
AES_CSI_INTERMEDIATE = 3, /* Inside CSI intermediate sequence. */
AES_SS_CHARACTER = 4, /* Reading SS2 or SS3 character value. */
AES_FINAL = 5 /* Read final character. */
};
enum AnsiSequenceMeaning {
ASM_C1, /** Read C1 escape sequence. */
ASM_CSI, /** Read CSI escape sequence. */
ASM_G2, /** Read SS2 escape and a character value. */
ASM_G3 /** Read SS3 escape and a character value. */
};
enum LinenoiseResult {
LR_HAVE_TEXT = 1, /** Text is available to be returned. */
LR_CLOSED = 0, /** Connection has been closed with no text to be returned. */
LR_ERROR = -1, /** Error occurred. */
LR_CANCELLED = -2, /** Current line editing has been cancelled. */
LR_CONTINUE = -3 /** Continue reading next character. */
};
typedef struct linenoiseString {
char_t *buf; /* String buffer. */
charpos_t *charindex; /* Starting position of characters. */
size_t buflen; /* String buffer size. */
size_t bytelen; /* String length (in bytes). */
size_t charlen; /* String length (in characters). */
} linenoiseString;
typedef struct linenoiseChar {
unicode_t unicodeChar;
uchar_t rawChars[MAX_RAW_CHARS+1];
size_t rawCharsLen;
} linenoiseChar;
typedef struct linenoiseRawChar {
linenoiseChar currentChar;
#ifdef _WIN32
linenoiseString tempString;
#endif
bool is_emited;
mbstate_t readingState;
} linenoiseRawChar;
#ifndef _WIN32
typedef struct linenoiseAnsi {
linenoiseChar escape; /* Read escape character. */
timer_t ansi_timer; /* Timer to differentiate between ESC and ANSI escape sequence. */
bool ansi_timer_created; /* True whether the timer has been created */
bool ansi_timer_is_active; /* True if the timer is active. */
int ansi_timer_overrun_count; /* Overrun count of timer. */
enum AnsiEscapeState ansi_state; /* ANSI sequence reading state */
struct linenoiseChar ansi_escape[ANSI_ESCAPE_MAX_LEN + 1]; /* RAW read ANSI escape sequence */
char_t ansi_intermediate[ANSI_ESCAPE_MAX_LEN + 1]; /* Intermediate sequence. */
char_t ansi_parameter[ANSI_ESCAPE_MAX_LEN + 1]; /* Parameter sequence. */
char_t ansi_final; /* Final character of sequence. */
enum AnsiSequenceMeaning ansi_sequence_meaning; /* Read sequence meaning. */
int ansi_escape_len; /* Current length of sequence */
int ansi_intermediate_len; /* Current length of intermediate block */
int ansi_parameter_len; /* Current length of parameter block */
linenoiseChar temp_char; /* Temporary character for negative RCS_* codes. */
} linenoiseAnsi;
#endif
typedef struct linenoiseHistorySearchState {
struct linenoiseString text; /* Text to be searched. */
int current_index; /* Current history index. */
bool found; /* True if current text has been fouond. */
} linenoiseHistorySearchState;
/* The linenoiseState structure represents the state during line editing.
* We pass this state to functions implementing specific editing
* functionalities. */
struct linenoiseState {
enum LinenoiseState state; /* Internal state. */
#ifdef _WIN32
HANDLE fdin; /* Terminal file descriptor. */
HANDLE fdout; /* Terminal file descriptor. */
HANDLE wakeup_event; /* Wake-up event for console signals. */
#ifdef __cplusplus_cli
gcroot<ConsoleHandler^> *console_handler_ptr;
gcroot<System::IntPtr^> *console_handler_intptr;
#endif
#else
int fd; /* Terminal file descriptor. */
#endif
bool is_supported; /* True if the terminal is supported. */
linenoiseString line; /* Current edited line. */
linenoiseString prompt; /* Prompt to display. */
linenoiseString tempprompt; /* Temporary prompt to display. */
size_t pos; /* Current cursor position. */
size_t oldpos; /* Previous refresh cursor position. */
size_t oldrpos; /* Previous cursor row position. */
size_t cols; /* Number of columns in terminal. */
#ifdef _WIN32
size_t rows; /* Number of rows in terminal. */
#endif
size_t maxrows; /* Maximum num of rows used so far (multiline mode) */
int history_index; /* The history index we are currently editing. */
bool is_async; /* True when the STDIN is in O_NONBLOCK mode. */
bool needs_refresh; /* True when the lines need to be refreshed. */
bool is_displayed; /* True when the prompt has been displayed. */
bool is_cancelled; /* True when the input has been cancelled (CTRL+C). */
bool is_closed; /* True once the input has been closed. */
linenoiseCompletions comp; /* Line completions. */
bool signals_blocked; /* True when the SIGINT is blocked. */
#ifndef _WIN32
sigset_t sigint_oldmask; /* Old signal mask. */
#endif
linenoiseRawChar rawChar; /* Character reading state. */
#ifndef _WIN32
linenoiseAnsi ansi; /* ANSI escape sequence state machine. */
#endif
linenoiseChar read_back_char[READ_BACK_MAX_LEN]; /* Read-back buffer for characters. */
linenoiseChar read_back_return; /* Read-back character to be returned (not further processed). */
linenoiseChar cached_read_char; /* Cached lastly read character to be processed. */
int read_back_char_len; /* Number of characters in buffer. */
linenoiseHistorySearchState hist_search; /* History search. */
};
static struct linenoiseState state = { /* Line editing state. */
LS_NEW_LINE
};
static volatile bool initialized = false; /* True if line editing has been initialized. */
static const linenoiseChar CHAR_NONE = { RCS_NONE, {0}, 0 };
static const linenoiseChar CHAR_ERROR = { RCS_ERROR, {0}, 0 };
static const linenoiseChar CHAR_CANCELLED = { RCS_CANCELLED, {0}, 0 };
static void linenoiseAtExit(void);
static int refreshLine(struct linenoiseState *l);
static int ensureInitialized(struct linenoiseState *l);
static int initialize(struct linenoiseState *l);
static void updateSize();
static int ensureBufLen(struct linenoiseString *s, size_t requestedBufLen);
static int prepareCustomOutputOnNewLine(struct linenoiseState *l);
static int prepareCustomOutputClearLine(struct linenoiseState *l);
static int freeHistorySearch(struct linenoiseState *l);
/* ======================= Line and buffer manipulation ===================== */
/* Fill character representation 'tempChar' of unicode char 'cs'.
* Returns supplied 'tempChar'. */
static const struct linenoiseChar *getChar(struct linenoiseChar *tempChar, unicode_t cs)
{
errno_t saved_errno = getError();
tempChar->unicodeChar = cs;
if (cs > 0) {
#if !defined(_WIN32)
mbstate_t state;
memset(&state, 0, sizeof(state));
tempChar->rawCharsLen = wcrtomb((char_t*)tempChar->rawChars, cs, &state);
if (tempChar->rawCharsLen == (size_t)-1 || tempChar->rawCharsLen == 0) {
tempChar->unicodeChar = RCS_NONE;
tempChar->rawCharsLen = 0;
}
#else /* _WIN32 && _UNICODE */
int convertedLen = 0;
wchar_t converted[3] = { 0, 0, 0 };
if (cs < 0x010000) {
convertedLen = 1;
converted[0] = (TCHAR)cs;
} else if (cs <= 0x10FFFF) {
unicode_t to_encode = cs - 0x10000;
convertedLen = 2;
converted[0] = (TCHAR)(cs >> 10) + 0xD7C0;
converted[1] = (TCHAR)(cs & 0x3FF) + 0xDC00;
} else {
convertedLen = 0;
}
#if !defined(_UNICODE)
if (convertedLen > 0) {
tempChar->rawCharsLen = WideCharToMultiByte(CP_ACP, 0,
converted, convertedLen, tempChar->rawChars,
MAX_RAW_CHARS, NULL, NULL);
} else {
tempChar->rawCharsLen = 0;
}
#else
memcpy(tempChar->rawChars, converted, convertedLen*sizeof(*converted));
tempChar->rawCharsLen = convertedLen;
#endif
#endif
} else {
tempChar->rawCharsLen = 0;
}
setError(saved_errno);
return tempChar;
}
/* Returns pointer to character at a character position. */
static char_t *getCharAt(struct linenoiseString *s, size_t pos)
{
if (pos >= s->charlen) {
return s->buf + s->charindex[s->charlen];
} else {
return s->buf + s->charindex[pos];
}
}
#ifdef _WIN32
static unicode_t fromUtf16(wchar_t first, wchar_t second)
{
if (first < 0xD800 || first > 0xDFFF) {
return (unicode_t)first;
} else if (first <= 0xDBFF && second >= 0xDC00 && second <= 0xDFFF) {
return ((first & 0x03FF) << 10) + (second & 0x03FF);
} else
return 0;
}
#endif
/* Returns unicode character at a supplied position. */
static unicode_t getUnicodeCharAt(struct linenoiseString *s, size_t pos)
{
#if !defined(_WIN32)
wchar_t c = 0;
errno_t saved_errno = getError();
mbstate_t state;
memset(&state, 0, sizeof(state));
(void) mbrtowc(&c, getCharAt(s, pos), 1, &state);
setError(saved_errno);
return c;
#else /* _WIN32 */
#if !defined(_UNICODE)
WCHAR wide[2] = { 0, 0 };
wchar_t *start = wide;
wchar_t *end = wide + 2;
if (MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED | MB_ERR_INVALID_CHARS, getCharAt(s, pos), 1, (LPWSTR)&wide, 2) == 0)
return 0;
#else /* _WIN32 && _UNICODE */
wchar_t *start = getCharAt(s, pos);
wchar_t *end = getCharAt(s, pos+1);
#endif
return fromUtf16(*start, start+1 < end ? *(start+1) : 0);
#endif /* _WIN32 */
}
/* Returns multi-byte character size at a supplied position. */
static size_t getCharSizeAt(struct linenoiseString *s, size_t pos)
{
if (pos >= s->charlen) {
return 0;
} else {
return s->charindex[pos + 1] - s->charindex[pos];
}
}
/* Check if the byte position is at character boundary. */
static bool isAtCharBoundary(size_t pos, struct linenoiseString *s)
{
size_t i;
for (i = 0; i <= s->charlen; i++) {
if (pos == s->charindex[i]) {
return true;
}
}
return false;
}
/* Find nearest character index from byte position. */
static size_t findNearestCharIndex(size_t pos, struct linenoiseString *s)
{
size_t i;
for (i = 0; i <= s->charlen; i++) {
if (pos <= s->charindex[i]) {
return i;
}
}
return s->charlen;
}
/* Clear linenoiseString (set width to 0). */
static void clearString(struct linenoiseString *s)
{
s->bytelen = s->charlen = 0;
if (s->buf != NULL)
s->buf[0] = '\0';
}
/* Free lineoiseString. */
static void freeString(struct linenoiseString *s)
{
free(s->buf);
free(s->charindex);
s->buf = NULL;
s->charindex = NULL;
s->bytelen = s->charlen = s->buflen = 0;
}
/* ======================= Low level terminal handling ====================== */
/* Set if to use or not the multi line mode. */
void linenoiseSetMultiLine(int ml) {
mlmode = ml;
}
/* Return true if the terminal is not a TTY or the name is in the list of
* terminals we know are not able to understand basic escape sequences. */
static int isUnsupportedTerm(struct linenoiseState *l) {
#ifdef _WIN32
if (GetFileType(l->fdin) == FILE_TYPE_CHAR && GetFileType(l->fdout) == FILE_TYPE_CHAR) return 0;
return 1;
#else
static char *unsupported_term[] = {"dumb","cons25",NULL};
char *term;
int j;
if ( !isatty(l->fd) )
return 1;
term = getenv("TERM");
if (term == NULL) return 0;
for (j = 0; unsupported_term[j]; j++)
if (!strcasecmp(term,unsupported_term[j])) return 1;
return 0;
#endif
}
/* Raw mode: 1960 magic shit. */
static int enableRawMode(struct linenoiseState *l) {
if (!rawmode) {
#ifdef _WIN32
if (!GetConsoleMode(l->fdin, &orig_inconsolemode)) return -1;
if (!SetConsoleMode(l->fdin, ENABLE_WINDOW_INPUT)) return -1;
if (!GetConsoleMode(l->fdout, &orig_outconsolemode)) return -1;
if (!mlmode) {
if (!SetConsoleMode(l->fdout, orig_outconsolemode & ~ENABLE_WRAP_AT_EOL_OUTPUT)) return -1;
}
#else
struct termios raw;
if (tcgetattr(l->fd,&orig_termios) == -1) goto fatal;
raw = orig_termios; /* modify the original mode */
/* input modes: no CR to NL, no parity check, no strip char,
* no start/stop output control. */
raw.c_iflag &= ~(ICRNL | INLCR | INPCK | ISTRIP | IXON);
/* output modes - disable post processing */
raw.c_oflag &= ~(OPOST);
/* control modes - set 8 bit chars */
raw.c_cflag |= (CS8);
/* local modes - choing off, canonical off, no extended functions,
* no signal chars (^Z,^C) */
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN);
/* control chars - set return condition: min number of bytes and timer.
* We want read to return every single byte, without timeout. */
raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
/* put terminal in raw mode after flushing */
if (tcsetattr(l->fd,TCSAFLUSH,&raw) < 0) goto fatal;
#endif
rawmode = 1;
}
return 0;
#ifndef _WIN32
fatal:
setError(ERROR_ENOTTY);
return -1;
#endif
}
/* Disable raw mode. */
static void disableRawMode(struct linenoiseState *l) {
errno_t saved_errno = getError();
/* Don't even check the return value as it's too late. */
if (rawmode) {
#ifdef _WIN32
SetConsoleMode(l->fdin, orig_inconsolemode);
SetConsoleMode(l->fdout, orig_outconsolemode);
rawmode = 0;
#else
if (tcsetattr(l->fd,TCSAFLUSH,&orig_termios) != -1)
rawmode = 0;
#endif
}
setError(saved_errno);
}
/* Try to get the number of columns in the current terminal, or assume 80
* if it fails. */
static bool setSize(struct linenoiseState *l) {
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO info;
bool changed;
if (!GetConsoleScreenBufferInfo(l->fdout, &info)) {
info.dwSize.X = 80;
info.dwSize.Y = 25;
}
changed = l->cols != info.dwSize.X || l->rows != info.dwSize.Y;
l->cols = info.dwSize.X;
l->rows = info.dwSize.Y;
return changed;
#else
struct winsize ws;
bool changed;
if (RETRY(ioctl(1, TIOCGWINSZ, &ws)) == -1 || ws.ws_col == 0)
ws.ws_col = 80;
changed = l->cols != ws.ws_col;
l->cols = ws.ws_col;
return changed;
#endif
}
#ifdef _WIN32
#ifdef __cplusplus_cli
static BOOL console_handler(DWORD win_event)
#else
static BOOL WINAPI console_handler(DWORD win_event)
#endif
{
if (win_event == CTRL_C_EVENT || win_event == CTRL_BREAK_EVENT) {
if (pending_console_event_len <
sizeof(pending_console_event)/sizeof(*pending_console_event)) {
pending_console_event[pending_console_event_len++] = win_event;
}
SetEvent(state.wakeup_event);
return TRUE;
} else {
SetEvent(state.wakeup_event);
return FALSE;
}
}
#endif
/* Block SIGINT, SIGALRM and SIGWINCH signals. */
static bool blockSignals(struct linenoiseState *ls) {
if (!ls->signals_blocked) {
errno_t old_errno = getError();
#ifdef _WIN32
#ifdef __cplusplus_cli
if (ls->console_handler_intptr != nullptr) {
SetConsoleCtrlHandler(static_cast<PHANDLER_ROUTINE>((*ls->console_handler_intptr)->ToPointer()), TRUE);
}
#else
SetConsoleCtrlHandler(console_handler, TRUE);
#endif
#else
sigset_t newset;
sigemptyset(&newset);
sigemptyset(&ls->sigint_oldmask);
sigaddset(&newset, SIGINT);
sigaddset(&newset, SIGALRM);
sigaddset(&newset, SIGWINCH);
pthread_sigmask(SIG_BLOCK, &newset, &ls->sigint_oldmask);
#endif
ls->signals_blocked = true;
setError(old_errno);
return true;
} else {
return false;
}
}
/* Re-enable SIGINT, SIGALRM and SIGWINCH signals. */
static bool revertSignals(struct linenoiseState *ls) {
if (ls->signals_blocked) {
errno_t old_errno = getError();
#ifdef _WIN32
int i;
#ifdef __cplusplus_cli
if (ls->console_handler_intptr != nullptr) {
SetConsoleCtrlHandler(static_cast<PHANDLER_ROUTINE>((*ls->console_handler_intptr)->ToPointer()), FALSE);
}
#else
SetConsoleCtrlHandler(console_handler, FALSE);
#endif
for (i = 0; i < pending_console_event_len; i++)
GenerateConsoleCtrlEvent(pending_console_event[i], 0);
pending_console_event_len = 0;
#else
pthread_sigmask(SIG_SETMASK, &ls->sigint_oldmask, NULL);
#endif
ls->signals_blocked = false;
setError(old_errno);
return true;
} else
return false;
}
/* Clear the screen. Used to handle ctrl+l */
static int clearScreen(struct linenoiseState *ls) {
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO info;
COORD topleft = { 0, 0 };
DWORD n;
if (!GetConsoleScreenBufferInfo(ls->fdout, &info)) return -1;
if (!FillConsoleOutputCharacter(ls->fdout, ' ', (DWORD)(ls->cols * ls->rows), topleft, &n)) return -1;
if (!FillConsoleOutputAttribute(ls->fdout,
FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, (DWORD)(ls->cols * ls->rows),
topleft, &n)) return -1;
if (!SetConsoleCursorPosition(ls->fdout, topleft)) return -1;
#else
if (RETRY(write(ls->fd,"\x1b[H\x1b[2J",7)) <= 0) {
/* nothing to do, just to avoid warning. */
}
#endif
ls->needs_refresh = true;
ls->maxrows = 0;
return 0;
}
/* Clear the screen. Used to handle ctrl+l */
int linenoiseClearScreen(void) {
return clearScreen(&state);
}
/* Beep, used for completion when there is nothing to complete or when all
* the choices were already shown. */
static int linenoiseBeep(void) {
if (fprintf(stderr, "\x7") < 0) return -1;
if (RETRY(fflush(stderr)) == -1) return -1;
return 0;
}
static int cursorMoveLeft(struct linenoiseState *l)
{
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO info;
COORD pos = {0, 0};
if (!GetConsoleScreenBufferInfo(l->fdout, &info)) return -1;
pos.Y = info.dwCursorPosition.Y;
if (!SetConsoleCursorPosition(l->fdout, pos)) return -1;
#else
const char* seq = "\x1b[1G";
if (RETRY(write(l->fd,seq,strlen(seq))) == -1) return -1;
#endif
return 0;
}
static int cursorSetColumn(struct linenoiseState *l, size_t column)
{
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO info;
COORD pos = {(SHORT)column, 0};
if (!GetConsoleScreenBufferInfo(l->fdout, &info)) return -1;
pos.Y = info.dwCursorPosition.Y;
if (!SetConsoleCursorPosition(l->fdout, pos)) return -1;
#else
char seq[64];
if (snprintf(seq,64,"\x1b[%zuG", column+1) < 0) return -1;
if (RETRY(write(l->fd,seq,strlen(seq))) == -1) return -1;
#endif
return 0;
}
static int cursorMoveDown(struct linenoiseState *l, size_t rows)
{
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO info;
COORD pos;
if (!GetConsoleScreenBufferInfo(l->fdout, &info)) return -1;
pos.X = info.dwCursorPosition.X;
pos.Y = (SHORT)(info.dwCursorPosition.Y + rows);
if (pos.Y >= info.dwMaximumWindowSize.Y)
pos.Y = info.dwMaximumWindowSize.Y - 1;
if (!SetConsoleCursorPosition(l->fdout, pos)) return -1;
#else
char seq[64];
if (snprintf(seq,64,"\x1b[%zuB", rows) < 0) return -1;
if (RETRY(write(l->fd,seq,strlen(seq))) == -1) return -1;
#endif
return 0;
}
static int cursorMoveUp(struct linenoiseState *l, size_t rows)
{
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO info;
COORD pos;
if (!GetConsoleScreenBufferInfo(l->fdout, &info)) return -1;
pos.X = info.dwCursorPosition.X;
pos.Y = (SHORT)(info.dwCursorPosition.Y - rows);
if (pos.Y < 0)
pos.Y = 0;
if (!SetConsoleCursorPosition(l->fdout, pos)) return -1;
#else
char seq[64];
if (snprintf(seq,64,"\x1b[%zuA", rows) < 0) return -1;
if (RETRY(write(l->fd,seq,strlen(seq))) == -1) return -1;
#endif
return 0;
}
static int eraseLineEnd(struct linenoiseState *l)
{
#ifdef _WIN32
DWORD oldmode = (DWORD)-1;
CONSOLE_SCREEN_BUFFER_INFO info;
DWORD written = 0;
if (mlmode) {
if (!GetConsoleMode(l->fdout, &oldmode)) return -1;
if (!SetConsoleMode(l->fdout, oldmode & ~ENABLE_WRAP_AT_EOL_OUTPUT)) return -1;
}
if (!GetConsoleScreenBufferInfo(l->fdout, &info)) return -1;
if (!FillConsoleOutputCharacter(l->fdout, _T(' '),
info.dwMaximumWindowSize.X-info.dwCursorPosition.X, info.dwCursorPosition, &written)) return -1;
if (!SetConsoleCursorPosition(l->fdout, info.dwCursorPosition)) return -1;
if (mlmode && oldmode != (DWORD)-1) {
if (!SetConsoleMode(l->fdout, oldmode)) return -1;
}
#else
const char* seq = "\x1b[0K";
if (RETRY(write(l->fd,seq,strlen(seq))) == -1) return -1;
#endif
return 0;
}
static int eraseLineAndMoveUp(struct linenoiseState *l)
{
#ifdef _WIN32
if (cursorSetColumn(l, 0) == -1) return -1;
if (eraseLineEnd(l) == -1) return -1;
if (cursorMoveUp(l, 1) == -1) return -1;
#else
char seq[64];
if (snprintf(seq,64,"\x1b[0G\x1b[0K\x1b[1A") < 0) return -1;
if (RETRY(write(l->fd,seq,strlen(seq))) == -1) return -1;
#endif
return 0;
}
static int writeChar(struct linenoiseState *l, const struct linenoiseChar *c)
{
#ifdef _WIN32
if (!WriteConsole(l->fdout, c->rawChars, (DWORD)c->rawCharsLen, NULL, NULL)) return -1;
#else
if (RETRY(write(l->fd, c->rawChars, c->rawCharsLen * sizeof(char_t))) == -1) return -1;
#endif
return 0;
}
static int writeLine(struct linenoiseState *l, struct linenoiseString *s, size_t pos, size_t count)
{
char_t *buf = getCharAt(s, pos);
size_t end_pos;
size_t len;
#ifdef _WIN32
DWORD written;
#endif
if (pos+count < pos) end_pos = SIZE_MAX;
else end_pos = pos + count;
len = getCharAt(s, end_pos) - buf;
#ifdef _WIN32
if (!WriteConsole(l->fdout, buf, (DWORD)len, &written, NULL)) return -1;
#else
if (RETRY(write(l->fd, buf, len * sizeof(char_t))) == -1) return -1;
#endif
return 0;
}
/* ============================== Completion ================================ */
/* Free a list of completion option populated by linenoiseAddCompletion(). */
static void freeCompletions(struct linenoiseState *ls) {
size_t i;
if (ls->comp.cvec != NULL) {
for (i = 0; i < ls->comp.len; i++) {
free(ls->comp.cvec[i].suggestion);
free(ls->comp.cvec[i].text);
}
free(ls->comp.cvec);
}
ls->comp.is_initialized = false;
ls->comp.cvec = NULL;
ls->comp.len = 0;
ls->comp.max_charlen = 0;
}
/* Compare completions, used for Quick sort. */
static int completitionCompare(const void *first, const void *second)
{
linenoiseSingleCompletion *firstcomp = (linenoiseSingleCompletion *) first;
linenoiseSingleCompletion *secondcomp = (linenoiseSingleCompletion *) second;
#if !defined(WIN32) || defined(_WIN32) && !defined(_UNICODE)
return (strcoll(firstcomp->suggestion, secondcomp->suggestion));
#else
return (wcscoll(firstcomp->suggestion, secondcomp->suggestion));
#endif
}
#ifdef _MSC_VER
__forceinline
#else
__inline__ __attribute__((always_inline))
#endif
static bool parseChar(const char_t **charstart, const char_t **charend, const char_t *srcend, mbstate_t *state)
{
while (*charend < srcend) {
#if !defined(_WIN32)
size_t found = mbrlen(*charend, 1, state);
#elif !defined(_UNICODE)
size_t found = 1;
#else /* _WIN32 && _UNICODE */
size_t found;
if (**charstart < 0xD800 || **charstart > 0xDFFF) {
found = 1;
} else if (**charstart <= 0xDBFF && *charstart+1 < srcend
&& *(*charstart+1) >= 0xDC00 && *(*charstart+1) <= 0xDFFF) {
++*charend;
found = 1;
} else if (*charstart+1 < srcend) {
++*charend;
found = (size_t)-1; /* Invalid sequence. */
} else {
found = (size_t)-2; /* Incomplete sequence. */
}
#endif
if (found == (size_t)-1) {
*charstart = *charend;
continue;
} else if (found != (size_t)-2) {