blob: 72549d21651faac11d050da077a4a0e8eddc7ebd [file] [log] [blame]
Václav Kubernát8eb3b4c2019-01-25 12:14:14 +01001/*
2 * linenoise.hpp -- Multi-platfrom C++ header-only linenoise library.
3 *
4 * All credits and commendations have to go to the authors of the
5 * following excellent libraries.
6 *
7 * - linenoise.h and linenose.c (https://github.com/antirez/linenoise)
8 * - ANSI.c (https://github.com/adoxa/ansicon)
9 * - Win32_ANSI.h and Win32_ANSI.c (https://github.com/MSOpenTech/redis)
10 *
11 * ------------------------------------------------------------------------
12 *
13 * Copyright (c) 2015 yhirose
14 * All rights reserved.
15 *
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions are met:
18 *
19 * 1. Redistributions of source code must retain the above copyright notice, this
20 * list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright notice,
22 * this list of conditions and the following disclaimer in the documentation
23 * and/or other materials provided with the distribution.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
27 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
29 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
32 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 */
36
37/* linenoise.h -- guerrilla line editing library against the idea that a
38 * line editing lib needs to be 20,000 lines of C code.
39 *
40 * See linenoise.c for more information.
41 *
42 * ------------------------------------------------------------------------
43 *
44 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
45 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
46 *
47 * All rights reserved.
48 *
49 * Redistribution and use in source and binary forms, with or without
50 * modification, are permitted provided that the following conditions are
51 * met:
52 *
53 * * Redistributions of source code must retain the above copyright
54 * notice, this list of conditions and the following disclaimer.
55 *
56 * * Redistributions in binary form must reproduce the above copyright
57 * notice, this list of conditions and the following disclaimer in the
58 * documentation and/or other materials provided with the distribution.
59 *
60 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
61 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
62 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
63 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
64 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
65 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
66 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
67 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
68 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
69 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
70 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
71 */
72
73/*
74 * ANSI.c - ANSI escape sequence console driver.
75 *
76 * Copyright (C) 2005-2014 Jason Hood
77 * This software is provided 'as-is', without any express or implied
78 * warranty. In no event will the author be held liable for any damages
79 * arising from the use of this software.
80 *
81 * Permission is granted to anyone to use this software for any purpose,
82 * including commercial applications, and to alter it and redistribute it
83 * freely, subject to the following restrictions:
84 *
85 * 1. The origin of this software must not be misrepresented; you must not
86 * claim that you wrote the original software. If you use this software
87 * in a product, an acknowledgment in the product documentation would be
88 * appreciated but is not required.
89 * 2. Altered source versions must be plainly marked as such, and must not be
90 * misrepresented as being the original software.
91 * 3. This notice may not be removed or altered from any source distribution.
92 *
93 * Jason Hood
94 * jadoxa@yahoo.com.au
95 */
96
97/*
98 * Win32_ANSI.h and Win32_ANSI.c
99 *
100 * Derived from ANSI.c by Jason Hood, from his ansicon project (https://github.com/adoxa/ansicon), with modifications.
101 *
102 * Copyright (c), Microsoft Open Technologies, Inc.
103 * All rights reserved.
104 * Redistribution and use in source and binary forms, with or without
105 * modification, are permitted provided that the following conditions are met:
106 * - Redistributions of source code must retain the above copyright notice,
107 * this list of conditions and the following disclaimer.
108 * - Redistributions in binary form must reproduce the above copyright notice,
109 * this list of conditions and the following disclaimer in the documentation
110 * and/or other materials provided with the distribution.
111 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
112 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
113 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
114 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
115 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
116 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
117 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
118 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
119 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
120 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
121 */
122
123#ifndef LINENOISE_HPP
124#define LINENOISE_HPP
125
126#ifndef _WIN32
127#include <termios.h>
128#include <unistd.h>
129#include <sys/ioctl.h>
130#else
131#ifndef NOMINMAX
132#define NOMINMAX
133#endif
134#include <Windows.h>
135#include <io.h>
136#ifndef STDIN_FILENO
137#define STDIN_FILENO (_fileno(stdin))
138#endif
139#ifndef STDOUT_FILENO
140#define STDOUT_FILENO 1
141#endif
142#define isatty _isatty
143#define write win32_write
144#define read _read
145#endif
146#include <stdlib.h>
147#include <stdio.h>
148#include <errno.h>
149#include <string.h>
150#include <stdlib.h>
151#include <ctype.h>
152#include <sys/types.h>
153#include <string>
154#include <fstream>
155#include <functional>
156#include <vector>
157#include <iostream>
158
159namespace linenoise {
160
161typedef std::function<void (const char*, std::vector<std::string>&)> CompletionCallback;
162
163#ifdef _WIN32
164
165namespace ansi {
166
167#define lenof(array) (sizeof(array)/sizeof(*(array)))
168
169typedef struct
170{
171 BYTE foreground; // ANSI base color (0 to 7; add 30)
172 BYTE background; // ANSI base color (0 to 7; add 40)
173 BYTE bold; // console FOREGROUND_INTENSITY bit
174 BYTE underline; // console BACKGROUND_INTENSITY bit
175 BYTE rvideo; // swap foreground/bold & background/underline
176 BYTE concealed; // set foreground/bold to background/underline
177 BYTE reverse; // swap console foreground & background attributes
178} GRM, *PGRM; // Graphic Rendition Mode
179
180
181inline bool is_digit(char c) { return '0' <= c && c <= '9'; }
182
183// ========== Global variables and constants
184
185HANDLE hConOut; // handle to CONOUT$
186
187const char ESC = '\x1B'; // ESCape character
188const char BEL = '\x07';
189const char SO = '\x0E'; // Shift Out
190const char SI = '\x0F'; // Shift In
191
192const int MAX_ARG = 16; // max number of args in an escape sequence
193int state; // automata state
194WCHAR prefix; // escape sequence prefix ( '[', ']' or '(' );
195WCHAR prefix2; // secondary prefix ( '?' or '>' );
196WCHAR suffix; // escape sequence suffix
197int es_argc; // escape sequence args count
198int es_argv[MAX_ARG]; // escape sequence args
199WCHAR Pt_arg[MAX_PATH * 2]; // text parameter for Operating System Command
200int Pt_len;
201BOOL shifted;
202
203
204// DEC Special Graphics Character Set from
205// http://vt100.net/docs/vt220-rm/table2-4.html
206// Some of these may not look right, depending on the font and code page (in
207// particular, the Control Pictures probably won't work at all).
208const WCHAR G1[] =
209{
210 ' ', // _ - blank
211 L'\x2666', // ` - Black Diamond Suit
212 L'\x2592', // a - Medium Shade
213 L'\x2409', // b - HT
214 L'\x240c', // c - FF
215 L'\x240d', // d - CR
216 L'\x240a', // e - LF
217 L'\x00b0', // f - Degree Sign
218 L'\x00b1', // g - Plus-Minus Sign
219 L'\x2424', // h - NL
220 L'\x240b', // i - VT
221 L'\x2518', // j - Box Drawings Light Up And Left
222 L'\x2510', // k - Box Drawings Light Down And Left
223 L'\x250c', // l - Box Drawings Light Down And Right
224 L'\x2514', // m - Box Drawings Light Up And Right
225 L'\x253c', // n - Box Drawings Light Vertical And Horizontal
226 L'\x00af', // o - SCAN 1 - Macron
227 L'\x25ac', // p - SCAN 3 - Black Rectangle
228 L'\x2500', // q - SCAN 5 - Box Drawings Light Horizontal
229 L'_', // r - SCAN 7 - Low Line
230 L'_', // s - SCAN 9 - Low Line
231 L'\x251c', // t - Box Drawings Light Vertical And Right
232 L'\x2524', // u - Box Drawings Light Vertical And Left
233 L'\x2534', // v - Box Drawings Light Up And Horizontal
234 L'\x252c', // w - Box Drawings Light Down And Horizontal
235 L'\x2502', // x - Box Drawings Light Vertical
236 L'\x2264', // y - Less-Than Or Equal To
237 L'\x2265', // z - Greater-Than Or Equal To
238 L'\x03c0', // { - Greek Small Letter Pi
239 L'\x2260', // | - Not Equal To
240 L'\x00a3', // } - Pound Sign
241 L'\x00b7', // ~ - Middle Dot
242};
243
244#define FIRST_G1 '_'
245#define LAST_G1 '~'
246
247
248// color constants
249
250#define FOREGROUND_BLACK 0
251#define FOREGROUND_WHITE FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE
252
253#define BACKGROUND_BLACK 0
254#define BACKGROUND_WHITE BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE
255
256const BYTE foregroundcolor[8] =
257 {
258 FOREGROUND_BLACK, // black foreground
259 FOREGROUND_RED, // red foreground
260 FOREGROUND_GREEN, // green foreground
261 FOREGROUND_RED | FOREGROUND_GREEN, // yellow foreground
262 FOREGROUND_BLUE, // blue foreground
263 FOREGROUND_BLUE | FOREGROUND_RED, // magenta foreground
264 FOREGROUND_BLUE | FOREGROUND_GREEN, // cyan foreground
265 FOREGROUND_WHITE // white foreground
266 };
267
268const BYTE backgroundcolor[8] =
269 {
270 BACKGROUND_BLACK, // black background
271 BACKGROUND_RED, // red background
272 BACKGROUND_GREEN, // green background
273 BACKGROUND_RED | BACKGROUND_GREEN, // yellow background
274 BACKGROUND_BLUE, // blue background
275 BACKGROUND_BLUE | BACKGROUND_RED, // magenta background
276 BACKGROUND_BLUE | BACKGROUND_GREEN, // cyan background
277 BACKGROUND_WHITE, // white background
278 };
279
280const BYTE attr2ansi[8] = // map console attribute to ANSI number
281{
282 0, // black
283 4, // blue
284 2, // green
285 6, // cyan
286 1, // red
287 5, // magenta
288 3, // yellow
289 7 // white
290};
291
292GRM grm;
293
294// saved cursor position
295COORD SavePos;
296
297// ========== Print Buffer functions
298
299#define BUFFER_SIZE 2048
300
301int nCharInBuffer;
302WCHAR ChBuffer[BUFFER_SIZE];
303
304//-----------------------------------------------------------------------------
305// FlushBuffer()
306// Writes the buffer to the console and empties it.
307//-----------------------------------------------------------------------------
308
309inline void FlushBuffer(void)
310{
311 DWORD nWritten;
312 if (nCharInBuffer <= 0) return;
313 WriteConsoleW(hConOut, ChBuffer, nCharInBuffer, &nWritten, NULL);
314 nCharInBuffer = 0;
315}
316
317//-----------------------------------------------------------------------------
318// PushBuffer( WCHAR c )
319// Adds a character in the buffer.
320//-----------------------------------------------------------------------------
321
322inline void PushBuffer(WCHAR c)
323{
324 if (shifted && c >= FIRST_G1 && c <= LAST_G1)
325 c = G1[c - FIRST_G1];
326 ChBuffer[nCharInBuffer] = c;
327 if (++nCharInBuffer == BUFFER_SIZE)
328 FlushBuffer();
329}
330
331//-----------------------------------------------------------------------------
332// SendSequence( LPCWSTR seq )
333// Send the string to the input buffer.
334//-----------------------------------------------------------------------------
335
336inline void SendSequence(LPCWSTR seq)
337{
338 DWORD out;
339 INPUT_RECORD in;
340 HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
341
342 in.EventType = KEY_EVENT;
343 in.Event.KeyEvent.bKeyDown = TRUE;
344 in.Event.KeyEvent.wRepeatCount = 1;
345 in.Event.KeyEvent.wVirtualKeyCode = 0;
346 in.Event.KeyEvent.wVirtualScanCode = 0;
347 in.Event.KeyEvent.dwControlKeyState = 0;
348 for (; *seq; ++seq)
349 {
350 in.Event.KeyEvent.uChar.UnicodeChar = *seq;
351 WriteConsoleInput(hStdIn, &in, 1, &out);
352 }
353}
354
355// ========== Print functions
356
357//-----------------------------------------------------------------------------
358// InterpretEscSeq()
359// Interprets the last escape sequence scanned by ParseAndPrintANSIString
360// prefix escape sequence prefix
361// es_argc escape sequence args count
362// es_argv[] escape sequence args array
363// suffix escape sequence suffix
364//
365// for instance, with \e[33;45;1m we have
366// prefix = '[',
367// es_argc = 3, es_argv[0] = 33, es_argv[1] = 45, es_argv[2] = 1
368// suffix = 'm'
369//-----------------------------------------------------------------------------
370
371inline void InterpretEscSeq(void)
372{
373 int i;
374 WORD attribut;
375 CONSOLE_SCREEN_BUFFER_INFO Info;
376 CONSOLE_CURSOR_INFO CursInfo;
377 DWORD len, NumberOfCharsWritten;
378 COORD Pos;
379 SMALL_RECT Rect;
380 CHAR_INFO CharInfo;
381
382 if (prefix == '[')
383 {
384 if (prefix2 == '?' && (suffix == 'h' || suffix == 'l'))
385 {
386 if (es_argc == 1 && es_argv[0] == 25)
387 {
388 GetConsoleCursorInfo(hConOut, &CursInfo);
389 CursInfo.bVisible = (suffix == 'h');
390 SetConsoleCursorInfo(hConOut, &CursInfo);
391 return;
392 }
393 }
394 // Ignore any other \e[? or \e[> sequences.
395 if (prefix2 != 0)
396 return;
397
398 GetConsoleScreenBufferInfo(hConOut, &Info);
399 switch (suffix)
400 {
401 case 'm':
402 if (es_argc == 0) es_argv[es_argc++] = 0;
403 for (i = 0; i < es_argc; i++)
404 {
405 if (30 <= es_argv[i] && es_argv[i] <= 37)
406 grm.foreground = es_argv[i] - 30;
407 else if (40 <= es_argv[i] && es_argv[i] <= 47)
408 grm.background = es_argv[i] - 40;
409 else switch (es_argv[i])
410 {
411 case 0:
412 case 39:
413 case 49:
414 {
415 WCHAR def[4];
416 int a;
417 *def = '7'; def[1] = '\0';
418 GetEnvironmentVariableW(L"ANSICON_DEF", def, lenof(def));
419 a = wcstol(def, NULL, 16);
420 grm.reverse = FALSE;
421 if (a < 0)
422 {
423 grm.reverse = TRUE;
424 a = -a;
425 }
426 if (es_argv[i] != 49)
427 grm.foreground = attr2ansi[a & 7];
428 if (es_argv[i] != 39)
429 grm.background = attr2ansi[(a >> 4) & 7];
430 if (es_argv[i] == 0)
431 {
432 if (es_argc == 1)
433 {
434 grm.bold = a & FOREGROUND_INTENSITY;
435 grm.underline = a & BACKGROUND_INTENSITY;
436 }
437 else
438 {
439 grm.bold = 0;
440 grm.underline = 0;
441 }
442 grm.rvideo = 0;
443 grm.concealed = 0;
444 }
445 }
446 break;
447
448 case 1: grm.bold = FOREGROUND_INTENSITY; break;
449 case 5: // blink
450 case 4: grm.underline = BACKGROUND_INTENSITY; break;
451 case 7: grm.rvideo = 1; break;
452 case 8: grm.concealed = 1; break;
453 case 21: // oops, this actually turns on double underline
454 case 22: grm.bold = 0; break;
455 case 25:
456 case 24: grm.underline = 0; break;
457 case 27: grm.rvideo = 0; break;
458 case 28: grm.concealed = 0; break;
459 }
460 }
461 if (grm.concealed)
462 {
463 if (grm.rvideo)
464 {
465 attribut = foregroundcolor[grm.foreground]
466 | backgroundcolor[grm.foreground];
467 if (grm.bold)
468 attribut |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
469 }
470 else
471 {
472 attribut = foregroundcolor[grm.background]
473 | backgroundcolor[grm.background];
474 if (grm.underline)
475 attribut |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
476 }
477 }
478 else if (grm.rvideo)
479 {
480 attribut = foregroundcolor[grm.background]
481 | backgroundcolor[grm.foreground];
482 if (grm.bold)
483 attribut |= BACKGROUND_INTENSITY;
484 if (grm.underline)
485 attribut |= FOREGROUND_INTENSITY;
486 }
487 else
488 attribut = foregroundcolor[grm.foreground] | grm.bold
489 | backgroundcolor[grm.background] | grm.underline;
490 if (grm.reverse)
491 attribut = ((attribut >> 4) & 15) | ((attribut & 15) << 4);
492 SetConsoleTextAttribute(hConOut, attribut);
493 return;
494
495 case 'J':
496 if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[J == ESC[0J
497 if (es_argc != 1) return;
498 switch (es_argv[0])
499 {
500 case 0: // ESC[0J erase from cursor to end of display
501 len = (Info.dwSize.Y - Info.dwCursorPosition.Y - 1) * Info.dwSize.X
502 + Info.dwSize.X - Info.dwCursorPosition.X - 1;
503 FillConsoleOutputCharacter(hConOut, ' ', len,
504 Info.dwCursorPosition,
505 &NumberOfCharsWritten);
506 FillConsoleOutputAttribute(hConOut, Info.wAttributes, len,
507 Info.dwCursorPosition,
508 &NumberOfCharsWritten);
509 return;
510
511 case 1: // ESC[1J erase from start to cursor.
512 Pos.X = 0;
513 Pos.Y = 0;
514 len = Info.dwCursorPosition.Y * Info.dwSize.X
515 + Info.dwCursorPosition.X + 1;
516 FillConsoleOutputCharacter(hConOut, ' ', len, Pos,
517 &NumberOfCharsWritten);
518 FillConsoleOutputAttribute(hConOut, Info.wAttributes, len, Pos,
519 &NumberOfCharsWritten);
520 return;
521
522 case 2: // ESC[2J Clear screen and home cursor
523 Pos.X = 0;
524 Pos.Y = 0;
525 len = Info.dwSize.X * Info.dwSize.Y;
526 FillConsoleOutputCharacter(hConOut, ' ', len, Pos,
527 &NumberOfCharsWritten);
528 FillConsoleOutputAttribute(hConOut, Info.wAttributes, len, Pos,
529 &NumberOfCharsWritten);
530 SetConsoleCursorPosition(hConOut, Pos);
531 return;
532
533 default:
534 return;
535 }
536
537 case 'K':
538 if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[K == ESC[0K
539 if (es_argc != 1) return;
540 switch (es_argv[0])
541 {
542 case 0: // ESC[0K Clear to end of line
543 len = Info.dwSize.X - Info.dwCursorPosition.X + 1;
544 FillConsoleOutputCharacter(hConOut, ' ', len,
545 Info.dwCursorPosition,
546 &NumberOfCharsWritten);
547 FillConsoleOutputAttribute(hConOut, Info.wAttributes, len,
548 Info.dwCursorPosition,
549 &NumberOfCharsWritten);
550 return;
551
552 case 1: // ESC[1K Clear from start of line to cursor
553 Pos.X = 0;
554 Pos.Y = Info.dwCursorPosition.Y;
555 FillConsoleOutputCharacter(hConOut, ' ',
556 Info.dwCursorPosition.X + 1, Pos,
557 &NumberOfCharsWritten);
558 FillConsoleOutputAttribute(hConOut, Info.wAttributes,
559 Info.dwCursorPosition.X + 1, Pos,
560 &NumberOfCharsWritten);
561 return;
562
563 case 2: // ESC[2K Clear whole line.
564 Pos.X = 0;
565 Pos.Y = Info.dwCursorPosition.Y;
566 FillConsoleOutputCharacter(hConOut, ' ', Info.dwSize.X, Pos,
567 &NumberOfCharsWritten);
568 FillConsoleOutputAttribute(hConOut, Info.wAttributes,
569 Info.dwSize.X, Pos,
570 &NumberOfCharsWritten);
571 return;
572
573 default:
574 return;
575 }
576
577 case 'X': // ESC[#X Erase # characters.
578 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[X == ESC[1X
579 if (es_argc != 1) return;
580 FillConsoleOutputCharacter(hConOut, ' ', es_argv[0],
581 Info.dwCursorPosition,
582 &NumberOfCharsWritten);
583 FillConsoleOutputAttribute(hConOut, Info.wAttributes, es_argv[0],
584 Info.dwCursorPosition,
585 &NumberOfCharsWritten);
586 return;
587
588 case 'L': // ESC[#L Insert # blank lines.
589 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[L == ESC[1L
590 if (es_argc != 1) return;
591 Rect.Left = 0;
592 Rect.Top = Info.dwCursorPosition.Y;
593 Rect.Right = Info.dwSize.X - 1;
594 Rect.Bottom = Info.dwSize.Y - 1;
595 Pos.X = 0;
596 Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
597 CharInfo.Char.UnicodeChar = ' ';
598 CharInfo.Attributes = Info.wAttributes;
599 ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Pos, &CharInfo);
600 return;
601
602 case 'M': // ESC[#M Delete # lines.
603 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[M == ESC[1M
604 if (es_argc != 1) return;
605 if (es_argv[0] > Info.dwSize.Y - Info.dwCursorPosition.Y)
606 es_argv[0] = Info.dwSize.Y - Info.dwCursorPosition.Y;
607 Rect.Left = 0;
608 Rect.Top = Info.dwCursorPosition.Y + es_argv[0];
609 Rect.Right = Info.dwSize.X - 1;
610 Rect.Bottom = Info.dwSize.Y - 1;
611 Pos.X = 0;
612 Pos.Y = Info.dwCursorPosition.Y;
613 CharInfo.Char.UnicodeChar = ' ';
614 CharInfo.Attributes = Info.wAttributes;
615 ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Pos, &CharInfo);
616 return;
617
618 case 'P': // ESC[#P Delete # characters.
619 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[P == ESC[1P
620 if (es_argc != 1) return;
621 if (Info.dwCursorPosition.X + es_argv[0] > Info.dwSize.X - 1)
622 es_argv[0] = Info.dwSize.X - Info.dwCursorPosition.X;
623 Rect.Left = Info.dwCursorPosition.X + es_argv[0];
624 Rect.Top = Info.dwCursorPosition.Y;
625 Rect.Right = Info.dwSize.X - 1;
626 Rect.Bottom = Info.dwCursorPosition.Y;
627 CharInfo.Char.UnicodeChar = ' ';
628 CharInfo.Attributes = Info.wAttributes;
629 ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Info.dwCursorPosition,
630 &CharInfo);
631 return;
632
633 case '@': // ESC[#@ Insert # blank characters.
634 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[@ == ESC[1@
635 if (es_argc != 1) return;
636 if (Info.dwCursorPosition.X + es_argv[0] > Info.dwSize.X - 1)
637 es_argv[0] = Info.dwSize.X - Info.dwCursorPosition.X;
638 Rect.Left = Info.dwCursorPosition.X;
639 Rect.Top = Info.dwCursorPosition.Y;
640 Rect.Right = Info.dwSize.X - 1 - es_argv[0];
641 Rect.Bottom = Info.dwCursorPosition.Y;
642 Pos.X = Info.dwCursorPosition.X + es_argv[0];
643 Pos.Y = Info.dwCursorPosition.Y;
644 CharInfo.Char.UnicodeChar = ' ';
645 CharInfo.Attributes = Info.wAttributes;
646 ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Pos, &CharInfo);
647 return;
648
649 case 'k': // ESC[#k
650 case 'A': // ESC[#A Moves cursor up # lines
651 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[A == ESC[1A
652 if (es_argc != 1) return;
653 Pos.Y = Info.dwCursorPosition.Y - es_argv[0];
654 if (Pos.Y < 0) Pos.Y = 0;
655 Pos.X = Info.dwCursorPosition.X;
656 SetConsoleCursorPosition(hConOut, Pos);
657 return;
658
659 case 'e': // ESC[#e
660 case 'B': // ESC[#B Moves cursor down # lines
661 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[B == ESC[1B
662 if (es_argc != 1) return;
663 Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
664 if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
665 Pos.X = Info.dwCursorPosition.X;
666 SetConsoleCursorPosition(hConOut, Pos);
667 return;
668
669 case 'a': // ESC[#a
670 case 'C': // ESC[#C Moves cursor forward # spaces
671 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[C == ESC[1C
672 if (es_argc != 1) return;
673 Pos.X = Info.dwCursorPosition.X + es_argv[0];
674 if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
675 Pos.Y = Info.dwCursorPosition.Y;
676 SetConsoleCursorPosition(hConOut, Pos);
677 return;
678
679 case 'j': // ESC[#j
680 case 'D': // ESC[#D Moves cursor back # spaces
681 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[D == ESC[1D
682 if (es_argc != 1) return;
683 Pos.X = Info.dwCursorPosition.X - es_argv[0];
684 if (Pos.X < 0) Pos.X = 0;
685 Pos.Y = Info.dwCursorPosition.Y;
686 SetConsoleCursorPosition(hConOut, Pos);
687 return;
688
689 case 'E': // ESC[#E Moves cursor down # lines, column 1.
690 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[E == ESC[1E
691 if (es_argc != 1) return;
692 Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
693 if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
694 Pos.X = 0;
695 SetConsoleCursorPosition(hConOut, Pos);
696 return;
697
698 case 'F': // ESC[#F Moves cursor up # lines, column 1.
699 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[F == ESC[1F
700 if (es_argc != 1) return;
701 Pos.Y = Info.dwCursorPosition.Y - es_argv[0];
702 if (Pos.Y < 0) Pos.Y = 0;
703 Pos.X = 0;
704 SetConsoleCursorPosition(hConOut, Pos);
705 return;
706
707 case '`': // ESC[#`
708 case 'G': // ESC[#G Moves cursor column # in current row.
709 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[G == ESC[1G
710 if (es_argc != 1) return;
711 Pos.X = es_argv[0] - 1;
712 if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
713 if (Pos.X < 0) Pos.X = 0;
714 Pos.Y = Info.dwCursorPosition.Y;
715 SetConsoleCursorPosition(hConOut, Pos);
716 return;
717
718 case 'd': // ESC[#d Moves cursor row #, current column.
719 if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[d == ESC[1d
720 if (es_argc != 1) return;
721 Pos.Y = es_argv[0] - 1;
722 if (Pos.Y < 0) Pos.Y = 0;
723 if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
724 SetConsoleCursorPosition(hConOut, Pos);
725 return;
726
727 case 'f': // ESC[#;#f
728 case 'H': // ESC[#;#H Moves cursor to line #, column #
729 if (es_argc == 0)
730 es_argv[es_argc++] = 1; // ESC[H == ESC[1;1H
731 if (es_argc == 1)
732 es_argv[es_argc++] = 1; // ESC[#H == ESC[#;1H
733 if (es_argc > 2) return;
734 Pos.X = es_argv[1] - 1;
735 if (Pos.X < 0) Pos.X = 0;
736 if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
737 Pos.Y = es_argv[0] - 1;
738 if (Pos.Y < 0) Pos.Y = 0;
739 if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
740 SetConsoleCursorPosition(hConOut, Pos);
741 return;
742
743 case 's': // ESC[s Saves cursor position for recall later
744 if (es_argc != 0) return;
745 SavePos = Info.dwCursorPosition;
746 return;
747
748 case 'u': // ESC[u Return to saved cursor position
749 if (es_argc != 0) return;
750 SetConsoleCursorPosition(hConOut, SavePos);
751 return;
752
753 case 'n': // ESC[#n Device status report
754 if (es_argc != 1) return; // ESC[n == ESC[0n -> ignored
755 switch (es_argv[0])
756 {
757 case 5: // ESC[5n Report status
758 SendSequence(L"\33[0n"); // "OK"
759 return;
760
761 case 6: // ESC[6n Report cursor position
762 {
763 WCHAR buf[32];
764 swprintf(buf, 32, L"\33[%d;%dR", Info.dwCursorPosition.Y + 1,
765 Info.dwCursorPosition.X + 1);
766 SendSequence(buf);
767 }
768 return;
769
770 default:
771 return;
772 }
773
774 case 't': // ESC[#t Window manipulation
775 if (es_argc != 1) return;
776 if (es_argv[0] == 21) // ESC[21t Report xterm window's title
777 {
778 WCHAR buf[MAX_PATH * 2];
779 DWORD len = GetConsoleTitleW(buf + 3, lenof(buf) - 3 - 2);
780 // Too bad if it's too big or fails.
781 buf[0] = ESC;
782 buf[1] = ']';
783 buf[2] = 'l';
784 buf[3 + len] = ESC;
785 buf[3 + len + 1] = '\\';
786 buf[3 + len + 2] = '\0';
787 SendSequence(buf);
788 }
789 return;
790
791 default:
792 return;
793 }
794 }
795 else // (prefix == ']')
796 {
797 // Ignore any \e]? or \e]> sequences.
798 if (prefix2 != 0)
799 return;
800
801 if (es_argc == 1 && es_argv[0] == 0) // ESC]0;titleST
802 {
803 SetConsoleTitleW(Pt_arg);
804 }
805 }
806}
807
808//-----------------------------------------------------------------------------
809// ParseAndPrintANSIString(hDev, lpBuffer, nNumberOfBytesToWrite)
810// Parses the string lpBuffer, interprets the escapes sequences and prints the
811// characters in the device hDev (console).
812// The lexer is a three states automata.
813// If the number of arguments es_argc > MAX_ARG, only the MAX_ARG-1 firsts and
814// the last arguments are processed (no es_argv[] overflow).
815//-----------------------------------------------------------------------------
816
817inline BOOL ParseAndPrintANSIString(HANDLE hDev, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten)
818{
819 DWORD i;
820 LPCSTR s;
821
822 if (hDev != hConOut) // reinit if device has changed
823 {
824 hConOut = hDev;
825 state = 1;
826 shifted = FALSE;
827 }
828 for (i = nNumberOfBytesToWrite, s = (LPCSTR)lpBuffer; i > 0; i--, s++)
829 {
830 if (state == 1)
831 {
832 if (*s == ESC) state = 2;
833 else if (*s == SO) shifted = TRUE;
834 else if (*s == SI) shifted = FALSE;
835 else PushBuffer(*s);
836 }
837 else if (state == 2)
838 {
839 if (*s == ESC); // \e\e...\e == \e
840 else if ((*s == '[') || (*s == ']'))
841 {
842 FlushBuffer();
843 prefix = *s;
844 prefix2 = 0;
845 state = 3;
846 Pt_len = 0;
847 *Pt_arg = '\0';
848 }
849 else if (*s == ')' || *s == '(') state = 6;
850 else state = 1;
851 }
852 else if (state == 3)
853 {
854 if (is_digit(*s))
855 {
856 es_argc = 0;
857 es_argv[0] = *s - '0';
858 state = 4;
859 }
860 else if (*s == ';')
861 {
862 es_argc = 1;
863 es_argv[0] = 0;
864 es_argv[1] = 0;
865 state = 4;
866 }
867 else if (*s == '?' || *s == '>')
868 {
869 prefix2 = *s;
870 }
871 else
872 {
873 es_argc = 0;
874 suffix = *s;
875 InterpretEscSeq();
876 state = 1;
877 }
878 }
879 else if (state == 4)
880 {
881 if (is_digit(*s))
882 {
883 es_argv[es_argc] = 10 * es_argv[es_argc] + (*s - '0');
884 }
885 else if (*s == ';')
886 {
887 if (es_argc < MAX_ARG - 1) es_argc++;
888 es_argv[es_argc] = 0;
889 if (prefix == ']')
890 state = 5;
891 }
892 else
893 {
894 es_argc++;
895 suffix = *s;
896 InterpretEscSeq();
897 state = 1;
898 }
899 }
900 else if (state == 5)
901 {
902 if (*s == BEL)
903 {
904 Pt_arg[Pt_len] = '\0';
905 InterpretEscSeq();
906 state = 1;
907 }
908 else if (*s == '\\' && Pt_len > 0 && Pt_arg[Pt_len - 1] == ESC)
909 {
910 Pt_arg[--Pt_len] = '\0';
911 InterpretEscSeq();
912 state = 1;
913 }
914 else if (Pt_len < lenof(Pt_arg) - 1)
915 Pt_arg[Pt_len++] = *s;
916 }
917 else if (state == 6)
918 {
919 // Ignore it (ESC ) 0 is implicit; nothing else is supported).
920 state = 1;
921 }
922 }
923 FlushBuffer();
924 if (lpNumberOfBytesWritten != NULL)
925 *lpNumberOfBytesWritten = nNumberOfBytesToWrite - i;
926 return (i == 0);
927}
928
929} // namespace ansi
930
931HANDLE hOut;
932HANDLE hIn;
933DWORD consolemodeIn = 0;
934
935inline int win32read(int *c) {
936 DWORD foo;
937 INPUT_RECORD b;
938 KEY_EVENT_RECORD e;
939 BOOL altgr;
940
941 while (1) {
942 if (!ReadConsoleInput(hIn, &b, 1, &foo)) return 0;
943 if (!foo) return 0;
944
945 if (b.EventType == KEY_EVENT && b.Event.KeyEvent.bKeyDown) {
946
947 e = b.Event.KeyEvent;
948 *c = b.Event.KeyEvent.uChar.AsciiChar;
949
950 altgr = e.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_ALT_PRESSED);
951
952 if (e.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED) && !altgr) {
953
954 /* Ctrl+Key */
955 switch (*c) {
956 case 'D':
957 *c = 4;
958 return 1;
959 case 'C':
960 *c = 3;
961 return 1;
962 case 'H':
963 *c = 8;
964 return 1;
965 case 'T':
966 *c = 20;
967 return 1;
968 case 'B': /* ctrl-b, left_arrow */
969 *c = 2;
970 return 1;
971 case 'F': /* ctrl-f right_arrow*/
972 *c = 6;
973 return 1;
974 case 'P': /* ctrl-p up_arrow*/
975 *c = 16;
976 return 1;
977 case 'N': /* ctrl-n down_arrow*/
978 *c = 14;
979 return 1;
980 case 'U': /* Ctrl+u, delete the whole line. */
981 *c = 21;
982 return 1;
983 case 'K': /* Ctrl+k, delete from current to end of line. */
984 *c = 11;
985 return 1;
986 case 'A': /* Ctrl+a, go to the start of the line */
987 *c = 1;
988 return 1;
989 case 'E': /* ctrl+e, go to the end of the line */
990 *c = 5;
991 return 1;
992 }
993
994 /* Other Ctrl+KEYs ignored */
995 } else {
996
997 switch (e.wVirtualKeyCode) {
998
999 case VK_ESCAPE: /* ignore - send ctrl-c, will return -1 */
1000 *c = 3;
1001 return 1;
1002 case VK_RETURN: /* enter */
1003 *c = 13;
1004 return 1;
1005 case VK_LEFT: /* left */
1006 *c = 2;
1007 return 1;
1008 case VK_RIGHT: /* right */
1009 *c = 6;
1010 return 1;
1011 case VK_UP: /* up */
1012 *c = 16;
1013 return 1;
1014 case VK_DOWN: /* down */
1015 *c = 14;
1016 return 1;
1017 case VK_HOME:
1018 *c = 1;
1019 return 1;
1020 case VK_END:
1021 *c = 5;
1022 return 1;
1023 case VK_BACK:
1024 *c = 8;
1025 return 1;
1026 case VK_DELETE:
1027 *c = 127;
1028 return 1;
1029 default:
1030 if (*c) return 1;
1031 }
1032 }
1033 }
1034 }
1035
1036 return -1; /* Makes compiler happy */
1037}
1038
1039inline int win32_write(int fd, const void *buffer, unsigned int count) {
1040 if (fd == _fileno(stdout)) {
1041 DWORD bytesWritten = 0;
1042 if (FALSE != ansi::ParseAndPrintANSIString(GetStdHandle(STD_OUTPUT_HANDLE), buffer, (DWORD)count, &bytesWritten)) {
1043 return (int)bytesWritten;
1044 } else {
1045 errno = GetLastError();
1046 return 0;
1047 }
1048 } else if (fd == _fileno(stderr)) {
1049 DWORD bytesWritten = 0;
1050 if (FALSE != ansi::ParseAndPrintANSIString(GetStdHandle(STD_ERROR_HANDLE), buffer, (DWORD)count, &bytesWritten)) {
1051 return (int)bytesWritten;
1052 } else {
1053 errno = GetLastError();
1054 return 0;
1055 }
1056 } else {
1057 return _write(fd, buffer, count);
1058 }
1059}
1060#endif // _WIN32
1061
1062#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
1063#define LINENOISE_MAX_LINE 4096
1064static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
1065static CompletionCallback completionCallback;
1066
1067#ifndef _WIN32
1068static struct termios orig_termios; /* In order to restore at exit.*/
1069#endif
1070static bool rawmode = false; /* For atexit() function to check if restore is needed*/
1071static bool mlmode = false; /* Multi line mode. Default is single line. */
1072static bool atexit_registered = false; /* Register atexit just 1 time. */
1073static size_t history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
1074static std::vector<std::string> history;
1075
1076/* The linenoiseState structure represents the state during line editing.
1077 * We pass this state to functions implementing specific editing
1078 * functionalities. */
1079struct linenoiseState {
1080 int ifd; /* Terminal stdin file descriptor. */
1081 int ofd; /* Terminal stdout file descriptor. */
1082 char *buf; /* Edited line buffer. */
1083 int buflen; /* Edited line buffer size. */
1084 std::string prompt; /* Prompt to display. */
1085 int pos; /* Current cursor position. */
1086 int oldcolpos; /* Previous refresh cursor column position. */
1087 int len; /* Current edited line length. */
1088 int cols; /* Number of columns in terminal. */
1089 int maxrows; /* Maximum num of rows used so far (multiline mode) */
1090 int history_index; /* The history index we are currently editing. */
1091};
1092
1093enum KEY_ACTION {
1094 KEY_NULL = 0, /* NULL */
1095 CTRL_A = 1, /* Ctrl+a */
1096 CTRL_B = 2, /* Ctrl-b */
1097 CTRL_C = 3, /* Ctrl-c */
1098 CTRL_D = 4, /* Ctrl-d */
1099 CTRL_E = 5, /* Ctrl-e */
1100 CTRL_F = 6, /* Ctrl-f */
1101 CTRL_H = 8, /* Ctrl-h */
1102 TAB = 9, /* Tab */
1103 CTRL_K = 11, /* Ctrl+k */
1104 CTRL_L = 12, /* Ctrl+l */
1105 ENTER = 13, /* Enter */
1106 CTRL_N = 14, /* Ctrl-n */
1107 CTRL_P = 16, /* Ctrl-p */
1108 CTRL_T = 20, /* Ctrl-t */
1109 CTRL_U = 21, /* Ctrl+u */
1110 CTRL_W = 23, /* Ctrl+w */
1111 ESC = 27, /* Escape */
1112 BACKSPACE = 127 /* Backspace */
1113};
1114
1115void linenoiseAtExit(void);
1116bool AddHistory(const char *line);
1117void refreshLine(struct linenoiseState *l);
1118
1119/* ============================ UTF8 utilities ============================== */
1120
1121static unsigned long unicodeWideCharTable[][2] = {
1122 { 0x1100, 0x115F }, { 0x2329, 0x232A }, { 0x2E80, 0x2E99, }, { 0x2E9B, 0x2EF3, },
1123 { 0x2F00, 0x2FD5, }, { 0x2FF0, 0x2FFB, }, { 0x3000, 0x303E, }, { 0x3041, 0x3096, },
1124 { 0x3099, 0x30FF, }, { 0x3105, 0x312D, }, { 0x3131, 0x318E, }, { 0x3190, 0x31BA, },
1125 { 0x31C0, 0x31E3, }, { 0x31F0, 0x321E, }, { 0x3220, 0x3247, }, { 0x3250, 0x4DBF, },
1126 { 0x4E00, 0xA48C, }, { 0xA490, 0xA4C6, }, { 0xA960, 0xA97C, }, { 0xAC00, 0xD7A3, },
1127 { 0xF900, 0xFAFF, }, { 0xFE10, 0xFE19, }, { 0xFE30, 0xFE52, }, { 0xFE54, 0xFE66, },
1128 { 0xFE68, 0xFE6B, }, { 0xFF01, 0xFFE6, },
1129 { 0x1B000, 0x1B001, }, { 0x1F200, 0x1F202, }, { 0x1F210, 0x1F23A, },
1130 { 0x1F240, 0x1F248, }, { 0x1F250, 0x1F251, }, { 0x20000, 0x3FFFD, },
1131};
1132
1133static int unicodeWideCharTableSize = sizeof(unicodeWideCharTable) / sizeof(unicodeWideCharTable[0]);
1134
1135static int unicodeIsWideChar(unsigned long cp)
1136{
1137 int i;
1138 for (i = 0; i < unicodeWideCharTableSize; i++) {
1139 if (unicodeWideCharTable[i][0] <= cp && cp <= unicodeWideCharTable[i][1]) {
1140 return 1;
1141 }
1142 }
1143 return 0;
1144}
1145
1146static unsigned long unicodeCombiningCharTable[] = {
1147 0x0300,0x0301,0x0302,0x0303,0x0304,0x0305,0x0306,0x0307,
1148 0x0308,0x0309,0x030A,0x030B,0x030C,0x030D,0x030E,0x030F,
1149 0x0310,0x0311,0x0312,0x0313,0x0314,0x0315,0x0316,0x0317,
1150 0x0318,0x0319,0x031A,0x031B,0x031C,0x031D,0x031E,0x031F,
1151 0x0320,0x0321,0x0322,0x0323,0x0324,0x0325,0x0326,0x0327,
1152 0x0328,0x0329,0x032A,0x032B,0x032C,0x032D,0x032E,0x032F,
1153 0x0330,0x0331,0x0332,0x0333,0x0334,0x0335,0x0336,0x0337,
1154 0x0338,0x0339,0x033A,0x033B,0x033C,0x033D,0x033E,0x033F,
1155 0x0340,0x0341,0x0342,0x0343,0x0344,0x0345,0x0346,0x0347,
1156 0x0348,0x0349,0x034A,0x034B,0x034C,0x034D,0x034E,0x034F,
1157 0x0350,0x0351,0x0352,0x0353,0x0354,0x0355,0x0356,0x0357,
1158 0x0358,0x0359,0x035A,0x035B,0x035C,0x035D,0x035E,0x035F,
1159 0x0360,0x0361,0x0362,0x0363,0x0364,0x0365,0x0366,0x0367,
1160 0x0368,0x0369,0x036A,0x036B,0x036C,0x036D,0x036E,0x036F,
1161 0x0483,0x0484,0x0485,0x0486,0x0487,0x0591,0x0592,0x0593,
1162 0x0594,0x0595,0x0596,0x0597,0x0598,0x0599,0x059A,0x059B,
1163 0x059C,0x059D,0x059E,0x059F,0x05A0,0x05A1,0x05A2,0x05A3,
1164 0x05A4,0x05A5,0x05A6,0x05A7,0x05A8,0x05A9,0x05AA,0x05AB,
1165 0x05AC,0x05AD,0x05AE,0x05AF,0x05B0,0x05B1,0x05B2,0x05B3,
1166 0x05B4,0x05B5,0x05B6,0x05B7,0x05B8,0x05B9,0x05BA,0x05BB,
1167 0x05BC,0x05BD,0x05BF,0x05C1,0x05C2,0x05C4,0x05C5,0x05C7,
1168 0x0610,0x0611,0x0612,0x0613,0x0614,0x0615,0x0616,0x0617,
1169 0x0618,0x0619,0x061A,0x064B,0x064C,0x064D,0x064E,0x064F,
1170 0x0650,0x0651,0x0652,0x0653,0x0654,0x0655,0x0656,0x0657,
1171 0x0658,0x0659,0x065A,0x065B,0x065C,0x065D,0x065E,0x065F,
1172 0x0670,0x06D6,0x06D7,0x06D8,0x06D9,0x06DA,0x06DB,0x06DC,
1173 0x06DF,0x06E0,0x06E1,0x06E2,0x06E3,0x06E4,0x06E7,0x06E8,
1174 0x06EA,0x06EB,0x06EC,0x06ED,0x0711,0x0730,0x0731,0x0732,
1175 0x0733,0x0734,0x0735,0x0736,0x0737,0x0738,0x0739,0x073A,
1176 0x073B,0x073C,0x073D,0x073E,0x073F,0x0740,0x0741,0x0742,
1177 0x0743,0x0744,0x0745,0x0746,0x0747,0x0748,0x0749,0x074A,
1178 0x07A6,0x07A7,0x07A8,0x07A9,0x07AA,0x07AB,0x07AC,0x07AD,
1179 0x07AE,0x07AF,0x07B0,0x07EB,0x07EC,0x07ED,0x07EE,0x07EF,
1180 0x07F0,0x07F1,0x07F2,0x07F3,0x0816,0x0817,0x0818,0x0819,
1181 0x081B,0x081C,0x081D,0x081E,0x081F,0x0820,0x0821,0x0822,
1182 0x0823,0x0825,0x0826,0x0827,0x0829,0x082A,0x082B,0x082C,
1183 0x082D,0x0859,0x085A,0x085B,0x08E3,0x08E4,0x08E5,0x08E6,
1184 0x08E7,0x08E8,0x08E9,0x08EA,0x08EB,0x08EC,0x08ED,0x08EE,
1185 0x08EF,0x08F0,0x08F1,0x08F2,0x08F3,0x08F4,0x08F5,0x08F6,
1186 0x08F7,0x08F8,0x08F9,0x08FA,0x08FB,0x08FC,0x08FD,0x08FE,
1187 0x08FF,0x0900,0x0901,0x0902,0x093A,0x093C,0x0941,0x0942,
1188 0x0943,0x0944,0x0945,0x0946,0x0947,0x0948,0x094D,0x0951,
1189 0x0952,0x0953,0x0954,0x0955,0x0956,0x0957,0x0962,0x0963,
1190 0x0981,0x09BC,0x09C1,0x09C2,0x09C3,0x09C4,0x09CD,0x09E2,
1191 0x09E3,0x0A01,0x0A02,0x0A3C,0x0A41,0x0A42,0x0A47,0x0A48,
1192 0x0A4B,0x0A4C,0x0A4D,0x0A51,0x0A70,0x0A71,0x0A75,0x0A81,
1193 0x0A82,0x0ABC,0x0AC1,0x0AC2,0x0AC3,0x0AC4,0x0AC5,0x0AC7,
1194 0x0AC8,0x0ACD,0x0AE2,0x0AE3,0x0B01,0x0B3C,0x0B3F,0x0B41,
1195 0x0B42,0x0B43,0x0B44,0x0B4D,0x0B56,0x0B62,0x0B63,0x0B82,
1196 0x0BC0,0x0BCD,0x0C00,0x0C3E,0x0C3F,0x0C40,0x0C46,0x0C47,
1197 0x0C48,0x0C4A,0x0C4B,0x0C4C,0x0C4D,0x0C55,0x0C56,0x0C62,
1198 0x0C63,0x0C81,0x0CBC,0x0CBF,0x0CC6,0x0CCC,0x0CCD,0x0CE2,
1199 0x0CE3,0x0D01,0x0D41,0x0D42,0x0D43,0x0D44,0x0D4D,0x0D62,
1200 0x0D63,0x0DCA,0x0DD2,0x0DD3,0x0DD4,0x0DD6,0x0E31,0x0E34,
1201 0x0E35,0x0E36,0x0E37,0x0E38,0x0E39,0x0E3A,0x0E47,0x0E48,
1202 0x0E49,0x0E4A,0x0E4B,0x0E4C,0x0E4D,0x0E4E,0x0EB1,0x0EB4,
1203 0x0EB5,0x0EB6,0x0EB7,0x0EB8,0x0EB9,0x0EBB,0x0EBC,0x0EC8,
1204 0x0EC9,0x0ECA,0x0ECB,0x0ECC,0x0ECD,0x0F18,0x0F19,0x0F35,
1205 0x0F37,0x0F39,0x0F71,0x0F72,0x0F73,0x0F74,0x0F75,0x0F76,
1206 0x0F77,0x0F78,0x0F79,0x0F7A,0x0F7B,0x0F7C,0x0F7D,0x0F7E,
1207 0x0F80,0x0F81,0x0F82,0x0F83,0x0F84,0x0F86,0x0F87,0x0F8D,
1208 0x0F8E,0x0F8F,0x0F90,0x0F91,0x0F92,0x0F93,0x0F94,0x0F95,
1209 0x0F96,0x0F97,0x0F99,0x0F9A,0x0F9B,0x0F9C,0x0F9D,0x0F9E,
1210 0x0F9F,0x0FA0,0x0FA1,0x0FA2,0x0FA3,0x0FA4,0x0FA5,0x0FA6,
1211 0x0FA7,0x0FA8,0x0FA9,0x0FAA,0x0FAB,0x0FAC,0x0FAD,0x0FAE,
1212 0x0FAF,0x0FB0,0x0FB1,0x0FB2,0x0FB3,0x0FB4,0x0FB5,0x0FB6,
1213 0x0FB7,0x0FB8,0x0FB9,0x0FBA,0x0FBB,0x0FBC,0x0FC6,0x102D,
1214 0x102E,0x102F,0x1030,0x1032,0x1033,0x1034,0x1035,0x1036,
1215 0x1037,0x1039,0x103A,0x103D,0x103E,0x1058,0x1059,0x105E,
1216 0x105F,0x1060,0x1071,0x1072,0x1073,0x1074,0x1082,0x1085,
1217 0x1086,0x108D,0x109D,0x135D,0x135E,0x135F,0x1712,0x1713,
1218 0x1714,0x1732,0x1733,0x1734,0x1752,0x1753,0x1772,0x1773,
1219 0x17B4,0x17B5,0x17B7,0x17B8,0x17B9,0x17BA,0x17BB,0x17BC,
1220 0x17BD,0x17C6,0x17C9,0x17CA,0x17CB,0x17CC,0x17CD,0x17CE,
1221 0x17CF,0x17D0,0x17D1,0x17D2,0x17D3,0x17DD,0x180B,0x180C,
1222 0x180D,0x18A9,0x1920,0x1921,0x1922,0x1927,0x1928,0x1932,
1223 0x1939,0x193A,0x193B,0x1A17,0x1A18,0x1A1B,0x1A56,0x1A58,
1224 0x1A59,0x1A5A,0x1A5B,0x1A5C,0x1A5D,0x1A5E,0x1A60,0x1A62,
1225 0x1A65,0x1A66,0x1A67,0x1A68,0x1A69,0x1A6A,0x1A6B,0x1A6C,
1226 0x1A73,0x1A74,0x1A75,0x1A76,0x1A77,0x1A78,0x1A79,0x1A7A,
1227 0x1A7B,0x1A7C,0x1A7F,0x1AB0,0x1AB1,0x1AB2,0x1AB3,0x1AB4,
1228 0x1AB5,0x1AB6,0x1AB7,0x1AB8,0x1AB9,0x1ABA,0x1ABB,0x1ABC,
1229 0x1ABD,0x1B00,0x1B01,0x1B02,0x1B03,0x1B34,0x1B36,0x1B37,
1230 0x1B38,0x1B39,0x1B3A,0x1B3C,0x1B42,0x1B6B,0x1B6C,0x1B6D,
1231 0x1B6E,0x1B6F,0x1B70,0x1B71,0x1B72,0x1B73,0x1B80,0x1B81,
1232 0x1BA2,0x1BA3,0x1BA4,0x1BA5,0x1BA8,0x1BA9,0x1BAB,0x1BAC,
1233 0x1BAD,0x1BE6,0x1BE8,0x1BE9,0x1BED,0x1BEF,0x1BF0,0x1BF1,
1234 0x1C2C,0x1C2D,0x1C2E,0x1C2F,0x1C30,0x1C31,0x1C32,0x1C33,
1235 0x1C36,0x1C37,0x1CD0,0x1CD1,0x1CD2,0x1CD4,0x1CD5,0x1CD6,
1236 0x1CD7,0x1CD8,0x1CD9,0x1CDA,0x1CDB,0x1CDC,0x1CDD,0x1CDE,
1237 0x1CDF,0x1CE0,0x1CE2,0x1CE3,0x1CE4,0x1CE5,0x1CE6,0x1CE7,
1238 0x1CE8,0x1CED,0x1CF4,0x1CF8,0x1CF9,0x1DC0,0x1DC1,0x1DC2,
1239 0x1DC3,0x1DC4,0x1DC5,0x1DC6,0x1DC7,0x1DC8,0x1DC9,0x1DCA,
1240 0x1DCB,0x1DCC,0x1DCD,0x1DCE,0x1DCF,0x1DD0,0x1DD1,0x1DD2,
1241 0x1DD3,0x1DD4,0x1DD5,0x1DD6,0x1DD7,0x1DD8,0x1DD9,0x1DDA,
1242 0x1DDB,0x1DDC,0x1DDD,0x1DDE,0x1DDF,0x1DE0,0x1DE1,0x1DE2,
1243 0x1DE3,0x1DE4,0x1DE5,0x1DE6,0x1DE7,0x1DE8,0x1DE9,0x1DEA,
1244 0x1DEB,0x1DEC,0x1DED,0x1DEE,0x1DEF,0x1DF0,0x1DF1,0x1DF2,
1245 0x1DF3,0x1DF4,0x1DF5,0x1DFC,0x1DFD,0x1DFE,0x1DFF,0x20D0,
1246 0x20D1,0x20D2,0x20D3,0x20D4,0x20D5,0x20D6,0x20D7,0x20D8,
1247 0x20D9,0x20DA,0x20DB,0x20DC,0x20E1,0x20E5,0x20E6,0x20E7,
1248 0x20E8,0x20E9,0x20EA,0x20EB,0x20EC,0x20ED,0x20EE,0x20EF,
1249 0x20F0,0x2CEF,0x2CF0,0x2CF1,0x2D7F,0x2DE0,0x2DE1,0x2DE2,
1250 0x2DE3,0x2DE4,0x2DE5,0x2DE6,0x2DE7,0x2DE8,0x2DE9,0x2DEA,
1251 0x2DEB,0x2DEC,0x2DED,0x2DEE,0x2DEF,0x2DF0,0x2DF1,0x2DF2,
1252 0x2DF3,0x2DF4,0x2DF5,0x2DF6,0x2DF7,0x2DF8,0x2DF9,0x2DFA,
1253 0x2DFB,0x2DFC,0x2DFD,0x2DFE,0x2DFF,0x302A,0x302B,0x302C,
1254 0x302D,0x3099,0x309A,0xA66F,0xA674,0xA675,0xA676,0xA677,
1255 0xA678,0xA679,0xA67A,0xA67B,0xA67C,0xA67D,0xA69E,0xA69F,
1256 0xA6F0,0xA6F1,0xA802,0xA806,0xA80B,0xA825,0xA826,0xA8C4,
1257 0xA8E0,0xA8E1,0xA8E2,0xA8E3,0xA8E4,0xA8E5,0xA8E6,0xA8E7,
1258 0xA8E8,0xA8E9,0xA8EA,0xA8EB,0xA8EC,0xA8ED,0xA8EE,0xA8EF,
1259 0xA8F0,0xA8F1,0xA926,0xA927,0xA928,0xA929,0xA92A,0xA92B,
1260 0xA92C,0xA92D,0xA947,0xA948,0xA949,0xA94A,0xA94B,0xA94C,
1261 0xA94D,0xA94E,0xA94F,0xA950,0xA951,0xA980,0xA981,0xA982,
1262 0xA9B3,0xA9B6,0xA9B7,0xA9B8,0xA9B9,0xA9BC,0xA9E5,0xAA29,
1263 0xAA2A,0xAA2B,0xAA2C,0xAA2D,0xAA2E,0xAA31,0xAA32,0xAA35,
1264 0xAA36,0xAA43,0xAA4C,0xAA7C,0xAAB0,0xAAB2,0xAAB3,0xAAB4,
1265 0xAAB7,0xAAB8,0xAABE,0xAABF,0xAAC1,0xAAEC,0xAAED,0xAAF6,
1266 0xABE5,0xABE8,0xABED,0xFB1E,0xFE00,0xFE01,0xFE02,0xFE03,
1267 0xFE04,0xFE05,0xFE06,0xFE07,0xFE08,0xFE09,0xFE0A,0xFE0B,
1268 0xFE0C,0xFE0D,0xFE0E,0xFE0F,0xFE20,0xFE21,0xFE22,0xFE23,
1269 0xFE24,0xFE25,0xFE26,0xFE27,0xFE28,0xFE29,0xFE2A,0xFE2B,
1270 0xFE2C,0xFE2D,0xFE2E,0xFE2F,
1271 0x101FD,0x102E0,0x10376,0x10377,0x10378,0x10379,0x1037A,0x10A01,
1272 0x10A02,0x10A03,0x10A05,0x10A06,0x10A0C,0x10A0D,0x10A0E,0x10A0F,
1273 0x10A38,0x10A39,0x10A3A,0x10A3F,0x10AE5,0x10AE6,0x11001,0x11038,
1274 0x11039,0x1103A,0x1103B,0x1103C,0x1103D,0x1103E,0x1103F,0x11040,
1275 0x11041,0x11042,0x11043,0x11044,0x11045,0x11046,0x1107F,0x11080,
1276 0x11081,0x110B3,0x110B4,0x110B5,0x110B6,0x110B9,0x110BA,0x11100,
1277 0x11101,0x11102,0x11127,0x11128,0x11129,0x1112A,0x1112B,0x1112D,
1278 0x1112E,0x1112F,0x11130,0x11131,0x11132,0x11133,0x11134,0x11173,
1279 0x11180,0x11181,0x111B6,0x111B7,0x111B8,0x111B9,0x111BA,0x111BB,
1280 0x111BC,0x111BD,0x111BE,0x111CA,0x111CB,0x111CC,0x1122F,0x11230,
1281 0x11231,0x11234,0x11236,0x11237,0x112DF,0x112E3,0x112E4,0x112E5,
1282 0x112E6,0x112E7,0x112E8,0x112E9,0x112EA,0x11300,0x11301,0x1133C,
1283 0x11340,0x11366,0x11367,0x11368,0x11369,0x1136A,0x1136B,0x1136C,
1284 0x11370,0x11371,0x11372,0x11373,0x11374,0x114B3,0x114B4,0x114B5,
1285 0x114B6,0x114B7,0x114B8,0x114BA,0x114BF,0x114C0,0x114C2,0x114C3,
1286 0x115B2,0x115B3,0x115B4,0x115B5,0x115BC,0x115BD,0x115BF,0x115C0,
1287 0x115DC,0x115DD,0x11633,0x11634,0x11635,0x11636,0x11637,0x11638,
1288 0x11639,0x1163A,0x1163D,0x1163F,0x11640,0x116AB,0x116AD,0x116B0,
1289 0x116B1,0x116B2,0x116B3,0x116B4,0x116B5,0x116B7,0x1171D,0x1171E,
1290 0x1171F,0x11722,0x11723,0x11724,0x11725,0x11727,0x11728,0x11729,
1291 0x1172A,0x1172B,0x16AF0,0x16AF1,0x16AF2,0x16AF3,0x16AF4,0x16B30,
1292 0x16B31,0x16B32,0x16B33,0x16B34,0x16B35,0x16B36,0x16F8F,0x16F90,
1293 0x16F91,0x16F92,0x1BC9D,0x1BC9E,0x1D167,0x1D168,0x1D169,0x1D17B,
1294 0x1D17C,0x1D17D,0x1D17E,0x1D17F,0x1D180,0x1D181,0x1D182,0x1D185,
1295 0x1D186,0x1D187,0x1D188,0x1D189,0x1D18A,0x1D18B,0x1D1AA,0x1D1AB,
1296 0x1D1AC,0x1D1AD,0x1D242,0x1D243,0x1D244,0x1DA00,0x1DA01,0x1DA02,
1297 0x1DA03,0x1DA04,0x1DA05,0x1DA06,0x1DA07,0x1DA08,0x1DA09,0x1DA0A,
1298 0x1DA0B,0x1DA0C,0x1DA0D,0x1DA0E,0x1DA0F,0x1DA10,0x1DA11,0x1DA12,
1299 0x1DA13,0x1DA14,0x1DA15,0x1DA16,0x1DA17,0x1DA18,0x1DA19,0x1DA1A,
1300 0x1DA1B,0x1DA1C,0x1DA1D,0x1DA1E,0x1DA1F,0x1DA20,0x1DA21,0x1DA22,
1301 0x1DA23,0x1DA24,0x1DA25,0x1DA26,0x1DA27,0x1DA28,0x1DA29,0x1DA2A,
1302 0x1DA2B,0x1DA2C,0x1DA2D,0x1DA2E,0x1DA2F,0x1DA30,0x1DA31,0x1DA32,
1303 0x1DA33,0x1DA34,0x1DA35,0x1DA36,0x1DA3B,0x1DA3C,0x1DA3D,0x1DA3E,
1304 0x1DA3F,0x1DA40,0x1DA41,0x1DA42,0x1DA43,0x1DA44,0x1DA45,0x1DA46,
1305 0x1DA47,0x1DA48,0x1DA49,0x1DA4A,0x1DA4B,0x1DA4C,0x1DA4D,0x1DA4E,
1306 0x1DA4F,0x1DA50,0x1DA51,0x1DA52,0x1DA53,0x1DA54,0x1DA55,0x1DA56,
1307 0x1DA57,0x1DA58,0x1DA59,0x1DA5A,0x1DA5B,0x1DA5C,0x1DA5D,0x1DA5E,
1308 0x1DA5F,0x1DA60,0x1DA61,0x1DA62,0x1DA63,0x1DA64,0x1DA65,0x1DA66,
1309 0x1DA67,0x1DA68,0x1DA69,0x1DA6A,0x1DA6B,0x1DA6C,0x1DA75,0x1DA84,
1310 0x1DA9B,0x1DA9C,0x1DA9D,0x1DA9E,0x1DA9F,0x1DAA1,0x1DAA2,0x1DAA3,
1311 0x1DAA4,0x1DAA5,0x1DAA6,0x1DAA7,0x1DAA8,0x1DAA9,0x1DAAA,0x1DAAB,
1312 0x1DAAC,0x1DAAD,0x1DAAE,0x1DAAF,0x1E8D0,0x1E8D1,0x1E8D2,0x1E8D3,
1313 0x1E8D4,0x1E8D5,0x1E8D6,0xE0100,0xE0101,0xE0102,0xE0103,0xE0104,
1314 0xE0105,0xE0106,0xE0107,0xE0108,0xE0109,0xE010A,0xE010B,0xE010C,
1315 0xE010D,0xE010E,0xE010F,0xE0110,0xE0111,0xE0112,0xE0113,0xE0114,
1316 0xE0115,0xE0116,0xE0117,0xE0118,0xE0119,0xE011A,0xE011B,0xE011C,
1317 0xE011D,0xE011E,0xE011F,0xE0120,0xE0121,0xE0122,0xE0123,0xE0124,
1318 0xE0125,0xE0126,0xE0127,0xE0128,0xE0129,0xE012A,0xE012B,0xE012C,
1319 0xE012D,0xE012E,0xE012F,0xE0130,0xE0131,0xE0132,0xE0133,0xE0134,
1320 0xE0135,0xE0136,0xE0137,0xE0138,0xE0139,0xE013A,0xE013B,0xE013C,
1321 0xE013D,0xE013E,0xE013F,0xE0140,0xE0141,0xE0142,0xE0143,0xE0144,
1322 0xE0145,0xE0146,0xE0147,0xE0148,0xE0149,0xE014A,0xE014B,0xE014C,
1323 0xE014D,0xE014E,0xE014F,0xE0150,0xE0151,0xE0152,0xE0153,0xE0154,
1324 0xE0155,0xE0156,0xE0157,0xE0158,0xE0159,0xE015A,0xE015B,0xE015C,
1325 0xE015D,0xE015E,0xE015F,0xE0160,0xE0161,0xE0162,0xE0163,0xE0164,
1326 0xE0165,0xE0166,0xE0167,0xE0168,0xE0169,0xE016A,0xE016B,0xE016C,
1327 0xE016D,0xE016E,0xE016F,0xE0170,0xE0171,0xE0172,0xE0173,0xE0174,
1328 0xE0175,0xE0176,0xE0177,0xE0178,0xE0179,0xE017A,0xE017B,0xE017C,
1329 0xE017D,0xE017E,0xE017F,0xE0180,0xE0181,0xE0182,0xE0183,0xE0184,
1330 0xE0185,0xE0186,0xE0187,0xE0188,0xE0189,0xE018A,0xE018B,0xE018C,
1331 0xE018D,0xE018E,0xE018F,0xE0190,0xE0191,0xE0192,0xE0193,0xE0194,
1332 0xE0195,0xE0196,0xE0197,0xE0198,0xE0199,0xE019A,0xE019B,0xE019C,
1333 0xE019D,0xE019E,0xE019F,0xE01A0,0xE01A1,0xE01A2,0xE01A3,0xE01A4,
1334 0xE01A5,0xE01A6,0xE01A7,0xE01A8,0xE01A9,0xE01AA,0xE01AB,0xE01AC,
1335 0xE01AD,0xE01AE,0xE01AF,0xE01B0,0xE01B1,0xE01B2,0xE01B3,0xE01B4,
1336 0xE01B5,0xE01B6,0xE01B7,0xE01B8,0xE01B9,0xE01BA,0xE01BB,0xE01BC,
1337 0xE01BD,0xE01BE,0xE01BF,0xE01C0,0xE01C1,0xE01C2,0xE01C3,0xE01C4,
1338 0xE01C5,0xE01C6,0xE01C7,0xE01C8,0xE01C9,0xE01CA,0xE01CB,0xE01CC,
1339 0xE01CD,0xE01CE,0xE01CF,0xE01D0,0xE01D1,0xE01D2,0xE01D3,0xE01D4,
1340 0xE01D5,0xE01D6,0xE01D7,0xE01D8,0xE01D9,0xE01DA,0xE01DB,0xE01DC,
1341 0xE01DD,0xE01DE,0xE01DF,0xE01E0,0xE01E1,0xE01E2,0xE01E3,0xE01E4,
1342 0xE01E5,0xE01E6,0xE01E7,0xE01E8,0xE01E9,0xE01EA,0xE01EB,0xE01EC,
1343 0xE01ED,0xE01EE,0xE01EF,
1344};
1345
1346static int unicodeCombiningCharTableSize = sizeof(unicodeCombiningCharTable) / sizeof(unicodeCombiningCharTable[0]);
1347
1348inline int unicodeIsCombiningChar(unsigned long cp)
1349{
1350 int i;
1351 for (i = 0; i < unicodeCombiningCharTableSize; i++) {
1352 if (unicodeCombiningCharTable[i] == cp) {
1353 return 1;
1354 }
1355 }
1356 return 0;
1357}
1358
1359/* Get length of previous UTF8 character
1360 */
1361inline int unicodePrevUTF8CharLen(char* buf, int pos)
1362{
1363 int end = pos--;
1364 while (pos >= 0 && ((unsigned char)buf[pos] & 0xC0) == 0x80) {
1365 pos--;
1366 }
1367 return end - pos;
1368}
1369
1370/* Get length of previous UTF8 character
1371 */
1372inline int unicodeUTF8CharLen(char* buf, int buf_len, int pos)
1373{
1374 if (pos == buf_len) { return 0; }
1375 unsigned char ch = buf[pos];
1376 if (ch < 0x80) { return 1; }
1377 else if (ch < 0xE0) { return 2; }
1378 else if (ch < 0xF0) { return 3; }
1379 else { return 4; }
1380}
1381
1382/* Convert UTF8 to Unicode code point
1383 */
1384inline int unicodeUTF8CharToCodePoint(
1385 const char* buf,
1386 int len,
1387 int* cp)
1388{
1389 if (len) {
1390 unsigned char byte = buf[0];
1391 if ((byte & 0x80) == 0) {
1392 *cp = byte;
1393 return 1;
1394 } else if ((byte & 0xE0) == 0xC0) {
1395 if (len >= 2) {
1396 *cp = (((unsigned long)(buf[0] & 0x1F)) << 6) |
1397 ((unsigned long)(buf[1] & 0x3F));
1398 return 2;
1399 }
1400 } else if ((byte & 0xF0) == 0xE0) {
1401 if (len >= 3) {
1402 *cp = (((unsigned long)(buf[0] & 0x0F)) << 12) |
1403 (((unsigned long)(buf[1] & 0x3F)) << 6) |
1404 ((unsigned long)(buf[2] & 0x3F));
1405 return 3;
1406 }
1407 } else if ((byte & 0xF8) == 0xF0) {
1408 if (len >= 4) {
1409 *cp = (((unsigned long)(buf[0] & 0x07)) << 18) |
1410 (((unsigned long)(buf[1] & 0x3F)) << 12) |
1411 (((unsigned long)(buf[2] & 0x3F)) << 6) |
1412 ((unsigned long)(buf[3] & 0x3F));
1413 return 4;
1414 }
1415 }
1416 }
1417 return 0;
1418}
1419
1420/* Get length of grapheme
1421 */
1422inline int unicodeGraphemeLen(char* buf, int buf_len, int pos)
1423{
1424 if (pos == buf_len) {
1425 return 0;
1426 }
1427 int beg = pos;
1428 pos += unicodeUTF8CharLen(buf, buf_len, pos);
1429 while (pos < buf_len) {
1430 int len = unicodeUTF8CharLen(buf, buf_len, pos);
1431 int cp = 0;
1432 unicodeUTF8CharToCodePoint(buf + pos, len, &cp);
1433 if (!unicodeIsCombiningChar(cp)) {
1434 return pos - beg;
1435 }
1436 pos += len;
1437 }
1438 return pos - beg;
1439}
1440
1441/* Get length of previous grapheme
1442 */
1443inline int unicodePrevGraphemeLen(char* buf, int pos)
1444{
1445 if (pos == 0) {
1446 return 0;
1447 }
1448 int end = pos;
1449 while (pos > 0) {
1450 int len = unicodePrevUTF8CharLen(buf, pos);
1451 pos -= len;
1452 int cp = 0;
1453 unicodeUTF8CharToCodePoint(buf + pos, len, &cp);
1454 if (!unicodeIsCombiningChar(cp)) {
1455 return end - pos;
1456 }
1457 }
1458 return 0;
1459}
1460
1461inline int isAnsiEscape(const char* buf, int buf_len, int* len)
1462{
1463 if (buf_len > 2 && !memcmp("\033[", buf, 2)) {
1464 int off = 2;
1465 while (off < buf_len) {
1466 switch (buf[off++]) {
1467 case 'A': case 'B': case 'C': case 'D':
1468 case 'E': case 'F': case 'G': case 'H':
1469 case 'J': case 'K': case 'S': case 'T':
1470 case 'f': case 'm':
1471 *len = off;
1472 return 1;
1473 }
1474 }
1475 }
1476 return 0;
1477}
1478
1479/* Get column position for the single line mode.
1480 */
1481inline int unicodeColumnPos(const char* buf, int buf_len)
1482{
1483 int ret = 0;
1484
1485 int off = 0;
1486 while (off < buf_len) {
1487 int len;
1488 if (isAnsiEscape(buf + off, buf_len - off, &len)) {
1489 off += len;
1490 continue;
1491 }
1492
1493 int cp = 0;
1494 len = unicodeUTF8CharToCodePoint(buf + off, buf_len - off, &cp);
1495
1496 if (!unicodeIsCombiningChar(cp)) {
1497 ret += unicodeIsWideChar(cp) ? 2 : 1;
1498 }
1499
1500 off += len;
1501 }
1502
1503 return ret;
1504}
1505
1506/* Get column position for the multi line mode.
1507 */
1508inline int unicodeColumnPosForMultiLine(char* buf, int buf_len, int pos, int cols, int ini_pos)
1509{
1510 int ret = 0;
1511 int colwid = ini_pos;
1512
1513 int off = 0;
1514 while (off < buf_len) {
1515 int cp = 0;
1516 int len = unicodeUTF8CharToCodePoint(buf + off, buf_len - off, &cp);
1517
1518 int wid = 0;
1519 if (!unicodeIsCombiningChar(cp)) {
1520 wid = unicodeIsWideChar(cp) ? 2 : 1;
1521 }
1522
1523 int dif = (int)(colwid + wid) - (int)cols;
1524 if (dif > 0) {
1525 ret += dif;
1526 colwid = wid;
1527 } else if (dif == 0) {
1528 colwid = 0;
1529 } else {
1530 colwid += wid;
1531 }
1532
1533 if (off >= pos) {
1534 break;
1535 }
1536
1537 off += len;
1538 ret += wid;
1539 }
1540
1541 return ret;
1542}
1543
1544/* Read UTF8 character from file.
1545 */
1546inline int unicodeReadUTF8Char(int fd, char* buf, int* cp)
1547{
1548 int nread = read(fd,&buf[0],1);
1549
1550 if (nread <= 0) { return nread; }
1551
1552 unsigned char byte = buf[0];
1553
1554 if ((byte & 0x80) == 0) {
1555 ;
1556 } else if ((byte & 0xE0) == 0xC0) {
1557 nread = read(fd,&buf[1],1);
1558 if (nread <= 0) { return nread; }
1559 } else if ((byte & 0xF0) == 0xE0) {
1560 nread = read(fd,&buf[1],2);
1561 if (nread <= 0) { return nread; }
1562 } else if ((byte & 0xF8) == 0xF0) {
1563 nread = read(fd,&buf[1],3);
1564 if (nread <= 0) { return nread; }
1565 } else {
1566 return -1;
1567 }
1568
1569 return unicodeUTF8CharToCodePoint(buf, 4, cp);
1570}
1571
1572/* ======================= Low level terminal handling ====================== */
1573
1574/* Set if to use or not the multi line mode. */
1575inline void SetMultiLine(bool ml) {
1576 mlmode = ml;
1577}
1578
1579/* Return true if the terminal name is in the list of terminals we know are
1580 * not able to understand basic escape sequences. */
1581inline bool isUnsupportedTerm(void) {
1582#ifndef _WIN32
1583 char *term = getenv("TERM");
1584 int j;
1585
1586 if (term == NULL) return false;
1587 for (j = 0; unsupported_term[j]; j++)
1588 if (!strcasecmp(term,unsupported_term[j])) return true;
1589#endif
1590 return false;
1591}
1592
1593/* Raw mode: 1960 magic shit. */
1594inline bool enableRawMode(int fd) {
1595#ifndef _WIN32
1596 struct termios raw;
1597
1598 if (!isatty(STDIN_FILENO)) goto fatal;
1599 if (!atexit_registered) {
1600 atexit(linenoiseAtExit);
1601 atexit_registered = true;
1602 }
1603 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
1604
1605 raw = orig_termios; /* modify the original mode */
1606 /* input modes: no break, no CR to NL, no parity check, no strip char,
1607 * no start/stop output control. */
1608 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
1609 /* output modes - disable post processing */
1610 // NOTE: Multithreaded issue #20 (https://github.com/yhirose/cpp-linenoise/issues/20)
1611 // raw.c_oflag &= ~(OPOST);
1612 /* control modes - set 8 bit chars */
1613 raw.c_cflag |= (CS8);
1614 /* local modes - choing off, canonical off, no extended functions,
1615 * no signal chars (^Z,^C) */
1616 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
1617 /* control chars - set return condition: min number of bytes and timer.
1618 * We want read to return every single byte, without timeout. */
1619 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
1620
1621 /* put terminal in raw mode after flushing */
1622 if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
1623 rawmode = true;
1624#else
1625 if (!atexit_registered) {
1626 /* Cleanup them at exit */
1627 atexit(linenoiseAtExit);
1628 atexit_registered = true;
1629
1630 /* Init windows console handles only once */
1631 hOut = GetStdHandle(STD_OUTPUT_HANDLE);
1632 if (hOut==INVALID_HANDLE_VALUE) goto fatal;
1633 }
1634
1635 DWORD consolemodeOut;
1636 if (!GetConsoleMode(hOut, &consolemodeOut)) {
1637 CloseHandle(hOut);
1638 errno = ENOTTY;
1639 return false;
1640 };
1641
1642 hIn = GetStdHandle(STD_INPUT_HANDLE);
1643 if (hIn == INVALID_HANDLE_VALUE) {
1644 CloseHandle(hOut);
1645 errno = ENOTTY;
1646 return false;
1647 }
1648
1649 GetConsoleMode(hIn, &consolemodeIn);
1650 DWORD consolemodeInWithRaw = consolemodeIn & ~ENABLE_PROCESSED_INPUT;
1651 SetConsoleMode(hIn, consolemodeInWithRaw);
1652
1653 rawmode = true;
1654#endif
1655 return true;
1656
1657fatal:
1658 errno = ENOTTY;
1659 return false;
1660}
1661
1662inline void disableRawMode(int fd) {
1663#ifdef _WIN32
1664 if (consolemodeIn) {
1665 SetConsoleMode(hIn, consolemodeIn);
1666 consolemodeIn = 0;
1667 }
1668 rawmode = false;
1669#else
1670 /* Don't even check the return value as it's too late. */
1671 if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
1672 rawmode = false;
1673#endif
1674}
1675
1676/* Use the ESC [6n escape sequence to query the horizontal cursor position
1677 * and return it. On error -1 is returned, on success the position of the
1678 * cursor. */
1679inline int getCursorPosition(int ifd, int ofd) {
1680 char buf[32];
1681 int cols, rows;
1682 unsigned int i = 0;
1683
1684 /* Report cursor location */
1685 if (write(ofd, "\x1b[6n", 4) != 4) return -1;
1686
1687 /* Read the response: ESC [ rows ; cols R */
1688 while (i < sizeof(buf)-1) {
1689 if (read(ifd,buf+i,1) != 1) break;
1690 if (buf[i] == 'R') break;
1691 i++;
1692 }
1693 buf[i] = '\0';
1694
1695 /* Parse it. */
1696 if (buf[0] != ESC || buf[1] != '[') return -1;
1697 if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1;
1698 return cols;
1699}
1700
1701/* Try to get the number of columns in the current terminal, or assume 80
1702 * if it fails. */
1703inline int getColumns(int ifd, int ofd) {
1704#ifdef _WIN32
1705 CONSOLE_SCREEN_BUFFER_INFO b;
1706
1707 if (!GetConsoleScreenBufferInfo(hOut, &b)) return 80;
1708 return b.srWindow.Right - b.srWindow.Left;
1709#else
1710 struct winsize ws;
1711
1712 if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
1713 /* ioctl() failed. Try to query the terminal itself. */
1714 int start, cols;
1715
1716 /* Get the initial position so we can restore it later. */
1717 start = getCursorPosition(ifd,ofd);
1718 if (start == -1) goto failed;
1719
1720 /* Go to right margin and get position. */
1721 if (write(ofd,"\x1b[999C",6) != 6) goto failed;
1722 cols = getCursorPosition(ifd,ofd);
1723 if (cols == -1) goto failed;
1724
1725 /* Restore position. */
1726 if (cols > start) {
1727 char seq[32];
1728 snprintf(seq,32,"\x1b[%dD",cols-start);
1729 if (write(ofd,seq,strlen(seq)) == -1) {
1730 /* Can't recover... */
1731 }
1732 }
1733 return cols;
1734 } else {
1735 return ws.ws_col;
1736 }
1737
1738failed:
1739 return 80;
1740#endif
1741}
1742
1743/* Clear the screen. Used to handle ctrl+l */
1744inline void linenoiseClearScreen(void) {
1745 if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
1746 /* nothing to do, just to avoid warning. */
1747 }
1748}
1749
1750/* Beep, used for completion when there is nothing to complete or when all
1751 * the choices were already shown. */
1752inline void linenoiseBeep(void) {
1753 fprintf(stderr, "\x7");
1754 fflush(stderr);
1755}
1756
1757/* ============================== Completion ================================ */
1758
1759/* This is an helper function for linenoiseEdit() and is called when the
1760 * user types the <tab> key in order to complete the string currently in the
1761 * input.
1762 *
1763 * The state of the editing is encapsulated into the pointed linenoiseState
1764 * structure as described in the structure definition. */
1765inline int completeLine(struct linenoiseState *ls, char *cbuf, int *c) {
1766 std::vector<std::string> lc;
1767 int nread = 0, nwritten;
1768 *c = 0;
1769
1770 completionCallback(ls->buf,lc);
1771 if (lc.empty()) {
1772 linenoiseBeep();
1773 } else {
1774 int stop = 0, i = 0;
1775
1776 while(!stop) {
1777 /* Show completion or original buffer */
1778 if (i < static_cast<int>(lc.size())) {
1779 struct linenoiseState saved = *ls;
1780
1781 ls->len = ls->pos = static_cast<int>(lc[i].size());
1782 ls->buf = &lc[i][0];
1783 refreshLine(ls);
1784 ls->len = saved.len;
1785 ls->pos = saved.pos;
1786 ls->buf = saved.buf;
1787 } else {
1788 refreshLine(ls);
1789 }
1790
1791 //nread = read(ls->ifd,&c,1);
1792#ifdef _WIN32
1793 nread = win32read(c);
1794 if (nread == 1) {
1795 cbuf[0] = *c;
1796 }
1797#else
1798 nread = unicodeReadUTF8Char(ls->ifd,cbuf,c);
1799#endif
1800 if (nread <= 0) {
1801 *c = -1;
1802 return nread;
1803 }
1804
1805 switch(*c) {
1806 case 9: /* tab */
1807 i = (i+1) % (lc.size()+1);
1808 if (i == static_cast<int>(lc.size())) linenoiseBeep();
1809 break;
1810 case 27: /* escape */
1811 /* Re-show original buffer */
1812 if (i < static_cast<int>(lc.size())) refreshLine(ls);
1813 stop = 1;
1814 break;
1815 default:
1816 /* Update buffer and return */
1817 if (i < static_cast<int>(lc.size())) {
1818 nwritten = snprintf(ls->buf,ls->buflen,"%s",&lc[i][0]);
1819 ls->len = ls->pos = nwritten;
1820 }
1821 stop = 1;
1822 break;
1823 }
1824 }
1825 }
1826
1827 return nread;
1828}
1829
1830/* Register a callback function to be called for tab-completion. */
1831inline void SetCompletionCallback(CompletionCallback fn) {
1832 completionCallback = fn;
1833}
1834
1835/* =========================== Line editing ================================= */
1836
1837/* Single line low level line refresh.
1838 *
1839 * Rewrite the currently edited line accordingly to the buffer content,
1840 * cursor position, and number of columns of the terminal. */
1841inline void refreshSingleLine(struct linenoiseState *l) {
1842 char seq[64];
1843 int pcolwid = unicodeColumnPos(l->prompt.c_str(), static_cast<int>(l->prompt.length()));
1844 int fd = l->ofd;
1845 char *buf = l->buf;
1846 int len = l->len;
1847 int pos = l->pos;
1848 std::string ab;
1849
1850 while((pcolwid+unicodeColumnPos(buf, pos)) >= l->cols) {
1851 int glen = unicodeGraphemeLen(buf, len, 0);
1852 buf += glen;
1853 len -= glen;
1854 pos -= glen;
1855 }
1856 while (pcolwid+unicodeColumnPos(buf, len) > l->cols) {
1857 len -= unicodePrevGraphemeLen(buf, len);
1858 }
1859
1860 /* Cursor to left edge */
1861 snprintf(seq,64,"\r");
1862 ab += seq;
1863 /* Write the prompt and the current buffer content */
1864 ab += l->prompt;
1865 ab.append(buf, len);
1866 /* Erase to right */
1867 snprintf(seq,64,"\x1b[0K");
1868 ab += seq;
1869 /* Move cursor to original position. */
1870 snprintf(seq,64,"\r\x1b[%dC", (int)(unicodeColumnPos(buf, pos)+pcolwid));
1871 ab += seq;
1872 if (write(fd,ab.c_str(), static_cast<int>(ab.length())) == -1) {} /* Can't recover from write error. */
1873}
1874
1875/* Multi line low level line refresh.
1876 *
1877 * Rewrite the currently edited line accordingly to the buffer content,
1878 * cursor position, and number of columns of the terminal. */
1879inline void refreshMultiLine(struct linenoiseState *l) {
1880 char seq[64];
1881 int pcolwid = unicodeColumnPos(l->prompt.c_str(), static_cast<int>(l->prompt.length()));
1882 int colpos = unicodeColumnPosForMultiLine(l->buf, l->len, l->len, l->cols, pcolwid);
1883 int colpos2; /* cursor column position. */
1884 int rows = (pcolwid+colpos+l->cols-1)/l->cols; /* rows used by current buf. */
1885 int rpos = (pcolwid+l->oldcolpos+l->cols)/l->cols; /* cursor relative row. */
1886 int rpos2; /* rpos after refresh. */
1887 int col; /* colum position, zero-based. */
1888 int old_rows = (int)l->maxrows;
1889 int fd = l->ofd, j;
1890 std::string ab;
1891
1892 /* Update maxrows if needed. */
1893 if (rows > (int)l->maxrows) l->maxrows = rows;
1894
1895 /* First step: clear all the lines used before. To do so start by
1896 * going to the last row. */
1897 if (old_rows-rpos > 0) {
1898 snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
1899 ab += seq;
1900 }
1901
1902 /* Now for every row clear it, go up. */
1903 for (j = 0; j < old_rows-1; j++) {
1904 snprintf(seq,64,"\r\x1b[0K\x1b[1A");
1905 ab += seq;
1906 }
1907
1908 /* Clean the top line. */
1909 snprintf(seq,64,"\r\x1b[0K");
1910 ab += seq;
1911
1912 /* Write the prompt and the current buffer content */
1913 ab += l->prompt;
1914 ab.append(l->buf, l->len);
1915
1916 /* Get text width to cursor position */
1917 colpos2 = unicodeColumnPosForMultiLine(l->buf, l->len, l->pos, l->cols, pcolwid);
1918
1919 /* If we are at the very end of the screen with our prompt, we need to
1920 * emit a newline and move the prompt to the first column. */
1921 if (l->pos &&
1922 l->pos == l->len &&
1923 (colpos2+pcolwid) % l->cols == 0)
1924 {
1925 ab += "\n";
1926 snprintf(seq,64,"\r");
1927 ab += seq;
1928 rows++;
1929 if (rows > (int)l->maxrows) l->maxrows = rows;
1930 }
1931
1932 /* Move cursor to right position. */
1933 rpos2 = (pcolwid+colpos2+l->cols)/l->cols; /* current cursor relative row. */
1934
1935 /* Go up till we reach the expected positon. */
1936 if (rows-rpos2 > 0) {
1937 snprintf(seq,64,"\x1b[%dA", rows-rpos2);
1938 ab += seq;
1939 }
1940
1941 /* Set column. */
1942 col = (pcolwid + colpos2) % l->cols;
1943 if (col)
1944 snprintf(seq,64,"\r\x1b[%dC", col);
1945 else
1946 snprintf(seq,64,"\r");
1947 ab += seq;
1948
1949 l->oldcolpos = colpos2;
1950
1951 if (write(fd,ab.c_str(), static_cast<int>(ab.length())) == -1) {} /* Can't recover from write error. */
1952}
1953
1954/* Calls the two low level functions refreshSingleLine() or
1955 * refreshMultiLine() according to the selected mode. */
1956inline void refreshLine(struct linenoiseState *l) {
1957 if (mlmode)
1958 refreshMultiLine(l);
1959 else
1960 refreshSingleLine(l);
1961}
1962
1963/* Insert the character 'c' at cursor current position.
1964 *
1965 * On error writing to the terminal -1 is returned, otherwise 0. */
1966inline int linenoiseEditInsert(struct linenoiseState *l, const char* cbuf, int clen) {
1967 if (l->len < l->buflen) {
1968 if (l->len == l->pos) {
1969 memcpy(&l->buf[l->pos],cbuf,clen);
1970 l->pos+=clen;
1971 l->len+=clen;;
1972 l->buf[l->len] = '\0';
1973 if ((!mlmode && unicodeColumnPos(l->prompt.c_str(), static_cast<int>(l->prompt.length()))+unicodeColumnPos(l->buf,l->len) < l->cols) /* || mlmode */) {
1974 /* Avoid a full update of the line in the
1975 * trivial case. */
1976 if (write(l->ofd,cbuf,clen) == -1) return -1;
1977 } else {
1978 refreshLine(l);
1979 }
1980 } else {
1981 memmove(l->buf+l->pos+clen,l->buf+l->pos,l->len-l->pos);
1982 memcpy(&l->buf[l->pos],cbuf,clen);
1983 l->pos+=clen;
1984 l->len+=clen;
1985 l->buf[l->len] = '\0';
1986 refreshLine(l);
1987 }
1988 }
1989 return 0;
1990}
1991
1992/* Move cursor on the left. */
1993inline void linenoiseEditMoveLeft(struct linenoiseState *l) {
1994 if (l->pos > 0) {
1995 l->pos -= unicodePrevGraphemeLen(l->buf, l->pos);
1996 refreshLine(l);
1997 }
1998}
1999
2000/* Move cursor on the right. */
2001inline void linenoiseEditMoveRight(struct linenoiseState *l) {
2002 if (l->pos != l->len) {
2003 l->pos += unicodeGraphemeLen(l->buf, l->len, l->pos);
2004 refreshLine(l);
2005 }
2006}
2007
2008/* Move cursor to the start of the line. */
2009inline void linenoiseEditMoveHome(struct linenoiseState *l) {
2010 if (l->pos != 0) {
2011 l->pos = 0;
2012 refreshLine(l);
2013 }
2014}
2015
2016/* Move cursor to the end of the line. */
2017inline void linenoiseEditMoveEnd(struct linenoiseState *l) {
2018 if (l->pos != l->len) {
2019 l->pos = l->len;
2020 refreshLine(l);
2021 }
2022}
2023
2024/* Substitute the currently edited line with the next or previous history
2025 * entry as specified by 'dir'. */
2026#define LINENOISE_HISTORY_NEXT 0
2027#define LINENOISE_HISTORY_PREV 1
2028inline void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
2029 if (history.size() > 1) {
2030 /* Update the current history entry before to
2031 * overwrite it with the next one. */
2032 history[history.size() - 1 - l->history_index] = l->buf;
2033 /* Show the new entry */
2034 l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
2035 if (l->history_index < 0) {
2036 l->history_index = 0;
2037 return;
2038 } else if (l->history_index >= (int)history.size()) {
2039 l->history_index = static_cast<int>(history.size())-1;
2040 return;
2041 }
2042 memset(l->buf, 0, l->buflen);
2043 strcpy(l->buf,history[history.size() - 1 - l->history_index].c_str());
2044 l->len = l->pos = static_cast<int>(strlen(l->buf));
2045 refreshLine(l);
2046 }
2047}
2048
2049/* Delete the character at the right of the cursor without altering the cursor
2050 * position. Basically this is what happens with the "Delete" keyboard key. */
2051inline void linenoiseEditDelete(struct linenoiseState *l) {
2052 if (l->len > 0 && l->pos < l->len) {
2053 int glen = unicodeGraphemeLen(l->buf,l->len,l->pos);
2054 memmove(l->buf+l->pos,l->buf+l->pos+glen,l->len-l->pos-glen);
2055 l->len-=glen;
2056 l->buf[l->len] = '\0';
2057 refreshLine(l);
2058 }
2059}
2060
2061/* Backspace implementation. */
2062inline void linenoiseEditBackspace(struct linenoiseState *l) {
2063 if (l->pos > 0 && l->len > 0) {
2064 int glen = unicodePrevGraphemeLen(l->buf,l->pos);
2065 memmove(l->buf+l->pos-glen,l->buf+l->pos,l->len-l->pos);
2066 l->pos-=glen;
2067 l->len-=glen;
2068 l->buf[l->len] = '\0';
2069 refreshLine(l);
2070 }
2071}
2072
2073/* Delete the previosu word, maintaining the cursor at the start of the
2074 * current word. */
2075inline void linenoiseEditDeletePrevWord(struct linenoiseState *l) {
2076 int old_pos = l->pos;
2077 int diff;
2078
2079 while (l->pos > 0 && l->buf[l->pos-1] == ' ')
2080 l->pos--;
2081 while (l->pos > 0 && l->buf[l->pos-1] != ' ')
2082 l->pos--;
2083 diff = old_pos - l->pos;
2084 memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
2085 l->len -= diff;
2086 refreshLine(l);
2087}
2088
2089/* This function is the core of the line editing capability of linenoise.
2090 * It expects 'fd' to be already in "raw mode" so that every key pressed
2091 * will be returned ASAP to read().
2092 *
2093 * The resulting string is put into 'buf' when the user type enter, or
2094 * when ctrl+d is typed.
2095 *
2096 * The function returns the length of the current buffer. */
2097inline int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, int buflen, const char *prompt)
2098{
2099 struct linenoiseState l;
2100
2101 /* Populate the linenoise state that we pass to functions implementing
2102 * specific editing functionalities. */
2103 l.ifd = stdin_fd;
2104 l.ofd = stdout_fd;
2105 l.buf = buf;
2106 l.buflen = buflen;
2107 l.prompt = prompt;
2108 l.oldcolpos = l.pos = 0;
2109 l.len = 0;
2110 l.cols = getColumns(stdin_fd, stdout_fd);
2111 l.maxrows = 0;
2112 l.history_index = 0;
2113
2114 /* Buffer starts empty. */
2115 l.buf[0] = '\0';
2116 l.buflen--; /* Make sure there is always space for the nulterm */
2117
2118 /* The latest history entry is always our current buffer, that
2119 * initially is just an empty string. */
2120 AddHistory("");
2121
2122 if (write(l.ofd,prompt, static_cast<int>(l.prompt.length())) == -1) return -1;
2123 while(1) {
2124 int c;
2125 char cbuf[4];
2126 int nread;
2127 char seq[3];
2128
2129#ifdef _WIN32
2130 nread = win32read(&c);
2131 if (nread == 1) {
2132 cbuf[0] = c;
2133 }
2134#else
2135 nread = unicodeReadUTF8Char(l.ifd,cbuf,&c);
2136#endif
2137 if (nread <= 0) return (int)l.len;
2138
2139 /* Only autocomplete when the callback is set. It returns < 0 when
2140 * there was an error reading from fd. Otherwise it will return the
2141 * character that should be handled next. */
2142 if (c == 9 && completionCallback != NULL) {
2143 nread = completeLine(&l,cbuf,&c);
2144 /* Return on errors */
2145 if (c < 0) return l.len;
2146 /* Read next character when 0 */
2147 if (c == 0) continue;
2148 }
2149
2150 switch(c) {
2151 case ENTER: /* enter */
2152 if (!history.empty()) history.pop_back();
2153 if (mlmode) linenoiseEditMoveEnd(&l);
2154 return (int)l.len;
2155 case CTRL_C: /* ctrl-c */
2156 errno = EAGAIN;
2157 return -1;
2158 case BACKSPACE: /* backspace */
2159 case 8: /* ctrl-h */
2160 linenoiseEditBackspace(&l);
2161 break;
2162 case CTRL_D: /* ctrl-d, remove char at right of cursor, or if the
2163 line is empty, act as end-of-file. */
2164 if (l.len > 0) {
2165 linenoiseEditDelete(&l);
2166 } else {
2167 history.pop_back();
2168 return -1;
2169 }
2170 break;
2171 case CTRL_T: /* ctrl-t, swaps current character with previous. */
2172 if (l.pos > 0 && l.pos < l.len) {
2173 char aux = buf[l.pos-1];
2174 buf[l.pos-1] = buf[l.pos];
2175 buf[l.pos] = aux;
2176 if (l.pos != l.len-1) l.pos++;
2177 refreshLine(&l);
2178 }
2179 break;
2180 case CTRL_B: /* ctrl-b */
2181 linenoiseEditMoveLeft(&l);
2182 break;
2183 case CTRL_F: /* ctrl-f */
2184 linenoiseEditMoveRight(&l);
2185 break;
2186 case CTRL_P: /* ctrl-p */
2187 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
2188 break;
2189 case CTRL_N: /* ctrl-n */
2190 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
2191 break;
2192 case ESC: /* escape sequence */
2193 /* Read the next two bytes representing the escape sequence.
2194 * Use two calls to handle slow terminals returning the two
2195 * chars at different times. */
2196 if (read(l.ifd,seq,1) == -1) break;
2197 if (read(l.ifd,seq+1,1) == -1) break;
2198
2199 /* ESC [ sequences. */
2200 if (seq[0] == '[') {
2201 if (seq[1] >= '0' && seq[1] <= '9') {
2202 /* Extended escape, read additional byte. */
2203 if (read(l.ifd,seq+2,1) == -1) break;
2204 if (seq[2] == '~') {
2205 switch(seq[1]) {
2206 case '3': /* Delete key. */
2207 linenoiseEditDelete(&l);
2208 break;
2209 }
2210 }
2211 } else {
2212 switch(seq[1]) {
2213 case 'A': /* Up */
2214 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
2215 break;
2216 case 'B': /* Down */
2217 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
2218 break;
2219 case 'C': /* Right */
2220 linenoiseEditMoveRight(&l);
2221 break;
2222 case 'D': /* Left */
2223 linenoiseEditMoveLeft(&l);
2224 break;
2225 case 'H': /* Home */
2226 linenoiseEditMoveHome(&l);
2227 break;
2228 case 'F': /* End*/
2229 linenoiseEditMoveEnd(&l);
2230 break;
2231 }
2232 }
2233 }
2234
2235 /* ESC O sequences. */
2236 else if (seq[0] == 'O') {
2237 switch(seq[1]) {
2238 case 'H': /* Home */
2239 linenoiseEditMoveHome(&l);
2240 break;
2241 case 'F': /* End*/
2242 linenoiseEditMoveEnd(&l);
2243 break;
2244 }
2245 }
2246 break;
2247 default:
2248 if (linenoiseEditInsert(&l,cbuf,nread)) return -1;
2249 break;
2250 case CTRL_U: /* Ctrl+u, delete the whole line. */
2251 buf[0] = '\0';
2252 l.pos = l.len = 0;
2253 refreshLine(&l);
2254 break;
2255 case CTRL_K: /* Ctrl+k, delete from current to end of line. */
2256 buf[l.pos] = '\0';
2257 l.len = l.pos;
2258 refreshLine(&l);
2259 break;
2260 case CTRL_A: /* Ctrl+a, go to the start of the line */
2261 linenoiseEditMoveHome(&l);
2262 break;
2263 case CTRL_E: /* ctrl+e, go to the end of the line */
2264 linenoiseEditMoveEnd(&l);
2265 break;
2266 case CTRL_L: /* ctrl+l, clear screen */
2267 linenoiseClearScreen();
2268 refreshLine(&l);
2269 break;
2270 case CTRL_W: /* ctrl+w, delete previous word */
2271 linenoiseEditDeletePrevWord(&l);
2272 break;
2273 }
2274 }
2275 return l.len;
2276}
2277
2278/* This function calls the line editing function linenoiseEdit() using
2279 * the STDIN file descriptor set in raw mode. */
2280inline bool linenoiseRaw(const char *prompt, std::string& line) {
2281 bool quit = false;
2282
2283 if (!isatty(STDIN_FILENO)) {
2284 /* Not a tty: read from file / pipe. */
2285 std::getline(std::cin, line);
2286 } else {
2287 /* Interactive editing. */
2288 if (enableRawMode(STDIN_FILENO) == false) {
2289 return quit;
2290 }
2291
2292 char buf[LINENOISE_MAX_LINE];
2293 auto count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, LINENOISE_MAX_LINE, prompt);
2294 if (count == -1) {
2295 quit = true;
2296 } else {
2297 line.assign(buf, count);
2298 }
2299
2300 disableRawMode(STDIN_FILENO);
2301 printf("\n");
2302 }
2303 return quit;
2304}
2305
2306/* The high level function that is the main API of the linenoise library.
2307 * This function checks if the terminal has basic capabilities, just checking
2308 * for a blacklist of stupid terminals, and later either calls the line
2309 * editing function or uses dummy fgets() so that you will be able to type
2310 * something even in the most desperate of the conditions. */
2311inline bool Readline(const char *prompt, std::string& line) {
2312 if (isUnsupportedTerm()) {
2313 printf("%s",prompt);
2314 fflush(stdout);
2315 std::getline(std::cin, line);
2316 return false;
2317 } else {
2318 return linenoiseRaw(prompt, line);
2319 }
2320}
2321
2322inline std::string Readline(const char *prompt, bool& quit) {
2323 std::string line;
2324 quit = Readline(prompt, line);
2325 return line;
2326}
2327
2328inline std::string Readline(const char *prompt) {
2329 bool quit; // dummy
2330 return Readline(prompt, quit);
2331}
2332
2333/* ================================ History ================================= */
2334
2335/* At exit we'll try to fix the terminal to the initial conditions. */
2336inline void linenoiseAtExit(void) {
2337 disableRawMode(STDIN_FILENO);
2338}
2339
2340/* This is the API call to add a new entry in the linenoise history.
2341 * It uses a fixed array of char pointers that are shifted (memmoved)
2342 * when the history max length is reached in order to remove the older
2343 * entry and make room for the new one, so it is not exactly suitable for huge
2344 * histories, but will work well for a few hundred of entries.
2345 *
2346 * Using a circular buffer is smarter, but a bit more complex to handle. */
2347inline bool AddHistory(const char* line) {
2348 if (history_max_len == 0) return false;
2349
2350 /* Don't add duplicated lines. */
2351 if (!history.empty() && history.back() == line) return false;
2352
2353 /* If we reached the max length, remove the older line. */
2354 if (history.size() == history_max_len) {
2355 history.erase(history.begin());
2356 }
2357 history.push_back(line);
2358
2359 return true;
2360}
2361
2362/* Set the maximum length for the history. This function can be called even
2363 * if there is already some history, the function will make sure to retain
2364 * just the latest 'len' elements if the new history length value is smaller
2365 * than the amount of items already inside the history. */
2366inline bool SetHistoryMaxLen(size_t len) {
2367 if (len < 1) return false;
2368 history_max_len = len;
2369 if (len < history.size()) {
2370 history.resize(len);
2371 }
2372 return true;
2373}
2374
2375/* Save the history in the specified file. On success *true* is returned
2376 * otherwise *false* is returned. */
2377inline bool SaveHistory(const char* path) {
2378 std::ofstream f(path); // TODO: need 'std::ios::binary'?
2379 if (!f) return false;
2380 for (const auto& h: history) {
2381 f << h << std::endl;
2382 }
2383 return true;
2384}
2385
2386/* Load the history from the specified file. If the file does not exist
2387 * zero is returned and no operation is performed.
2388 *
2389 * If the file exists and the operation succeeded *true* is returned, otherwise
2390 * on error *false* is returned. */
2391inline bool LoadHistory(const char* path) {
2392 std::ifstream f(path);
2393 if (!f) return false;
2394 std::string line;
2395 while (std::getline(f, line)) {
2396 AddHistory(line.c_str());
2397 }
2398 return true;
2399}
2400
2401inline const std::vector<std::string>& GetHistory() {
2402 return history;
2403}
2404
2405} // namespace linenoise
2406
2407#ifdef _WIN32
2408#undef isatty
2409#undef write
2410#undef read
2411#endif
2412
2413#endif /* __LINENOISE_HPP */