Correct PPTP server firewall rules chain.
[tomato/davidwu.git] / release / src / router / usbmodeswitch / jim / linenoise.c
blob4065d06a7bd1565edd2bc4b7acf17cd5c80585b8
1 /* linenoise.c -- guerrilla line editing library against the idea that a
2 * line editing lib needs to be 20,000 lines of C code.
4 * You can find the latest source code at:
6 * http://github.com/antirez/linenoise
8 * Does a number of crazy assumptions that happen to be true in 99.9999% of
9 * the 2010 UNIX computers around.
11 * ------------------------------------------------------------------------
13 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
14 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16 * All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met:
22 * * Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
25 * * Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 * ------------------------------------------------------------------------
43 * References:
44 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
45 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
47 * Todo list:
48 * - Win32 support
49 * - Save and load history containing newlines
51 * Bloat:
52 * - Completion?
54 * List of escape sequences used by this program, we do everything just
55 * a few sequences. In order to be so cheap we may have some
56 * flickering effect with some slow terminal, but the lesser sequences
57 * the more compatible.
59 * CHA (Cursor Horizontal Absolute)
60 * Sequence: ESC [ n G
61 * Effect: moves cursor to column n (1 based)
63 * EL (Erase Line)
64 * Sequence: ESC [ n K
65 * Effect: if n is 0 or missing, clear from cursor to end of line
66 * Effect: if n is 1, clear from beginning of line to cursor
67 * Effect: if n is 2, clear entire line
69 * CUF (CUrsor Forward)
70 * Sequence: ESC [ n C
71 * Effect: moves cursor forward of n chars
73 * The following are used to clear the screen: ESC [ H ESC [ 2 J
74 * This is actually composed of two sequences:
76 * cursorhome
77 * Sequence: ESC [ H
78 * Effect: moves the cursor to upper left corner
80 * ED2 (Clear entire screen)
81 * Sequence: ESC [ 2 J
82 * Effect: clear the whole screen
84 * == For highlighting control characters, we also use the following two ==
85 * SO (enter StandOut)
86 * Sequence: ESC [ 7 m
87 * Effect: Uses some standout mode such as reverse video
89 * SE (Standout End)
90 * Sequence: ESC [ 0 m
91 * Effect: Exit standout mode
93 * == Only used if TIOCGWINSZ fails ==
94 * DSR/CPR (Report cursor position)
95 * Sequence: ESC [ 6 n
96 * Effect: reports current cursor position as ESC [ NNN ; MMM R
99 #ifdef __MINGW32__
100 #include <windows.h>
101 #include <fcntl.h>
102 #define USE_WINCONSOLE
103 #else
104 #include <termios.h>
105 #include <sys/ioctl.h>
106 #include <sys/poll.h>
107 #define USE_TERMIOS
108 #endif
110 #include <unistd.h>
111 #include <stdlib.h>
112 #include <stdarg.h>
113 #include <stdio.h>
114 #include <errno.h>
115 #include <string.h>
116 #include <stdlib.h>
117 #include <sys/types.h>
118 #include <unistd.h>
120 #include "linenoise.h"
122 #include "jim-config.h"
123 #ifdef JIM_UTF8
124 #define USE_UTF8
125 #endif
126 #include "utf8.h"
128 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
129 #define LINENOISE_MAX_LINE 4096
131 #define ctrl(C) ((C) - '@')
133 /* Use -ve numbers here to co-exist with normal unicode chars */
134 enum {
135 SPECIAL_NONE,
136 SPECIAL_UP = -20,
137 SPECIAL_DOWN = -21,
138 SPECIAL_LEFT = -22,
139 SPECIAL_RIGHT = -23,
140 SPECIAL_DELETE = -24,
141 SPECIAL_HOME = -25,
142 SPECIAL_END = -26,
145 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
146 static int history_len = 0;
147 static char **history = NULL;
149 /* Structure to contain the status of the current (being edited) line */
150 struct current {
151 char *buf; /* Current buffer. Always null terminated */
152 int bufmax; /* Size of the buffer, including space for the null termination */
153 int len; /* Number of bytes in 'buf' */
154 int chars; /* Number of chars in 'buf' (utf-8 chars) */
155 int pos; /* Cursor position, measured in chars */
156 int cols; /* Size of the window, in chars */
157 const char *prompt;
158 #if defined(USE_TERMIOS)
159 int fd; /* Terminal fd */
160 #elif defined(USE_WINCONSOLE)
161 HANDLE outh; /* Console output handle */
162 HANDLE inh; /* Console input handle */
163 int rows; /* Screen rows */
164 int x; /* Current column during output */
165 int y; /* Current row */
166 #endif
169 static int fd_read(struct current *current);
170 static int getWindowSize(struct current *current);
172 void linenoiseHistoryFree(void) {
173 if (history) {
174 int j;
176 for (j = 0; j < history_len; j++)
177 free(history[j]);
178 free(history);
179 history = NULL;
183 #if defined(USE_TERMIOS)
184 static void linenoiseAtExit(void);
185 static struct termios orig_termios; /* in order to restore at exit */
186 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
187 static int atexit_registered = 0; /* register atexit just 1 time */
189 static const char *unsupported_term[] = {"dumb","cons25",NULL};
191 static int isUnsupportedTerm(void) {
192 char *term = getenv("TERM");
194 if (term) {
195 int j;
196 for (j = 0; unsupported_term[j]; j++) {
197 if (strcasecmp(term, unsupported_term[j]) == 0) {
198 return 1;
202 return 0;
205 static int enableRawMode(struct current *current) {
206 struct termios raw;
208 current->fd = STDIN_FILENO;
210 if (!isatty(current->fd) || isUnsupportedTerm() ||
211 tcgetattr(current->fd, &orig_termios) == -1) {
212 fatal:
213 errno = ENOTTY;
214 return -1;
217 if (!atexit_registered) {
218 atexit(linenoiseAtExit);
219 atexit_registered = 1;
222 raw = orig_termios; /* modify the original mode */
223 /* input modes: no break, no CR to NL, no parity check, no strip char,
224 * no start/stop output control. */
225 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
226 /* output modes - disable post processing */
227 raw.c_oflag &= ~(OPOST);
228 /* control modes - set 8 bit chars */
229 raw.c_cflag |= (CS8);
230 /* local modes - choing off, canonical off, no extended functions,
231 * no signal chars (^Z,^C) */
232 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
233 /* control chars - set return condition: min number of bytes and timer.
234 * We want read to return every single byte, without timeout. */
235 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
237 /* put terminal in raw mode after flushing */
238 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
239 goto fatal;
241 rawmode = 1;
243 current->cols = 0;
244 return 0;
247 static void disableRawMode(struct current *current) {
248 /* Don't even check the return value as it's too late. */
249 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
250 rawmode = 0;
253 /* At exit we'll try to fix the terminal to the initial conditions. */
254 static void linenoiseAtExit(void) {
255 if (rawmode) {
256 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
258 linenoiseHistoryFree();
261 /* gcc/glibc insists that we care about the return code of write! */
262 #define IGNORE_RC(EXPR) if (EXPR) {}
264 /* This is fdprintf() on some systems, but use a different
265 * name to avoid conflicts
267 static void fd_printf(int fd, const char *format, ...)
269 va_list args;
270 char buf[64];
271 int n;
273 va_start(args, format);
274 n = vsnprintf(buf, sizeof(buf), format, args);
275 va_end(args);
276 IGNORE_RC(write(fd, buf, n));
279 static void clearScreen(struct current *current)
281 fd_printf(current->fd, "\x1b[H\x1b[2J");
284 static void cursorToLeft(struct current *current)
286 fd_printf(current->fd, "\x1b[1G");
289 static int outputChars(struct current *current, const char *buf, int len)
291 return write(current->fd, buf, len);
294 static void outputControlChar(struct current *current, char ch)
296 fd_printf(current->fd, "\033[7m^%c\033[0m", ch);
299 static void eraseEol(struct current *current)
301 fd_printf(current->fd, "\x1b[0K");
304 static void setCursorPos(struct current *current, int x)
306 fd_printf(current->fd, "\x1b[1G\x1b[%dC", x);
310 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
312 * A timeout of -1 means to wait forever.
314 * Returns -1 if no char is received within the time or an error occurs.
316 static int fd_read_char(int fd, int timeout)
318 struct pollfd p;
319 unsigned char c;
321 p.fd = fd;
322 p.events = POLLIN;
324 if (poll(&p, 1, timeout) == 0) {
325 /* timeout */
326 return -1;
328 if (read(fd, &c, 1) != 1) {
329 return -1;
331 return c;
335 * Reads a complete utf-8 character
336 * and returns the unicode value, or -1 on error.
338 static int fd_read(struct current *current)
340 #ifdef USE_UTF8
341 char buf[4];
342 int n;
343 int i;
344 int c;
346 if (read(current->fd, &buf[0], 1) != 1) {
347 return -1;
349 n = utf8_charlen(buf[0]);
350 if (n < 1 || n > 3) {
351 return -1;
353 for (i = 1; i < n; i++) {
354 if (read(current->fd, &buf[i], 1) != 1) {
355 return -1;
358 buf[n] = 0;
359 /* decode and return the character */
360 utf8_tounicode(buf, &c);
361 return c;
362 #else
363 return fd_read_char(current->fd, -1);
364 #endif
367 static int getWindowSize(struct current *current)
369 struct winsize ws;
371 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
372 current->cols = ws.ws_col;
373 return 0;
376 /* Failed to query the window size. Perhaps we are on a serial terminal.
377 * Try to query the width by sending the cursor as far to the right
378 * and reading back the cursor position.
379 * Note that this is only done once per call to linenoise rather than
380 * every time the line is refreshed for efficiency reasons.
382 if (current->cols == 0) {
383 current->cols = 80;
385 /* Move cursor far right and report cursor position */
386 fd_printf(current->fd, "\x1b[999G" "\x1b[6n");
388 /* Parse the response: ESC [ rows ; cols R */
389 if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
390 int n = 0;
391 while (1) {
392 int ch = fd_read_char(current->fd, 100);
393 if (ch == ';') {
394 /* Ignore rows */
395 n = 0;
397 else if (ch == 'R') {
398 /* Got cols */
399 if (n != 0 && n < 1000) {
400 current->cols = n;
402 break;
404 else if (ch >= 0 && ch <= '9') {
405 n = n * 10 + ch - '0';
407 else {
408 break;
413 return 0;
417 * If escape (27) was received, reads subsequent
418 * chars to determine if this is a known special key.
420 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
422 * If no additional char is received within a short time,
423 * 27 is returned.
425 static int check_special(int fd)
427 int c = fd_read_char(fd, 50);
428 int c2;
430 if (c < 0) {
431 return 27;
434 c2 = fd_read_char(fd, 50);
435 if (c2 < 0) {
436 return c2;
438 if (c == '[' || c == 'O') {
439 /* Potential arrow key */
440 switch (c2) {
441 case 'A':
442 return SPECIAL_UP;
443 case 'B':
444 return SPECIAL_DOWN;
445 case 'C':
446 return SPECIAL_RIGHT;
447 case 'D':
448 return SPECIAL_LEFT;
449 case 'F':
450 return SPECIAL_END;
451 case 'H':
452 return SPECIAL_HOME;
455 if (c == '[' && c2 >= '1' && c2 <= '6') {
456 /* extended escape */
457 int c3 = fd_read_char(fd, 50);
458 if (c2 == '3' && c3 == '~') {
459 /* delete char under cursor */
460 return SPECIAL_DELETE;
462 while (c3 != -1 && c3 != '~') {
463 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
464 c3 = fd_read_char(fd, 50);
468 return SPECIAL_NONE;
470 #elif defined(USE_WINCONSOLE)
472 static DWORD orig_consolemode = 0;
474 static int enableRawMode(struct current *current) {
475 DWORD n;
476 INPUT_RECORD irec;
478 current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
479 current->inh = GetStdHandle(STD_INPUT_HANDLE);
481 if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
482 return -1;
484 if (getWindowSize(current) != 0) {
485 return -1;
487 if (GetConsoleMode(current->inh, &orig_consolemode)) {
488 SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
490 return 0;
493 static void disableRawMode(struct current *current)
495 SetConsoleMode(current->inh, orig_consolemode);
498 static void clearScreen(struct current *current)
500 COORD topleft = { 0, 0 };
501 DWORD n;
503 FillConsoleOutputCharacter(current->outh, ' ',
504 current->cols * current->rows, topleft, &n);
505 FillConsoleOutputAttribute(current->outh,
506 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
507 current->cols * current->rows, topleft, &n);
508 SetConsoleCursorPosition(current->outh, topleft);
511 static void cursorToLeft(struct current *current)
513 COORD pos = { 0, current->y };
514 DWORD n;
516 FillConsoleOutputAttribute(current->outh,
517 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
518 current->x = 0;
521 static int outputChars(struct current *current, const char *buf, int len)
523 COORD pos = { current->x, current->y };
524 WriteConsoleOutputCharacter(current->outh, buf, len, pos, 0);
525 current->x += len;
526 return 0;
529 static void outputControlChar(struct current *current, char ch)
531 COORD pos = { current->x, current->y };
532 DWORD n;
534 FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
535 outputChars(current, "^", 1);
536 outputChars(current, &ch, 1);
539 static void eraseEol(struct current *current)
541 COORD pos = { current->x, current->y };
542 DWORD n;
544 FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
547 static void setCursorPos(struct current *current, int x)
549 COORD pos = { x, current->y };
551 SetConsoleCursorPosition(current->outh, pos);
552 current->x = x;
555 static int fd_read(struct current *current)
557 while (1) {
558 INPUT_RECORD irec;
559 DWORD n;
560 if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
561 break;
563 if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
564 break;
566 if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
567 KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
568 if (k->dwControlKeyState & ENHANCED_KEY) {
569 switch (k->wVirtualKeyCode) {
570 case VK_LEFT:
571 return SPECIAL_LEFT;
572 case VK_RIGHT:
573 return SPECIAL_RIGHT;
574 case VK_UP:
575 return SPECIAL_UP;
576 case VK_DOWN:
577 return SPECIAL_DOWN;
578 case VK_DELETE:
579 return SPECIAL_DELETE;
580 case VK_HOME:
581 return SPECIAL_HOME;
582 case VK_END:
583 return SPECIAL_END;
586 /* Note that control characters are already translated in AsciiChar */
587 else {
588 #ifdef USE_UTF8
589 return k->uChar.UnicodeChar;
590 #else
591 return k->uChar.AsciiChar;
592 #endif
596 return -1;
599 static int getWindowSize(struct current *current)
601 CONSOLE_SCREEN_BUFFER_INFO info;
602 if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
603 return -1;
605 current->cols = info.dwSize.X;
606 current->rows = info.dwSize.Y;
607 if (current->cols <= 0 || current->rows <= 0) {
608 current->cols = 80;
609 return -1;
611 current->y = info.dwCursorPosition.Y;
612 current->x = info.dwCursorPosition.X;
613 return 0;
615 #endif
617 static int utf8_getchars(char *buf, int c)
619 #ifdef USE_UTF8
620 return utf8_fromunicode(buf, c);
621 #else
622 *buf = c;
623 return 1;
624 #endif
628 * Returns the unicode character at the given offset,
629 * or -1 if none.
631 static int get_char(struct current *current, int pos)
633 if (pos >= 0 && pos < current->chars) {
634 int c;
635 int i = utf8_index(current->buf, pos);
636 (void)utf8_tounicode(current->buf + i, &c);
637 return c;
639 return -1;
642 static void refreshLine(const char *prompt, struct current *current)
644 int plen;
645 int pchars;
646 int backup = 0;
647 int i;
648 const char *buf = current->buf;
649 int chars = current->chars;
650 int pos = current->pos;
651 int b;
652 int ch;
653 int n;
655 /* Should intercept SIGWINCH. For now, just get the size every time */
656 getWindowSize(current);
658 plen = strlen(prompt);
659 pchars = utf8_strlen(prompt, plen);
661 /* Account for a line which is too long to fit in the window.
662 * Note that control chars require an extra column
665 /* How many cols are required to the left of 'pos'?
666 * The prompt, plus one extra for each control char
668 n = pchars + utf8_strlen(buf, current->len);
669 b = 0;
670 for (i = 0; i < pos; i++) {
671 b += utf8_tounicode(buf + b, &ch);
672 if (ch < ' ') {
673 n++;
677 /* If too many are need, strip chars off the front of 'buf'
678 * until it fits. Note that if the current char is a control character,
679 * we need one extra col.
681 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
682 n++;
685 while (n >= current->cols) {
686 b = utf8_tounicode(buf, &ch);
687 if (ch < ' ') {
688 n--;
690 n--;
691 buf += b;
692 pos--;
693 chars--;
696 /* Cursor to left edge, then the prompt */
697 cursorToLeft(current);
698 outputChars(current, prompt, plen);
700 /* Now the current buffer content */
702 /* Need special handling for control characters.
703 * If we hit 'cols', stop.
705 b = 0; /* unwritted bytes */
706 n = 0; /* How many control chars were written */
707 for (i = 0; i < chars; i++) {
708 int ch;
709 int w = utf8_tounicode(buf + b, &ch);
710 if (ch < ' ') {
711 n++;
713 if (pchars + i + n >= current->cols) {
714 break;
716 if (ch < ' ') {
717 /* A control character, so write the buffer so far */
718 outputChars(current, buf, b);
719 buf += b + w;
720 b = 0;
721 outputControlChar(current, ch + '@');
722 if (i < pos) {
723 backup++;
726 else {
727 b += w;
730 outputChars(current, buf, b);
732 /* Erase to right, move cursor to original position */
733 eraseEol(current);
734 setCursorPos(current, pos + pchars + backup);
737 static void set_current(struct current *current, const char *str)
739 strncpy(current->buf, str, current->bufmax);
740 current->buf[current->bufmax - 1] = 0;
741 current->len = strlen(current->buf);
742 current->pos = current->chars = utf8_strlen(current->buf, current->len);
745 static int has_room(struct current *current, int bytes)
747 return current->len + bytes < current->bufmax - 1;
751 * Removes the char at 'pos'.
753 * Returns 1 if the line needs to be refreshed, 2 if not
754 * and 0 if nothing was removed
756 static int remove_char(struct current *current, int pos)
758 if (pos >= 0 && pos < current->chars) {
759 int p1, p2;
760 int ret = 1;
761 p1 = utf8_index(current->buf, pos);
762 p2 = p1 + utf8_index(current->buf + p1, 1);
764 #ifdef USE_TERMIOS
765 /* optimise remove char in the case of removing the last char */
766 if (current->pos == pos + 1 && current->pos == current->chars) {
767 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
768 ret = 2;
769 fd_printf(current->fd, "\b \b");
772 #endif
774 /* Move the null char too */
775 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
776 current->len -= (p2 - p1);
777 current->chars--;
779 if (current->pos > pos) {
780 current->pos--;
782 return ret;
784 return 0;
788 * Insert 'ch' at position 'pos'
790 * Returns 1 if the line needs to be refreshed, 2 if not
791 * and 0 if nothing was inserted (no room)
793 static int insert_char(struct current *current, int pos, int ch)
795 char buf[3];
796 int n = utf8_getchars(buf, ch);
798 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
799 int p1, p2;
800 int ret = 1;
801 p1 = utf8_index(current->buf, pos);
802 p2 = p1 + n;
804 #ifdef USE_TERMIOS
805 /* optimise the case where adding a single char to the end and no scrolling is needed */
806 if (current->pos == pos && current->chars == pos) {
807 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
808 IGNORE_RC(write(current->fd, buf, n));
809 ret = 2;
812 #endif
814 memmove(current->buf + p2, current->buf + p1, current->len - p1);
815 memcpy(current->buf + p1, buf, n);
816 current->len += n;
818 current->chars++;
819 if (current->pos >= pos) {
820 current->pos++;
822 return ret;
824 return 0;
828 * Returns 0 if no chars were removed or non-zero otherwise.
830 static int remove_chars(struct current *current, int pos, int n)
832 int removed = 0;
833 while (n-- && remove_char(current, pos)) {
834 removed++;
836 return removed;
839 #ifndef NO_COMPLETION
840 static linenoiseCompletionCallback *completionCallback = NULL;
842 static void beep() {
843 #ifdef USE_TERMIOS
844 fprintf(stderr, "\x7");
845 fflush(stderr);
846 #endif
849 static void freeCompletions(linenoiseCompletions *lc) {
850 size_t i;
851 for (i = 0; i < lc->len; i++)
852 free(lc->cvec[i]);
853 free(lc->cvec);
856 static int completeLine(struct current *current) {
857 linenoiseCompletions lc = { 0, NULL };
858 int c = 0;
860 completionCallback(current->buf,&lc);
861 if (lc.len == 0) {
862 beep();
863 } else {
864 size_t stop = 0, i = 0;
866 while(!stop) {
867 /* Show completion or original buffer */
868 if (i < lc.len) {
869 struct current tmp = *current;
870 tmp.buf = lc.cvec[i];
871 tmp.pos = tmp.len = strlen(tmp.buf);
872 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
873 refreshLine(current->prompt, &tmp);
874 } else {
875 refreshLine(current->prompt, current);
878 c = fd_read(current);
879 if (c == -1) {
880 break;
883 switch(c) {
884 case '\t': /* tab */
885 i = (i+1) % (lc.len+1);
886 if (i == lc.len) beep();
887 break;
888 case 27: /* escape */
889 /* Re-show original buffer */
890 if (i < lc.len) {
891 refreshLine(current->prompt, current);
893 stop = 1;
894 break;
895 default:
896 /* Update buffer and return */
897 if (i < lc.len) {
898 set_current(current,lc.cvec[i]);
900 stop = 1;
901 break;
906 freeCompletions(&lc);
907 return c; /* Return last read character */
910 /* Register a callback function to be called for tab-completion. */
911 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
912 completionCallback = fn;
915 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
916 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
917 lc->cvec[lc->len++] = strdup(str);
920 #endif
922 static int linenoisePrompt(struct current *current) {
923 int history_index = 0;
925 /* The latest history entry is always our current buffer, that
926 * initially is just an empty string. */
927 linenoiseHistoryAdd("");
929 set_current(current, "");
930 refreshLine(current->prompt, current);
932 while(1) {
933 int dir = -1;
934 int c = fd_read(current);
936 #ifndef NO_COMPLETION
937 /* Only autocomplete when the callback is set. It returns < 0 when
938 * there was an error reading from fd. Otherwise it will return the
939 * character that should be handled next. */
940 if (c == 9 && completionCallback != NULL) {
941 c = completeLine(current);
942 /* Return on errors */
943 if (c < 0) return current->len;
944 /* Read next character when 0 */
945 if (c == 0) continue;
947 #endif
949 process_char:
950 if (c == -1) return current->len;
951 #ifdef USE_TERMIOS
952 if (c == 27) { /* escape sequence */
953 c = check_special(current->fd);
955 #endif
956 switch(c) {
957 case '\r': /* enter */
958 history_len--;
959 free(history[history_len]);
960 return current->len;
961 case ctrl('C'): /* ctrl-c */
962 errno = EAGAIN;
963 return -1;
964 case 127: /* backspace */
965 case ctrl('H'):
966 if (remove_char(current, current->pos - 1) == 1) {
967 refreshLine(current->prompt, current);
969 break;
970 case ctrl('D'): /* ctrl-d */
971 if (current->len == 0) {
972 /* Empty line, so EOF */
973 history_len--;
974 free(history[history_len]);
975 return -1;
977 /* Otherwise delete char to right of cursor */
978 if (remove_char(current, current->pos)) {
979 refreshLine(current->prompt, current);
981 break;
982 case ctrl('W'): /* ctrl-w */
983 /* eat any spaces on the left */
985 int pos = current->pos;
986 while (pos > 0 && get_char(current, pos - 1) == ' ') {
987 pos--;
990 /* now eat any non-spaces on the left */
991 while (pos > 0 && get_char(current, pos - 1) != ' ') {
992 pos--;
995 if (remove_chars(current, pos, current->pos - pos)) {
996 refreshLine(current->prompt, current);
999 break;
1000 case ctrl('R'): /* ctrl-r */
1002 /* Display the reverse-i-search prompt and process chars */
1003 char rbuf[50];
1004 char rprompt[80];
1005 int rchars = 0;
1006 int rlen = 0;
1007 int searchpos = history_len - 1;
1009 rbuf[0] = 0;
1010 while (1) {
1011 int n = 0;
1012 const char *p = NULL;
1013 int skipsame = 0;
1014 int searchdir = -1;
1016 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1017 refreshLine(rprompt, current);
1018 c = fd_read(current);
1019 if (c == ctrl('H') || c == 127) {
1020 if (rchars) {
1021 int p = utf8_index(rbuf, --rchars);
1022 rbuf[p] = 0;
1023 rlen = strlen(rbuf);
1025 continue;
1027 #ifdef USE_TERMIOS
1028 if (c == 27) {
1029 c = check_special(current->fd);
1031 #endif
1032 if (c == ctrl('P') || c == SPECIAL_UP) {
1033 /* Search for the previous (earlier) match */
1034 if (searchpos > 0) {
1035 searchpos--;
1037 skipsame = 1;
1039 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1040 /* Search for the next (later) match */
1041 if (searchpos < history_len) {
1042 searchpos++;
1044 searchdir = 1;
1045 skipsame = 1;
1047 else if (c >= ' ') {
1048 if (rlen >= (int)sizeof(rbuf) + 3) {
1049 continue;
1052 n = utf8_getchars(rbuf + rlen, c);
1053 rlen += n;
1054 rchars++;
1055 rbuf[rlen] = 0;
1057 /* Adding a new char resets the search location */
1058 searchpos = history_len - 1;
1060 else {
1061 /* Exit from incremental search mode */
1062 break;
1065 /* Now search through the history for a match */
1066 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1067 p = strstr(history[searchpos], rbuf);
1068 if (p) {
1069 /* Found a match */
1070 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1071 /* But it is identical, so skip it */
1072 continue;
1074 /* Copy the matching line and set the cursor position */
1075 set_current(current,history[searchpos]);
1076 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1077 break;
1080 if (!p && n) {
1081 /* No match, so don't add it */
1082 rchars--;
1083 rlen -= n;
1084 rbuf[rlen] = 0;
1087 if (c == ctrl('G') || c == ctrl('C')) {
1088 /* ctrl-g terminates the search with no effect */
1089 set_current(current, "");
1090 c = 0;
1092 else if (c == ctrl('J')) {
1093 /* ctrl-j terminates the search leaving the buffer in place */
1094 c = 0;
1096 /* Go process the char normally */
1097 refreshLine(current->prompt, current);
1098 goto process_char;
1100 break;
1101 case ctrl('T'): /* ctrl-t */
1102 if (current->pos > 0 && current->pos < current->chars) {
1103 c = get_char(current, current->pos);
1104 remove_char(current, current->pos);
1105 insert_char(current, current->pos - 1, c);
1106 refreshLine(current->prompt, current);
1108 break;
1109 case ctrl('V'): /* ctrl-v */
1110 if (has_room(current, 3)) {
1111 /* Insert the ^V first */
1112 if (insert_char(current, current->pos, c)) {
1113 refreshLine(current->prompt, current);
1114 /* Now wait for the next char. Can insert anything except \0 */
1115 c = fd_read(current);
1117 /* Remove the ^V first */
1118 remove_char(current, current->pos - 1);
1119 if (c != -1) {
1120 /* Insert the actual char */
1121 insert_char(current, current->pos, c);
1123 refreshLine(current->prompt, current);
1126 break;
1127 case ctrl('B'):
1128 case SPECIAL_LEFT:
1129 if (current->pos > 0) {
1130 current->pos--;
1131 refreshLine(current->prompt, current);
1133 break;
1134 case ctrl('F'):
1135 case SPECIAL_RIGHT:
1136 if (current->pos < current->chars) {
1137 current->pos++;
1138 refreshLine(current->prompt, current);
1140 break;
1141 case ctrl('P'):
1142 case SPECIAL_UP:
1143 dir = 1;
1144 case ctrl('N'):
1145 case SPECIAL_DOWN:
1146 if (history_len > 1) {
1147 /* Update the current history entry before to
1148 * overwrite it with tne next one. */
1149 free(history[history_len-1-history_index]);
1150 history[history_len-1-history_index] = strdup(current->buf);
1151 /* Show the new entry */
1152 history_index += dir;
1153 if (history_index < 0) {
1154 history_index = 0;
1155 break;
1156 } else if (history_index >= history_len) {
1157 history_index = history_len-1;
1158 break;
1160 set_current(current, history[history_len-1-history_index]);
1161 refreshLine(current->prompt, current);
1163 break;
1165 case SPECIAL_DELETE:
1166 if (remove_char(current, current->pos) == 1) {
1167 refreshLine(current->prompt, current);
1169 break;
1170 case SPECIAL_HOME:
1171 current->pos = 0;
1172 refreshLine(current->prompt, current);
1173 break;
1174 case SPECIAL_END:
1175 current->pos = current->chars;
1176 refreshLine(current->prompt, current);
1177 break;
1178 default:
1179 /* Only tab is allowed without ^V */
1180 if (c == '\t' || c >= ' ') {
1181 if (insert_char(current, current->pos, c) == 1) {
1182 refreshLine(current->prompt, current);
1185 break;
1186 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1187 if (remove_chars(current, 0, current->pos)) {
1188 refreshLine(current->prompt, current);
1190 break;
1191 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1192 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1193 refreshLine(current->prompt, current);
1195 break;
1196 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1197 current->pos = 0;
1198 refreshLine(current->prompt, current);
1199 break;
1200 case ctrl('E'): /* ctrl+e, go to the end of the line */
1201 current->pos = current->chars;
1202 refreshLine(current->prompt, current);
1203 break;
1204 case ctrl('L'): /* Ctrl+L, clear screen */
1205 /* clear screen */
1206 clearScreen(current);
1207 /* Force recalc of window size for serial terminals */
1208 current->cols = 0;
1209 refreshLine(current->prompt, current);
1210 break;
1213 return current->len;
1216 char *linenoise(const char *prompt)
1218 int count;
1219 struct current current;
1220 char buf[LINENOISE_MAX_LINE];
1222 if (enableRawMode(&current) == -1) {
1223 printf("%s", prompt);
1224 fflush(stdout);
1225 if (fgets(buf, sizeof(buf), stdin) == NULL) {
1226 return NULL;
1228 count = strlen(buf);
1229 if (count && buf[count-1] == '\n') {
1230 count--;
1231 buf[count] = '\0';
1234 else
1236 current.buf = buf;
1237 current.bufmax = sizeof(buf);
1238 current.len = 0;
1239 current.chars = 0;
1240 current.pos = 0;
1241 current.prompt = prompt;
1243 count = linenoisePrompt(&current);
1244 disableRawMode(&current);
1245 printf("\n");
1246 if (count == -1) {
1247 return NULL;
1250 return strdup(buf);
1253 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1254 int linenoiseHistoryAdd(const char *line) {
1255 char *linecopy;
1257 if (history_max_len == 0) return 0;
1258 if (history == NULL) {
1259 history = (char**)malloc(sizeof(char*)*history_max_len);
1260 if (history == NULL) return 0;
1261 memset(history,0,(sizeof(char*)*history_max_len));
1263 linecopy = strdup(line);
1264 if (!linecopy) return 0;
1265 if (history_len == history_max_len) {
1266 free(history[0]);
1267 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1268 history_len--;
1270 history[history_len] = linecopy;
1271 history_len++;
1272 return 1;
1275 int linenoiseHistorySetMaxLen(int len) {
1276 char **newHistory;
1278 if (len < 1) return 0;
1279 if (history) {
1280 int tocopy = history_len;
1282 newHistory = (char**)malloc(sizeof(char*)*len);
1283 if (newHistory == NULL) return 0;
1284 if (len < tocopy) tocopy = len;
1285 memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1286 free(history);
1287 history = newHistory;
1289 history_max_len = len;
1290 if (history_len > history_max_len)
1291 history_len = history_max_len;
1292 return 1;
1295 /* Save the history in the specified file. On success 0 is returned
1296 * otherwise -1 is returned. */
1297 int linenoiseHistorySave(const char *filename) {
1298 FILE *fp = fopen(filename,"w");
1299 int j;
1301 if (fp == NULL) return -1;
1302 for (j = 0; j < history_len; j++) {
1303 const char *str = history[j];
1304 /* Need to encode backslash, nl and cr */
1305 while (*str) {
1306 if (*str == '\\') {
1307 fputs("\\\\", fp);
1309 else if (*str == '\n') {
1310 fputs("\\n", fp);
1312 else if (*str == '\r') {
1313 fputs("\\r", fp);
1315 else {
1316 fputc(*str, fp);
1318 str++;
1320 fputc('\n', fp);
1323 fclose(fp);
1324 return 0;
1327 /* Load the history from the specified file. If the file does not exist
1328 * zero is returned and no operation is performed.
1330 * If the file exists and the operation succeeded 0 is returned, otherwise
1331 * on error -1 is returned. */
1332 int linenoiseHistoryLoad(const char *filename) {
1333 FILE *fp = fopen(filename,"r");
1334 char buf[LINENOISE_MAX_LINE];
1336 if (fp == NULL) return -1;
1338 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1339 char *src, *dest;
1341 /* Decode backslash escaped values */
1342 for (src = dest = buf; *src; src++) {
1343 char ch = *src;
1345 if (ch == '\\') {
1346 src++;
1347 if (*src == 'n') {
1348 ch = '\n';
1350 else if (*src == 'r') {
1351 ch = '\r';
1352 } else {
1353 ch = *src;
1356 *dest++ = ch;
1358 /* Remove trailing newline */
1359 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1360 dest--;
1362 *dest = 0;
1364 linenoiseHistoryAdd(buf);
1366 fclose(fp);
1367 return 0;
1370 /* Provide access to the history buffer.
1372 * If 'len' is not NULL, the length is stored in *len.
1374 char **linenoiseHistory(int *len) {
1375 if (len) {
1376 *len = history_len;
1378 return history;